Cryo Explorer Ethereum Mainnet

Address Contract Partially Verified

Address 0x6067487ee98B6A830cc3E5E7F57Dc194044D1F1D
Balance 0 ETH
Nonce 1
Code Size 17570 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

17570 bytes
0x60e080604052600436101561001357600080fd5b600090813560e01c90816301ffc9a714611b2d575080630513436214611a575780631ad7b12714611a05578063209164cb1461189d57806328e9d35b146117d15780632c9354671461178f578063313dab201461177157806333016eb71461146a5780633929a4af14611443578063403755f5146113a957806345a1b92c1461138b5780635fb5689614611370578063633dd1451461134957806364c4540914611320578063653a34e2146112f957806368215fcb146110d257806371201a0e146110ae578063715018a61461104957806374f7cd4e14610d9057806379ba509714610d0b578063816b44fd14610ce2578063833be38414610c9d57806385c9c05114610c455780638b05c53814610c1f5780638da5cb5b14610bf85780638e805a7c14610b9d578063947b43f314610b7f5780639aa695e114610b405780639d81359314610b1c578063a717639c14610af6578063ab2da61014610a4b578063b115e4df14610a06578063ba29281c146109df578063d5472a9c146109b8578063db1992b31461099a578063ddbe3c1d14610841578063df3851e314610823578063e30c3978146107fa578063e37750e5146107d1578063eb4af04514610799578063f1127f1a146103cd578063f1887684146103af578063f22bb62e14610350578063f2fde38b146102e3578063f7cc662d1461029e5763fca2086b1461021b57600080fd5b3461029b57602036600319011261029b5760043563ffffffff811680820361029757610245611e8c565b80156102885761271010610279576009805463ffffffff60601b191660609290921b63ffffffff60601b1691909117905580f35b632b0039c760e21b8252600482fd5b63af458c0760e01b8352600483fd5b8280fd5b80fd5b503461029b578060031936011261029b576040517f0000000000000000000000004e3dbd6333e649af13c823daacdd14f8507ecbc56001600160a01b03168152602090f35b503461029b57602036600319011261029b576102fd611bd0565b610305611e8c565b600180546001600160a01b0319166001600160a01b0392831690811790915582549091167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e227008380a380f35b503461029b57602036600319011261029b5760043563ffffffff81168082036102975761037b611e8c565b80156102885761271010610279576009805463ffffffff60801b191660809290921b63ffffffff60801b1691909117905580f35b503461029b578060031936011261029b576020600854604051908152f35b503461029b57602036600319011261029b576004356001600160401b038111610702576103fe903690600401611ba0565b8015801561078f575b610780576040516370a0823160e01b81523060048201529160208360248160008051602061444d8339815191525afa928315610775578493610741575b5073d605a87187563c94c577a6e57e4a36ec8433b9ae3b1561073d579083916040519163024ff33160e21b835280604484016040600486015252606483019190845b818110610711575050508180849230602483015203818373d605a87187563c94c577a6e57e4a36ec8433b9ae5af18015610706576106ed575b50506040516370a0823160e01b81523060048201529060208260248160008051602061444d8339815191525afa801561069a5783906106b4575b6105039250611c64565b80156106a5576105226105279163ffffffff60095460201c1690611ede565b6140f0565b60405163175c979560e31b81526366f04d10600482015260208160248173bbf25ca275325ef4682851a12bd8e9aa714da2f45af490811561069a578391610658575b5063ffffffff600191160163ffffffff81116106445763ffffffff1663ffffffff610309820416908115159182610639575b826105f3575b5050156105df576105b490600454613c53565b6004555b7f68e2c7e09a4a7d4fed2367771ceaa06623fb2e3f8b90065b2473b3f9752f99688180a180f35b6105eb90600354613c53565b6003556105b8565b6103099192500263ffffffff81169081036106255760030163ffffffff81116106255763ffffffff16101538806105a1565b634e487b7160e01b84526011600452602484fd5b60058110925061059b565b634e487b7160e01b83526011600452602483fd5b90506020813d602011610692575b8161067360209383611c18565b810103126102975763ffffffff61068b600192611db2565b9150610569565b3d9150610666565b6040513d85823e3d90fd5b6312d37ee560e31b8252600482fd5b506020823d6020116106e5575b816106ce60209383611c18565b810103126106e05761050391516104f9565b600080fd5b3d91506106c1565b816106f791611c18565b6107025781386104bf565b5080fd5b6040513d84823e3d90fd5b9193945091602080600192838060a01b0361072b88611c50565b16815201940191019186949392610486565b8380fd5b9092506020813d60201161076d575b8161075d60209383611c18565b810103126106e057519138610444565b3d9150610750565b6040513d86823e3d90fd5b632b0039c760e21b8352600483fd5b5060648111610407565b503461029b57602036600319011261029b576004356107b6611e8c565b80156107c25760085580f35b63af458c0760e01b8252600482fd5b503461029b57602036600319011261029b576004356107ee611e8c565b80156107c25760065580f35b503461029b578060031936011261029b576001546040516001600160a01b039091168152602090f35b503461029b578060031936011261029b576020600654604051908152f35b503461029b5761085036611b82565b91333b15801590610990575b61098157610868611d4e565b63ffffffff42161061097257600354801561096357338652600a60205260ff60408720541615610954579261091a926108c89261092296956006549081811160001461094c5750955b6108c363ffffffff6009541688611ede565b611f06565b9060075467ffffffff000000004260201b169067ffffffff000000001916176007556109157f0000000000000000000000004e3dbd6333e649af13c823daacdd14f8507ecbc59182613aab565b613aff565b600354611c64565b6003557f8eb6cb374f3c3afaeacaeb762e4b89e530913c32c88c07c6f8cad6833f047e2a8180a180f35b9050956108b1565b632b0039c760e21b8652600486fd5b63d9b9141960e01b8652600486fd5b63b0782df760e01b8552600485fd5b632b0039c760e21b8552600485fd5b503233141561085c565b503461029b578060031936011261029b576020600554604051908152f35b503461029b578060031936011261029b57602063ffffffff60095460801c16604051908152f35b503461029b578060031936011261029b57602063ffffffff60025460c01c16604051908152f35b503461029b578060031936011261029b576040517f0000000000000000000000002d28cfb0a0928ca0d29fae64275569f503fc0acc6001600160a01b03168152602090f35b503461029b578060031936011261029b576040516370a0823160e01b815230600482015260208160248160008051602061444d8339815191525afa918215610aea5791610ab6575b6020610aae610aa58460035490611c64565b60045490611c64565b604051908152f35b90506020813d602011610ae2575b81610ad160209383611c18565b810103126106e05751610aae610a93565b3d9150610ac4565b604051903d90823e3d90fd5b503461029b578060031936011261029b57602063ffffffff600754821c16604051908152f35b503461029b578060031936011261029b57602063ffffffff60095416604051908152f35b503461029b57602036600319011261029b5760209060ff906040906001600160a01b03610b6b611bd0565b168152600a84522054166040519015158152f35b503461029b578060031936011261029b576020600454604051908152f35b503461029b57602036600319011261029b57610bb7611bd0565b610bbf611e8c565b6001600160a01b03168015610be9576bffffffffffffffffffffffff60a01b600254161760025580f35b63d92e233d60e01b8252600482fd5b503461029b578060031936011261029b57546040516001600160a01b039091168152602090f35b503461029b578060031936011261029b57602063ffffffff600954821c16604051908152f35b503461029b57602036600319011261029b5760043563ffffffff81168082036102975761271090610c74611e8c565b116102795767ffffffff000000006009549160201b169067ffffffff0000000019161760095580f35b503461029b57602036600319011261029b5760043563ffffffff811680910361070257610cc8611e8c565b61271081116102795763ffffffff19600954161760095580f35b503461029b578060031936011261029b576002546040516001600160a01b039091168152602090f35b503461029b578060031936011261029b57600154336001600160a01b0390911603610d7d57600180546001600160a01b0319908116909155815433918116821783556001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08380a380f35b63118cdaa760e01b815233600452602490fd5b503461029b578060031936011261029b57610da9613fac565b90801561103a57604051636eb1769f60e11b81523060048201527336e5a8105f000029d4b3b99d0c3d0e24aaa52adf602482015283919060208160448160008051602061444d8339815191525afa90811561069a578391611003575b5081610e1091613c53565b828060405192602084019063095ea7b360e01b82527336e5a8105f000029d4b3b99d0c3d0e24aaa52adf6024860152604485015260448452610e53606485611c18565b8351908260008051602061444d8339815191525af1610e7061411c565b81610fcc575b5080610fb4575b15610f54575b507336e5a8105f000029d4b3b99d0c3d0e24aaa52adf3b1561070257604051630547902760e21b81526001600160c01b0390911660048201528181602481837336e5a8105f000029d4b3b99d0c3d0e24aaa52adf5af1801561070657610f3f575b505060025490610f0563ffffffff60a01b9163ffffffff8460a01c16611cce565b60a01b169063ffffffff60a01b1916176002557f88844d6865965563acd5b25451a33d44f4600e733b6c5afa2a2827a79c6354818180a180f35b81610f4991611c18565b610702578138610ee4565b610fae90610f9a60405163095ea7b360e01b60208201527336e5a8105f000029d4b3b99d0c3d0e24aaa52adf602482015285604482015260448152610f9a606482611c18565b60008051602061444d83398151915261407a565b38610e83565b5060008051602061444d8339815191523b1515610e7d565b8051801592508215610fe1575b505038610e76565b819250906020918101031261073d576020610ffc910161406d565b3880610fd9565b9250506020823d602011611032575b8161101f60209383611c18565b810103126106e057905183919081610e05565b3d9150611012565b632fc532ad60e11b8352600483fd5b503461029b578060031936011261029b57611062611e8c565b600180546001600160a01b03199081169091558154908116825581906001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a380f35b503461029b578060031936011261029b57602063ffffffff60075416604051908152f35b503461029b57602036600319011261029b576004356001600160401b03811161070257366023820112156107025780600401359061110f82611c39565b9161111d6040519384611c18565b8083526024602084019160051b830101913683116112f557602401905b8282106112dd57505050805161116861115282611c39565b916111606040519384611c18565b808352611c39565b602082019290601f19013684376040938451916111858684611c18565b600183526020830190601f198701368337825b8151811015611296576001600160a01b036111b38284611d9e565b51166111be86611d6b565b5287519063367b97ef60e11b825281602481016020600483015287518091526044820190869088905b808210611271575050509080602092038173d605a87187563c94c577a6e57e4a36ec8433b9ae5afa8015611267578590611231575b6001925061122a8289611d9e565b5201611198565b509060203d8111611260575b6112478183611c18565b6020826000928101031261029b5750906001915161121c565b503d61123d565b89513d87823e3d90fd5b82516001600160a01b03168452869450602093840193909201916001909101906111e7565b505050905092919092825193849360208501916020865251809252840192915b8181106112c4575050500390f35b82518452859450602093840193909201916001016112b6565b602080916112ea84611c50565b81520191019061113a565b8480fd5b503461029b578060031936011261029b57602063ffffffff60025460a01c16604051908152f35b503461029b57602036600319011261029b5760043561133d611e8c565b80156107c25760055580f35b503461029b578060031936011261029b57602063ffffffff60095460401c16604051908152f35b503461029b578060031936011261029b576020610aae611d4e565b503461029b57604036600319011261029b576113a5611bd0565b5080f35b503461029b57604036600319011261029b576004356001600160401b038111610702576113da903690600401611ba0565b6024359182151580930361073d576113f3929192611e8c565b60ff849216915b8381101561143f57600581901b8201356001600160a01b038116919082900361143b57908552600a60205260408520805460ff1916841790556001016113fa565b8580fd5b8480f35b503461029b578060031936011261029b57602063ffffffff60095460601c16604051908152f35b503461029b57602036600319011261029b576004356001600160401b0381116107025761149b903690600401611ba0565b9081156107805760405191633791e82360e11b835230600484015260406024840152602083806114cf604482018587611ce8565b03817336e5a8105f000029d4b3b99d0c3d0e24aaa52adf5afa92831561077557849361173d575b50821561172e579083917336e5a8105f000029d4b3b99d0c3d0e24aaa52adf3b1561029757604051630147c1f960e71b8152602060048201529183918391829161154591602484019190611ce8565b0381837336e5a8105f000029d4b3b99d0c3d0e24aaa52adf5af1801561070657611719575b505060405163a9059cbb60e01b60208201526001600160a01b037f0000000000000000000000004e3dbd6333e649af13c823daacdd14f8507ecbc516602482015260019190911c60448201526115eb906115d181606481015b03601f198101835282611c18565b73bfde5ac4f5adb419a931a5bf64b0f3bb5a623d0661407a565b6040516370a0823160e01b815230600482015260208160248173bfde5ac4f5adb419a931a5bf64b0f3bb5a623d065afa9081156107065782916116e6575b5060408161163961166b93613c60565b8151635cacc5fb60e11b8152630edf6c0060048201526001600160a01b03909116602482015291829081906044820190565b03818573d605a87187563c94c577a6e57e4a36ec8433b9ae5af18015610706576116b8575b507fa35dd573ba89f5b4572ac75031f4eb81cffe1e7d86f25d6b82011c8c70d9b42c8180a180f35b6116d99060403d6040116116df575b6116d18183611c18565b810190611c87565b50611690565b503d6116c7565b90506020813d602011611711575b8161170160209383611c18565b810103126106e057516040611629565b3d91506116f4565b8161172391611c18565b61070257813861156a565b6312d37ee560e31b8452600484fd5b9092506020813d602011611769575b8161175960209383611c18565b810103126106e0575191386114f6565b3d915061174c565b503461029b578060031936011261029b576020600354604051908152f35b503461029b57602036600319011261029b5760043563ffffffff8116809103610702576117ba611e8c565b80156107c25763ffffffff19600754161760075580f35b503461029b578060031936011261029b576117ea613b8b565b90801561103a5760408161163961180093613c60565b03818673d605a87187563c94c577a6e57e4a36ec8433b9ae5af1801561069a5761187f575b506002549061184563ffffffff60c01b9163ffffffff8460c01c16611cce565b60c01b169063ffffffff60c01b1916176002557f20af3ebfa4072e782df60fec636554cc396357f543596cce54e8ed62403108698180a180f35b6118979060403d6040116116df576116d18183611c18565b50611825565b503461029b576118ac36611b82565b91333b158015906119fb575b610981576118c4611d4e565b63ffffffff42161061097257600454801561096357338652600a60205260ff604087205416156109545791859391611918936006549081811160001461094c5750956108c363ffffffff6009541688611ede565b6007805467ffffffff0000000019164260201b67ffffffff00000000161790559091907f0000000000000000000000004e3dbd6333e649af13c823daacdd14f8507ecbc56119668482613aab565b6119708282613aff565b6001600160a01b031692833b15610297576044908360405195869485936348d24d6f60e01b8552600485015260248401525af1801561069a576119e5575b506119bb90600454611c64565b6004557f8eb6cb374f3c3afaeacaeb762e4b89e530913c32c88c07c6f8cad6833f047e2a8180a180f35b916119f4816119bb9394611c18565b91906119ae565b50323314156118b8565b503461029b57602036600319011261029b5760043563ffffffff811680820361029757611a30611e8c565b156107c25763ffffffff60401b6009549160401b169063ffffffff60401b19161760095580f35b503461029b578060031936011261029b57611a7c63ffffffff60025460a01c16611df5565b6040516370a0823160e01b815230600482015260208160248160008051602061444d8339815191525afa928315610aea578093611af0575b505063ffffffff611acd610aa560209460035490611c64565b911615159081611ae3575b506040519015158152f35b9050600554111538611ad8565b9092506020833d602011611b25575b81611b0c60209383611c18565b8101031261029b575090519063ffffffff611acd611ab4565b3d9150611aff565b9050346107025760203660031901126107025760043563ffffffff60e01b811680910361029757602092506301ffc9a760e01b8114908115611b71575b5015158152f35b6311686e4b60e21b14905038611b6a565b60809060031901126106e05760043590602435906044359060643590565b9181601f840112156106e0578235916001600160401b0383116106e0576020808501948460051b0101116106e057565b600435906001600160a01b03821682036106e057565b61010081019081106001600160401b03821117611c0257604052565b634e487b7160e01b600052604160045260246000fd5b90601f801991011681019081106001600160401b03821117611c0257604052565b6001600160401b038111611c025760051b60200190565b35906001600160a01b03821682036106e057565b91908203918211611c7157565b634e487b7160e01b600052601160045260246000fd5b91908260409103126106e05781516bffffffffffffffffffffffff811681036106e05760209092015171ffffffffffffffffffffffffffffffffffff811681036106e05790565b9063ffffffff8091169116019063ffffffff8211611c7157565b916020908281520191906000905b808210611d035750505090565b9091928335906001600160401b0382168092036106e057602081600193829352019401920190611cf6565b8115611d38570490565b634e487b7160e01b600052601260045260246000fd5b63ffffffff611d67600754828082169160201c16611cce565b1690565b805115611d785760200190565b634e487b7160e01b600052603260045260246000fd5b805160011015611d785760400190565b8051821015611d785760209160051b010190565b519063ffffffff821682036106e057565b63ffffffff16612710039063ffffffff8211611c7157565b9063ffffffff8091169116039063ffffffff8211611c7157565b60405163175c979560e31b815263673f671060048201529060208260248173bbf25ca275325ef4682851a12bd8e9aa714da2f45af48015611e8057600090611e45575b611e429250611ddb565b90565b506020823d602011611e78575b81611e5f60209383611c18565b810103126106e057611e73611e4292611db2565b611e38565b3d9150611e52565b6040513d6000823e3d90fd5b6000546001600160a01b03163303611ea057565b63118cdaa760e01b6000523360045260246000fd5b908160041b9180830460101490151715611c7157565b81810292918115918404141715611c7157565b620186a0611ef563ffffffff611e42941683611ecb565b0490611f018233613b52565b611c64565b949392919460a0526064611f1b60a051611eb5565b0492611f3684600254600060c05260018060a01b0316613b52565b60a051602a81810291801590830490911417156132835760c05160095460408051633850c7bd60e01b815292979082901c63ffffffff9081169691946064900493919260601c1690731e90b67149e688dfb95fd73acacd8adefd16d88d9060e081600481855afa8015612d6c5760c051918291613a1b575b5061ffff169081156134b65761ffff60019116019061ffff82116132835760405163252c09d760e01b815261ffff928316919091069091166004820152608081602481855afa908115612d6c5760c0519060c051926139f6575b50901561399a575b6120209063ffffffff4216611ddb565b8763ffffffff821610613992575b5063ffffffff8716156133f3576040516060979061204c8982611c18565b600281526020810190601f198a0136833763ffffffff831661206d82611d6b565b5260c05161207a82611d8e565b5260405193849163883bdbfd60e01b83526024830190602060048501525180915260448301939060c0515b81811061397357505050818060c0519403915afa918215612d6c5760c0519060c0519361385f575b506120e46120da82611d8e565b5160060b91611d6b565b5160060b900391667fffffffffffff198312667fffffffffffff841317613283576001600160a01b0361211682611d8e565b5116906001600160a01b039061212b90611d6b565b51169003906001600160a01b0382116132835763ffffffff811660060b156130325760001963ffffffff821660060b14667fffffffffffff198460060b14166132835763ffffffff811660060b8360060b0560020b9260c0518160060b12908161383f575b50613829575b63ffffffff166001600160a01b038082026001600160c01b03169190910490036132835760201b640100000000600160c01b0316156130325760020b60c0515060c0518112600014613823578060c05103905b620d89e8821161326a576001821615613811576001600160881b036ffffcb933bd6fad37aa2d162d1a5940015b1691600281166137f5575b600481166137d9575b600881166137bd575b601081166137a1575b60208116613785575b60408116613769575b6080811661374d575b6101008116613731575b6102008116613715575b61040081166136f9575b61080081166136dd575b61100081166136c1575b61200081166136a5575b6140008116613689575b618000811661366d575b620100008116613651575b620200008116613636575b62040000811661361b575b6208000016613603575b60c051126135f4575b63ffffffff81166135ec5760c051905b6001600160801b038581169260209290921c60ff92909216919091016001600160a01b03169081116135c4579163ffffffff61234761234e936123318661271097611ecb565b8d15612fe857906123419161439c565b92611dc3565b1690611ecb565b0481106135b557866040519161236383611be6565b60008051602061444d83398151915283526020830172f116ac0c304c570daaa68fa6c30a86a04b5c5f815260408401612710815288850130815262ffffff60808701928a845260a088019489865260c0890196875260e089019788526123c88a613e0f565b60405163414bf38960e01b815298516001600160a01b0390811660048b01529051811660248a0152905191909116604488015290518116606487015290516084860152905160a4850152905160c484015290511660e4820152602081610104818a73e592427a0aece92de3edee1f18e0157c058615645af1968715610aea5796613581575b50606461245987611eb5565b0460805272f116ac0c304c570daaa68fa6c30a86a04b5c5f3b15612d9257604051630852cd8d60e31b8152608051600482015260c051909290836024818372f116ac0c304c570daaa68fa6c30a86a04b5c5f5af1908115612d6c576124ca93611f019261356f575b5060a051611c64565b60095460408051633850c7bd60e01b815298929163ffffffff608082901c811692732c83c54c5612bfd62a78124d4a0ea001278a689c92901c1660e08b600481855afa8015612d6c5760c0519b8c916134e0575b5061ffff169a8b156134b65761ffff600191160161ffff81116132835761ffff60009c816040519363252c09d760e01b85521606166004820152608081602481865afa908115612d6c5760c0519060c05192613491575b509015613425575b61258d9063ffffffff4216611ddb565b8163ffffffff82161061341d575b5063ffffffff8116156133f3576040516125b58882611c18565b600281526020810190601f19890136833763ffffffff83166125d682611d6b565b5260c0516125e382611d8e565b5260405193849163883bdbfd60e01b83526024830190602060048501525180915260448301939060c0515b8181106133d457505050818060c0519403915afa918215612d6c5760c0519060c051936132c0575b506126436120da82611d8e565b5160060b900391667fffffffffffff198312667fffffffffffff841317613283576001600160a01b0361267582611d8e565b5116906001600160a01b039061268a90611d6b565b51169003906001600160a01b0382116132835763ffffffff811660060b9260060b831561303257667fffffffffffff1981146000198514166132835783810560020b9360c051821291826132b1575b505061329b575b63ffffffff166001600160a01b038082026001600160c01b03169190910490036132835760201b640100000000600160c01b0316156130325760020b60c0515060c051811260001461327d578060c05103905b620d89e8821161326a576001821615613258576001600160881b036ffffcb933bd6fad37aa2d162d1a5940015b16916002811661323c575b60048116613220575b60088116613204575b601081166131e8575b602081166131cc575b604081166131b0575b60808116613194575b6101008116613178575b610200811661315c575b6104008116613140575b6108008116613124575b6110008116613108575b61200081166130ec575b61400081166130d0575b61800081166130b4575b620100008116613098575b62020000811661307d575b620400008116613062575b620800001661304a575b60c05112613023575b6127109161288b9163ffffffff906123479080831661301b5760c051905b6001600160801b038881169260209290921c60ff92909216919091016001600160a01b0316908111612ff6578061287991611ecb565b60c05115612fe857906123419161439c565b048210612fd5576040519161289f83611be6565b60008051602061444d833981519152835260208301732614f29c39de46468a921fd0b41fdd99a01f2edf815260408401612710815286850130815262ffffff608087019288845260a088019487865260c0890196875261290760e08a019860c0518a52613e0f565b60405163414bf38960e01b815298516001600160a01b0390811660048b01529051811660248a0152905191909116604488015290518116606487015290516084860152905160a4850152905160c484015290511660e482015260c051602090829061010490829073e592427a0aece92de3edee1f18e0157c058615645af1908115612d6c5760c05191612f9f575b5060646129a182611eb5565b604051636eb1769f60e11b81523060048201819052602482015291900490602081604481732614f29c39de46468a921fd0b41fdd99a01f2edf5afa8015612d6c5760c0518391612f69575b6129f69250613c53565b60405163095ea7b360e01b6020820190815230602483015260448083019390935291815290612a26606483611c18565b60c0518251909182919082732614f29c39de46468a921fd0b41fdd99a01f2edf5af1612a5061411c565b81612f32575b5080612f14575b15612eda575b50732614f29c39de46468a921fd0b41fdd99a01f2edf3b15612d925760405163067e7faf60e31b81523060048201526024810182905260c080516044830152600860648301527f0000000000000000000000002d28cfb0a0928ca0d29fae64275569f503fc0acc6001600160a01b03166084830152518160a48183732614f29c39de46468a921fd0b41fdd99a01f2edf5af18015612d6c57612ec1575b50612b0a91611c64565b8315612eae57604051612b1d8482611c18565b600281526020810193601f1901368537732614f29c39de46468a921fd0b41fdd99a01f2edf612b4b82611d6b565b5273e9a53c43a0b58706e67341c4055de861e29ee943612b6a82611d8e565b52604051636eb1769f60e11b8152306004820152737a250d5630b4cf539739df2c5dacb4c659f2488d6024820152602081604481732614f29c39de46468a921fd0b41fdd99a01f2edf5afa8015612d6c5760c0518491612e74575b612bcf9250613c53565b60405163095ea7b360e01b60208201908152737a250d5630b4cf539739df2c5dacb4c659f2488d602483015260448083019390935291815290612c13606483611c18565b60c0518251909182919082732614f29c39de46468a921fd0b41fdd99a01f2edf5af1612c3d61411c565b81612e3d575b5080612e1f575b15612db7575b50737a250d5630b4cf539739df2c5dacb4c659f2488d3b15612d925760405194635c11d79560e01b865260a48601926004870152602486015260a060448601525180915260c48401929060c0515b818110612d98575050503060648401526084830152818060c05192038160c051737a250d5630b4cf539739df2c5dacb4c659f2488d5af18015612d6c57612d79575b506040516370a0823160e01b815230600482015260208160248173e9a53c43a0b58706e67341c4055de861e29ee9435afa938415612d6c5760c05194612d33575b5050608051612d2f91611c64565b9190565b909193506020823d602011612d64575b81612d5060209383611c18565b8101031261029b57505191612d2f38612d21565b3d9150612d43565b6040513d60c051823e3d90fd5b60c051612d8591611c18565b60c051612d925738612ce0565b60c05180fd5b82516001600160a01b0316855260209485019490920191600101612c9e565b612e1990612dff60405163095ea7b360e01b6020820152737a250d5630b4cf539739df2c5dacb4c659f2488d602482015260c051604482015260448152612dff606482611c18565b732614f29c39de46468a921fd0b41fdd99a01f2edf61407a565b38612c50565b50732614f29c39de46468a921fd0b41fdd99a01f2edf3b1515612c4a565b8051801592508215612e52575b505038612c43565b8192509060209181010312612d92576020612e6d910161406d565b3880612e4a565b50506020813d602011612ea6575b81612e8f60209383611c18565b81010312612ea25782612bcf9151612bc5565b8880fd5b3d9150612e82565b63af458c0760e01b60c05152600460c051fd5b60c051612ecd91611c18565b60c051612d925738612b00565b612f0e90612dff60405163095ea7b360e01b602082015230602482015260c051604482015260448152612dff606482611c18565b38612a63565b50732614f29c39de46468a921fd0b41fdd99a01f2edf3b1515612a5d565b8051801592508215612f47575b505038612a56565b8192509060209181010312612d92576020612f62910161406d565b3880612f3f565b50506020813d602011612f97575b81612f8460209383611c18565b81010312612ea257816129f691516129ec565b3d9150612f77565b90506020813d602011612fcd575b81612fba60209383611c18565b81010312612fc9575138612995565b8680fd5b3d9150612fad565b63431653f160e11b60c05152600460c051fd5b612ff191614317565b612341565b80613000916141c7565b60c051156130125790612341916142c8565b612ff191614226565b600190612843565b80156130325760001904612825565b634e487b7160e01b60c051526012600452602460c051fd5b906b048a170391f7dc42444e8fa20260801c9061281c565b6d2216e584f5fa1ea926041bedfe9890920260801c91612812565b916e5d6af8dedb81196699c329225ee6040260801c91612807565b916f09aa508b5b7a84e1c677de54f3e99bc90260801c916127fc565b916f31be135f97d08fd981231505542fcfa60260801c916127f1565b916f70d869a156d2a1b890bb3df62baf32f70260801c916127e7565b916fa9f746462d870fdf8a65dc1f90e061e50260801c916127dd565b916fd097f3bdfd2022b8845ad8f792aa58250260801c916127d3565b916fe7159475a2c29b7443b29c7fa6e889d90260801c916127c9565b916ff3392b0822b70005940c7a398e4b70f30260801c916127bf565b916ff987a7253ac413176f2b074cf7815e540260801c916127b5565b916ffcbe86c7900a88aedcffc83b479aa3a40260801c916127ab565b916ffe5dee046a99a2a811c461f1969c30530260801c916127a1565b916fff2ea16466c96a3843ec78b326b528610260801c91612798565b916fff973b41fa98c081472e6896dfb254c00260801c9161278f565b916fffcb9843d60f6159c9db58835c9266440260801c91612786565b916fffe5caca7e10e4e61c3624eaa0941cd00260801c9161277d565b916ffff2e50f5f656932ef12357cf3c7fdcc0260801c91612774565b916ffff97272373d413259a46990580e213a0260801c9161276b565b6001600160881b03600160801b612760565b6315e4079d60e11b60c05152600460c051fd5b80612733565b634e487b7160e01b60c051526011600452602460c051fd5b91627fffff1981146132835760001901916126e0565b0760060b1515905038806126d9565b9250503d8060c051843e6132d48184611c18565b820191604081840312612d925780516001600160401b038111612d925781019083601f83011215612d925781519161330b83611c39565b926133196040519485611c18565b80845260208085019160051b83010191868311612d9257602001905b8282106133bc575050506020810151906001600160401b038211612d9257019280601f85011215612d9257835161336b81611c39565b946133796040519687611c18565b81865260208087019260051b820101928311612d9257602001905b8282106133a45750505038612636565b602080916133b18461415b565b815201910190613394565b602080916133c98461417e565b815201910190613335565b825163ffffffff1686526020958601958895509092019160010161260e565b60405162461bcd60e51b8152602060048201526002602482015261042560f41b6044820152606490fd5b90503861259b565b5060405163252c09d760e01b815260c0516004820152608081602481865afa8015612d6c5761258d9160c0519161345f575b50905061257d565b613481915060803d60801161348a575b6134798183611c18565b81019061418c565b50505038613457565b503d61346f565b90506134ac915060803d60801161348a576134798183611c18565b9291505038612575565b60405162461bcd60e51b81526020600482015260026024820152614e4960f01b6044820152606490fd5b9b505060e08b3d60e011613567575b816134fc60e09383611c18565b81010312612d925761350d8b61415b565b5060208b01518060020b03612d925761352860408c0161416f565b9a61353488820161416f565b9b6135416080830161416f565b5060a082015160ff811603612d925761355f60c061ffff930161406d565b509b9061251e565b3d91506134ef565b60c05161357b91611c18565b386124c1565b9095506020813d6020116135ad575b8161359d60209383611c18565b81010312612d925751943861244d565b3d9150613590565b63431653f160e11b8752600487fd5b61234e9199509163ffffffff6123476123416135e386612710976141c7565b60c0519d614226565b6001906122eb565b801561303257600019046122db565b906b048a170391f7dc42444e8fa20260801c906122d2565b6d2216e584f5fa1ea926041bedfe9890920260801c916122c8565b916e5d6af8dedb81196699c329225ee6040260801c916122bd565b916f09aa508b5b7a84e1c677de54f3e99bc90260801c916122b2565b916f31be135f97d08fd981231505542fcfa60260801c916122a7565b916f70d869a156d2a1b890bb3df62baf32f70260801c9161229d565b916fa9f746462d870fdf8a65dc1f90e061e50260801c91612293565b916fd097f3bdfd2022b8845ad8f792aa58250260801c91612289565b916fe7159475a2c29b7443b29c7fa6e889d90260801c9161227f565b916ff3392b0822b70005940c7a398e4b70f30260801c91612275565b916ff987a7253ac413176f2b074cf7815e540260801c9161226b565b916ffcbe86c7900a88aedcffc83b479aa3a40260801c91612261565b916ffe5dee046a99a2a811c461f1969c30530260801c91612257565b916fff2ea16466c96a3843ec78b326b528610260801c9161224e565b916fff973b41fa98c081472e6896dfb254c00260801c91612245565b916fffcb9843d60f6159c9db58835c9266440260801c9161223c565b916fffe5caca7e10e4e61c3624eaa0941cd00260801c91612233565b916ffff2e50f5f656932ef12357cf3c7fdcc0260801c9161222a565b916ffff97272373d413259a46990580e213a0260801c91612221565b6001600160881b03600160801b612216565b806121e9565b91627fffff198114613283576000190191612196565b905060c0515063ffffffff821660060b9060060b0760060b151538612190565b9250503d8060c051843e6138738184611c18565b820191604081840312612d925780516001600160401b038111612d925781019083601f83011215612d92578151916138aa83611c39565b926138b86040519485611c18565b80845260208085019160051b83010191868311612d9257602001905b82821061395b575050506020810151906001600160401b038211612d9257019280601f85011215612d9257835161390a81611c39565b946139186040519687611c18565b81865260208087019260051b820101928311612d9257602001905b82821061394357505050386120cd565b602080916139508461415b565b815201910190613933565b602080916139688461417e565b8152019101906138d4565b825163ffffffff168652602095860195889550909201916001016120a5565b96503861202e565b5060405163252c09d760e01b815260c0516004820152608081602481855afa8015612d6c576120209160c051916139d4575b509050612010565b6139ed915060803d60801161348a576134798183611c18565b505050386139cc565b9050613a11915060803d60801161348a576134798183611c18565b9291505038612008565b91505060e0813d60e011613aa3575b81613a3760e09383611c18565b81010312612d9257613a488161415b565b5060208101518060020b03612d9257613a636040820161416f565b90613a706060820161416f565b91613a7d6080830161416f565b5060a082015160ff811603612d9257613a9b60c061ffff930161406d565b509190611fae565b3d9150613a2a565b60405163a9059cbb60e01b60208201526001600160a01b0390911660248201526044810191909152613afd90613ae481606481016115c3565b72f116ac0c304c570daaa68fa6c30a86a04b5c5f61407a565b565b60405163a9059cbb60e01b60208201526001600160a01b0390911660248201526044810191909152613afd90613b3881606481016115c3565b73e9a53c43a0b58706e67341c4055de861e29ee94361407a565b60405163a9059cbb60e01b60208201526001600160a01b0390911660248201526044810191909152613afd90610f9a81606481016115c3565b63673f67104210613c4257613baa63ffffffff60025460c01c16611df5565b9063ffffffff821615613c3a576040516370a0823160e01b815230600482015260208160248173bfde5ac4f5adb419a931a5bf64b0f3bb5a623d065afa908115611e8057600091613c08575b50600854811015612d2f575060009190565b906020823d602011613c32575b81613c2260209383611c18565b8101031261029b57505138613bf6565b3d9150613c15565b600091508190565b636396a26f60e01b60005260046000fd5b91908201809211611c7157565b604051636eb1769f60e11b815230600482015273d605a87187563c94c577a6e57e4a36ec8433b9ae60248201529060208260448173bfde5ac4f5adb419a931a5bf64b0f3bb5a623d065afa8015611e8057600090613ddb575b613cc39250613c53565b60008060405192602084019063095ea7b360e01b825273d605a87187563c94c577a6e57e4a36ec8433b9ae6024860152604485015260448452613d07606485611c18565b8351908273bfde5ac4f5adb419a931a5bf64b0f3bb5a623d065af1613d2a61411c565b81613da4575b5080613d86575b15613d3f5750565b613afd906115d160405163095ea7b360e01b602082015273d605a87187563c94c577a6e57e4a36ec8433b9ae602482015260006044820152604481526115d1606482611c18565b5073bfde5ac4f5adb419a931a5bf64b0f3bb5a623d063b1515613d37565b8051801592508215613db9575b505038613d30565b81925090602091810103126106e0576020613dd4910161406d565b3880613db1565b506020823d602011613e07575b81613df560209383611c18565b810103126106e057613cc39151613cb9565b3d9150613de8565b604051636eb1769f60e11b815230600482015273e592427a0aece92de3edee1f18e0157c0586156460248201529060208260448160008051602061444d8339815191525afa8015611e8057600090613f78575b613e6c9250613c53565b60008060405192602084019063095ea7b360e01b825273e592427a0aece92de3edee1f18e0157c058615646024860152604485015260448452613eb0606485611c18565b8351908260008051602061444d8339815191525af1613ecd61411c565b81613f41575b5080613f29575b15613ee25750565b613afd90610f9a60405163095ea7b360e01b602082015273e592427a0aece92de3edee1f18e0157c0586156460248201526000604482015260448152610f9a606482611c18565b5060008051602061444d8339815191523b1515613eda565b8051801592508215613f56575b505038613ed3565b81925090602091810103126106e0576020613f71910161406d565b3880613f4e565b506020823d602011613fa4575b81613f9260209383611c18565b810103126106e057613e6c9151613e62565b3d9150613f85565b63673f67104210613c4257613fcb63ffffffff60025460a01c16611df5565b9063ffffffff821615613c3a576040516370a0823160e01b815230600482015260208160248160008051602061444d8339815191525afa908115611e8057600091614039575b50610aa56140229160035490611c64565b600554809110614030579190565b50600091508190565b90506020813d602011614065575b8161405460209383611c18565b810103126106e05751610aa5614011565b3d9150614047565b519081151582036106e057565b6000806140a39260018060a01b03169360208151910182865af161409c61411c565b90836143eb565b80519081151591826140cd575b50506140b95750565b635274afe760e01b60005260045260246000fd5b81925090602091810103126106e05760206140e8910161406d565b1538806140b0565b6372f165904263ffffffff161015611e4257604681029080820460461490151715611c71576064900490565b3d15614156573d906001600160401b038211611c02576040519161414a601f8201601f191660200184611c18565b82523d6000602084013e565b606090565b51906001600160a01b03821682036106e057565b519061ffff821682036106e057565b51908160060b82036106e057565b91908260809103126106e0576141a182611db2565b916141ae6020820161417e565b91611e4260606141c06040850161415b565b930161406d565b818102916000916000198282099284808510940393808503941461421b5783600160401b111561420c575090600160401b910990828211900360c01b910360401c1790565b63227bc15360e01b8152600490fd5b925050505060401c90565b90608082901b9060001983600160801b09928280851094039380850394146142bc57838211156142ab578190600160801b09816000038216809204600281600302188082026002030280820260020302808202600203028082026002030280820260020302809102600203029360018380600003040190848311900302920304170290565b63227bc15360e01b60005260046000fd5b5090611e429250611d2e565b600090828102926000198183099284808510940393808503941461430c57600160801b84101561420c5750600160801b910990828211900360801b910360801c1790565b925050505060801c90565b9060c082901b9060001983600160c01b09928280851094039380850394146142bc57838211156142ab578190600160c01b09816000038216809204600281600302188082026002030280820260020302808202600203028082026002030280820260020302809102600203029360018380600003040190848311900302920304170290565b60009082810292600019818309928480851094039380850394146143e057600160c01b84101561420c5750600160c01b910990828211900360401b910360c01c1790565b925050505060c01c90565b90614411575080511561440057805190602001fd5b630a12f52160e11b60005260046000fd5b81511580614443575b614422575090565b639996b31560e01b60009081526001600160a01b0391909116600452602490fd5b50803b1561441a56fe000000000000000000000000f19308f923582a6f7c465e5ce7a9dc1bec6665b1a26469706673582212201e61217d017939db987212284ca5f9e24b50b6efa0a5f7f111d306feb1afef3464736f6c634300081a0033

Verified Source Code Partial Match

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
        external;

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}
SafeERC20.sol 118 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

        bytes memory returndata = address(token).functionCall(data);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

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

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
    }
}
Address.sol 159 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert AddressInsufficientBalance(address(this));
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

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

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

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

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

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert FailedInnerCall();
        }
    }
}
Context.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

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

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

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface 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[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
Math.sol 416 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

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

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

    }

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

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

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

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

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

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

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

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            return a / b;
        }

        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

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

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

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

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
        }
    }

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

pragma solidity ^0.8.20;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

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

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

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}
Strings.sol 94 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;

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

    /**
     * @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;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), 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 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));
    }
}
IUniswapV2Router01.sol 121 lines
pragma solidity >=0.6.2;

interface IUniswapV2Router01 {
    function factory() external pure returns (address);
    function WETH() external pure returns (address);

    function addLiquidity(
        address tokenA,
        address tokenB,
        uint256 amountADesired,
        uint256 amountBDesired,
        uint256 amountAMin,
        uint256 amountBMin,
        address to,
        uint256 deadline
    ) external returns (uint256 amountA, uint256 amountB, uint256 liquidity);
    function addLiquidityETH(
        address token,
        uint256 amountTokenDesired,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline
    ) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);
    function removeLiquidity(
        address tokenA,
        address tokenB,
        uint256 liquidity,
        uint256 amountAMin,
        uint256 amountBMin,
        address to,
        uint256 deadline
    ) external returns (uint256 amountA, uint256 amountB);
    function removeLiquidityETH(
        address token,
        uint256 liquidity,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline
    ) external returns (uint256 amountToken, uint256 amountETH);
    function removeLiquidityWithPermit(
        address tokenA,
        address tokenB,
        uint256 liquidity,
        uint256 amountAMin,
        uint256 amountBMin,
        address to,
        uint256 deadline,
        bool approveMax,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (uint256 amountA, uint256 amountB);
    function removeLiquidityETHWithPermit(
        address token,
        uint256 liquidity,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline,
        bool approveMax,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (uint256 amountToken, uint256 amountETH);
    function swapExactTokensForTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
    function swapTokensForExactTokens(
        uint256 amountOut,
        uint256 amountInMax,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
    function swapExactETHForTokens(uint256 amountOutMin, address[] calldata path, address to, uint256 deadline)
        external
        payable
        returns (uint256[] memory amounts);
    function swapTokensForExactETH(
        uint256 amountOut,
        uint256 amountInMax,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
    function swapExactTokensForETH(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
    function swapETHForExactTokens(uint256 amountOut, address[] calldata path, address to, uint256 deadline)
        external
        payable
        returns (uint256[] memory amounts);

    function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) external pure returns (uint256 amountB);
    function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut)
        external
        pure
        returns (uint256 amountOut);
    function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut)
        external
        pure
        returns (uint256 amountIn);
    function getAmountsOut(uint256 amountIn, address[] calldata path)
        external
        view
        returns (uint256[] memory amounts);
    function getAmountsIn(uint256 amountOut, address[] calldata path)
        external
        view
        returns (uint256[] memory amounts);
}
IUniswapV2Router02.sol 47 lines
pragma solidity >=0.6.2;

import "./IUniswapV2Router01.sol";

interface IUniswapV2Router02 is IUniswapV2Router01 {
    function removeLiquidityETHSupportingFeeOnTransferTokens(
        address token,
        uint256 liquidity,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline
    ) external returns (uint256 amountETH);
    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
        address token,
        uint256 liquidity,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline,
        bool approveMax,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (uint256 amountETH);

    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external;
    function swapExactETHForTokensSupportingFeeOnTransferTokens(
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external payable;
    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external;
}
IUniswapV3SwapCallback.sol 17 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
    /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
    /// @dev In the implementation you must pay the pool tokens owed for the swap.
    /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
    /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
    /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
    /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
    /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
    function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external;
}
IUniswapV3Pool.sol 22 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import "./pool/IUniswapV3PoolImmutables.sol";
import "./pool/IUniswapV3PoolState.sol";
import "./pool/IUniswapV3PoolDerivedState.sol";
import "./pool/IUniswapV3PoolActions.sol";
import "./pool/IUniswapV3PoolOwnerActions.sol";
import "./pool/IUniswapV3PoolEvents.sol";

/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
    IUniswapV3PoolImmutables,
    IUniswapV3PoolState,
    IUniswapV3PoolDerivedState,
    IUniswapV3PoolActions,
    IUniswapV3PoolOwnerActions,
    IUniswapV3PoolEvents
{}
IUniswapV3PoolActions.sol 92 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
    /// @notice Sets the initial price for the pool
    /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
    /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
    function initialize(uint160 sqrtPriceX96) external;

    /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
    /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
    /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
    /// on tickLower, tickUpper, the amount of liquidity, and the current price.
    /// @param recipient The address for which the liquidity will be created
    /// @param tickLower The lower tick of the position in which to add liquidity
    /// @param tickUpper The upper tick of the position in which to add liquidity
    /// @param amount The amount of liquidity to mint
    /// @param data Any data that should be passed through to the callback
    /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
    /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
    function mint(address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data)
        external
        returns (uint256 amount0, uint256 amount1);

    /// @notice Collects tokens owed to a position
    /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
    /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
    /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
    /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
    /// @param recipient The address which should receive the fees collected
    /// @param tickLower The lower tick of the position for which to collect fees
    /// @param tickUpper The upper tick of the position for which to collect fees
    /// @param amount0Requested How much token0 should be withdrawn from the fees owed
    /// @param amount1Requested How much token1 should be withdrawn from the fees owed
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collect(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);

    /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
    /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
    /// @dev Fees must be collected separately via a call to #collect
    /// @param tickLower The lower tick of the position for which to burn liquidity
    /// @param tickUpper The upper tick of the position for which to burn liquidity
    /// @param amount How much liquidity to burn
    /// @return amount0 The amount of token0 sent to the recipient
    /// @return amount1 The amount of token1 sent to the recipient
    function burn(int24 tickLower, int24 tickUpper, uint128 amount)
        external
        returns (uint256 amount0, uint256 amount1);

    /// @notice Swap token0 for token1, or token1 for token0
    /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
    /// @param recipient The address to receive the output of the swap
    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @param data Any data to be passed through to the callback
    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);

    /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
    /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
    /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
    /// with 0 amount{0,1} and sending the donation amount(s) from the callback
    /// @param recipient The address which will receive the token0 and token1 amounts
    /// @param amount0 The amount of token0 to send
    /// @param amount1 The amount of token1 to send
    /// @param data Any data to be passed through to the callback
    function flash(address recipient, uint256 amount0, uint256 amount1, bytes calldata data) external;

    /// @notice Increase the maximum number of price and liquidity observations that this pool will store
    /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
    /// the input observationCardinalityNext.
    /// @param observationCardinalityNext The desired minimum number of observations for the pool to store
    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
IUniswapV3PoolDerivedState.sol 36 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
    /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
    /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
    /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
    /// you must call it with secondsAgos = [3600, 0].
    /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
    /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
    /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
    /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
    /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
    /// timestamp
    function observe(uint32[] calldata secondsAgos)
        external
        view
        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);

    /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
    /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
    /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
    /// snapshot is taken and the second snapshot is taken.
    /// @param tickLower The lower tick of the range
    /// @param tickUpper The upper tick of the range
    /// @return tickCumulativeInside The snapshot of the tick accumulator for the range
    /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
    /// @return secondsInside The snapshot of seconds per liquidity for the range
    function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
        external
        view
        returns (int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside);
}
IUniswapV3PoolEvents.sol 120 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
    /// @notice Emitted exactly once by a pool when #initialize is first called on the pool
    /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
    /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
    /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
    event Initialize(uint160 sqrtPriceX96, int24 tick);

    /// @notice Emitted when liquidity is minted for a given position
    /// @param sender The address that minted the liquidity
    /// @param owner The owner of the position and recipient of any minted liquidity
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity minted to the position range
    /// @param amount0 How much token0 was required for the minted liquidity
    /// @param amount1 How much token1 was required for the minted liquidity
    event Mint(
        address sender,
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted when fees are collected by the owner of a position
    /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
    /// @param owner The owner of the position for which fees are collected
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount0 The amount of token0 fees collected
    /// @param amount1 The amount of token1 fees collected
    event Collect(
        address indexed owner,
        address recipient,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount0,
        uint128 amount1
    );

    /// @notice Emitted when a position's liquidity is removed
    /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
    /// @param owner The owner of the position for which liquidity is removed
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity to remove
    /// @param amount0 The amount of token0 withdrawn
    /// @param amount1 The amount of token1 withdrawn
    event Burn(
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted by the pool for any swaps between token0 and token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the output of the swap
    /// @param amount0 The delta of the token0 balance of the pool
    /// @param amount1 The delta of the token1 balance of the pool
    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
    /// @param liquidity The liquidity of the pool after the swap
    /// @param tick The log base 1.0001 of price of the pool after the swap
    event Swap(
        address indexed sender,
        address indexed recipient,
        int256 amount0,
        int256 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick
    );

    /// @notice Emitted by the pool for any flashes of token0/token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the tokens from flash
    /// @param amount0 The amount of token0 that was flashed
    /// @param amount1 The amount of token1 that was flashed
    /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
    /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
    event Flash(
        address indexed sender,
        address indexed recipient,
        uint256 amount0,
        uint256 amount1,
        uint256 paid0,
        uint256 paid1
    );

    /// @notice Emitted by the pool for increases to the number of observations that can be stored
    /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
    /// just before a mint/swap/burn.
    /// @param observationCardinalityNextOld The previous value of the next observation cardinality
    /// @param observationCardinalityNextNew The updated value of the next observation cardinality
    event IncreaseObservationCardinalityNext(
        uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew
    );

    /// @notice Emitted when the protocol fee is changed by the pool
    /// @param feeProtocol0Old The previous value of the token0 protocol fee
    /// @param feeProtocol1Old The previous value of the token1 protocol fee
    /// @param feeProtocol0New The updated value of the token0 protocol fee
    /// @param feeProtocol1New The updated value of the token1 protocol fee
    event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);

    /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
    /// @param sender The address that collects the protocol fees
    /// @param recipient The address that receives the collected protocol fees
    /// @param amount0 The amount of token0 protocol fees that is withdrawn
    /// @param amount0 The amount of token1 protocol fees that is withdrawn
    event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
IUniswapV3PoolImmutables.sol 35 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
    /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
    /// @return The contract address
    function factory() external view returns (address);

    /// @notice The first of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token0() external view returns (address);

    /// @notice The second of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token1() external view returns (address);

    /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
    /// @return The fee
    function fee() external view returns (uint24);

    /// @notice The pool tick spacing
    /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
    /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
    /// This value is an int24 to avoid casting even though it is always positive.
    /// @return The tick spacing
    function tickSpacing() external view returns (int24);

    /// @notice The maximum amount of position liquidity that can use any tick in the range
    /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
    /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
    /// @return The max amount of liquidity per tick
    function maxLiquidityPerTick() external view returns (uint128);
}
IUniswapV3PoolOwnerActions.sol 21 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
    /// @notice Set the denominator of the protocol's % share of the fees
    /// @param feeProtocol0 new protocol fee for token0 of the pool
    /// @param feeProtocol1 new protocol fee for token1 of the pool
    function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;

    /// @notice Collect the protocol fee accrued to the pool
    /// @param recipient The address to which collected protocol fees should be sent
    /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
    /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
    /// @return amount0 The protocol fee collected in token0
    /// @return amount1 The protocol fee collected in token1
    function collectProtocol(address recipient, uint128 amount0Requested, uint128 amount1Requested)
        external
        returns (uint128 amount0, uint128 amount1);
}
IUniswapV3PoolState.sol 116 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
    /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
    /// when accessed externally.
    /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
    /// tick The current tick of the pool, i.e. according to the last tick transition that was run.
    /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
    /// boundary.
    /// observationIndex The index of the last oracle observation that was written,
    /// observationCardinality The current maximum number of observations stored in the pool,
    /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
    /// feeProtocol The protocol fee for both tokens of the pool.
    /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
    /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
    /// unlocked Whether the pool is currently locked to reentrancy
    function slot0()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint8 feeProtocol,
            bool unlocked
        );

    /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal0X128() external view returns (uint256);

    /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal1X128() external view returns (uint256);

    /// @notice The amounts of token0 and token1 that are owed to the protocol
    /// @dev Protocol fees will never exceed uint128 max in either token
    function protocolFees() external view returns (uint128 token0, uint128 token1);

    /// @notice The currently in range liquidity available to the pool
    /// @dev This value has no relationship to the total liquidity across all ticks
    function liquidity() external view returns (uint128);

    /// @notice Look up information about a specific tick in the pool
    /// @param tick The tick to look up
    /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
    /// tick upper,
    /// liquidityNet how much liquidity changes when the pool price crosses the tick,
    /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
    /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
    /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
    /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
    /// secondsOutside the seconds spent on the other side of the tick from the current tick,
    /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
    /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
    /// In addition, these values are only relative and must be used only in comparison to previous snapshots for
    /// a specific position.
    function ticks(int24 tick)
        external
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128,
            int56 tickCumulativeOutside,
            uint160 secondsPerLiquidityOutsideX128,
            uint32 secondsOutside,
            bool initialized
        );

    /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
    function tickBitmap(int16 wordPosition) external view returns (uint256);

    /// @notice Returns the information about a position by the position's key
    /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
    /// @return _liquidity The amount of liquidity in the position,
    /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
    /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
    /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
    /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
    function positions(bytes32 key)
        external
        view
        returns (
            uint128 _liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    /// @notice Returns data about a specific observation index
    /// @param index The element of the observations array to fetch
    /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
    /// ago, rather than at a specific index in the array.
    /// @return blockTimestamp The timestamp of the observation,
    /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
    /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
    /// Returns initialized whether the observation has been initialized and the values are safe to use
    function observations(uint256 index)
        external
        view
        returns (
            uint32 blockTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,
            bool initialized
        );
}
ISwapRouter.sol 67 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;

import "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol";

/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
    struct ExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swaps `amountIn` of one token for as much as possible of another token
    /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
    /// @return amountOut The amount of the received token
    function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);

    struct ExactInputParams {
        bytes path;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
    }

    /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
    /// @return amountOut The amount of the received token
    function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);

    struct ExactOutputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swaps as little as possible of one token for `amountOut` of another token
    /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
    /// @return amountIn The amount of the input token
    function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);

    struct ExactOutputParams {
        bytes path;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
    }

    /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
    /// @return amountIn The amount of the input token
    function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
FluxHub.sol 507 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.26;

import "@openzeppelin/contracts/access/Ownable2Step.sol";
import "@openzeppelin/contracts/interfaces/IERC20.sol";
import "@openzeppelin/contracts/interfaces/IERC165.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "erc721a/contracts/ERC721A.sol";
import "./interfaces/ITitanOnBurn.sol";
import "./interfaces/IERC20Burnable.sol";
import "./interfaces/ITITANX.sol";
import "./interfaces/IFluxStaking.sol";
import "./interfaces/IFluxAuction.sol";
import "./interfaces/IE369HolderVault.sol";
import "./interfaces/IWETH9.sol";
import "./lib/constants.sol";
import "./lib/Time.sol";
import "./lib/OracleLibrary.sol";
import "./lib/TickMath.sol";

/// @title Element 369 FLUX Hub Contract
contract FluxHub is Ownable2Step, IERC165, ITitanOnBurn {
    using SafeERC20 for IERC20;

    // -------------------------- STATE VARIABLES -------------------------- //

    address public ELMNT_BB;
    address public immutable HolderVault;
    address public immutable DevWallet;

    /// @notice FLUX day number when the last auction was entered.
    uint32 public lastAuctionDay;

    /// @notice FLUX day number when the last stake was manually created.
    uint32 public lastStakeDay;

    /// @notice Balance of regular rewards to be distributed to the Holder Vault.
    uint256 public treasuryBalance;

    /// @notice Balance of day 777 rewards to be distributed to the Holder Vault.
    uint256 public treasury777Balance;

    /// @notice The max amount of TitanX to be used when entering FLUX auctions.
    uint256 public dailyAuctionLimit;

    /// @notice The max amount of TitanX to be used in a single treasury distribution.
    uint256 public distributionLimit;

    /// @notice Cooldown time between treasury distrbitutions.
    uint32 public distributionInterval = 15 minutes;

    /// @notice Timestamp of last treasury distribution.
    uint32 public lastDistribution;

    /// @notice Minimum Flux required for a manual stake.
    uint256 public minStakeAmount;

    /// @notice Incentive fee size for calling distributeTreasury and distribute777Treasury.
    uint32 public distributeTreasuryIncentiveFee = 300;

    /// @notice Incentive fee size for calling claimRewards.
    uint32 public claimRewardsIncentiveFee = 300;

    /// @notice Time used for TWAP calculation
    uint32 public secondsAgo = 5 * 60;

    /// @notice Allowed deviation of the minAmountOut from historical price for TitanX/Inferno swaps (BPS).
    uint32 public infernoDeviation = 2000;

    /// @notice Allowed deviation of the minAmountOut from historical price for TitanX/Helios swaps (BPS).
    uint32 public heliosDeviation = 2000;

    /// @notice Whitelisted wallets to distribute treasury funds.
    mapping(address account => bool) public distributionWhitelist;

    // ------------------------------ EVENTS ------------------------------ //

    event AuctionEntered();
    event StakeCreated();
    event AuctionsClaimed();
    event RewardsClaimed();
    event TreasuryDistributed();

    // ------------------------ ERRORS & MODIFIERS ------------------------ //

    error HubInactive();
    error NoAllocation();
    error NothingToClaim();
    error ZeroAddress();
    error ZeroInput();
    error Prohibited();
    error NotAvailable();
    error Cooldown();
    error TWAP();

    modifier originCheck() {
        if (address(msg.sender).code.length != 0 || msg.sender != tx.origin) revert Prohibited();
        _;
    }

    // ----------------------------- CONSTRUCTOR --------------------------- //

    constructor(
        address _owner,
        address _devWallet,
        address _element280BB,
        address _holderVault,
        uint256 _dailyAuctionLimit,
        uint256 _distributionLimit,
        uint256 _minStakeAmount
    ) Ownable(_owner) {
        if (_owner == address(0)) revert ZeroAddress();
        if (_devWallet == address(0)) revert ZeroAddress();
        if (_element280BB == address(0)) revert ZeroAddress();
        if (_holderVault == address(0)) revert ZeroAddress();
        if (_dailyAuctionLimit == 0) revert ZeroInput();
        if (_distributionLimit == 0) revert ZeroInput();
        if (_minStakeAmount == 0) revert ZeroInput();

        ELMNT_BB = _element280BB;
        HolderVault = _holderVault;
        DevWallet = _devWallet;
        dailyAuctionLimit = _dailyAuctionLimit;
        distributionLimit = _distributionLimit;
        minStakeAmount = _minStakeAmount;
    }

    // --------------------------- PUBLIC FUNCTIONS ------------------------ //

    /// @notice Enters the daily Flux auction.
    function enterAuction() external {
        (uint256 titanAmount, uint32 eligibleDays) = _getAvailableTitanX();
        if (titanAmount == 0) revert NoAllocation();
        IERC20(TITANX).safeIncreaseAllowance(FLUX_AUCTIONS, titanAmount);
        IFluxAuction(FLUX_AUCTIONS).deposit(uint192(titanAmount));
        lastAuctionDay += eligibleDays;
        emit AuctionEntered();
    }

    /// @notice Claims provided auction IDs, distributes 50% Flux to Holder Vault, and max stakes the rest.
    /// @param ids Auction IDs to claim.
    function claimAuctions(uint64[] calldata ids) external {
        if (ids.length == 0) revert Prohibited();
        IFluxAuction fluxAuctions = IFluxAuction(FLUX_AUCTIONS);
        IERC20 flux = IERC20(FLUX);
        uint256 claimableAmount = fluxAuctions.batchClaimableAmount(address(this), ids);
        if (claimableAmount == 0) revert NothingToClaim();
        fluxAuctions.batchClaim(ids);
        uint256 vaultAmount = claimableAmount / 2;
        flux.safeTransfer(HolderVault, vaultAmount);
        uint256 stakeAmount = flux.balanceOf(address(this));
        flux.safeIncreaseAllowance(FLUX_STAKING, stakeAmount);
        IFluxStaking(FLUX_STAKING).stake(MAX_DURATION, uint160(stakeAmount));
        emit AuctionsClaimed();
    }

    /// @notice Claims accrued rewards for provided Stake IDs and adds them to corresponding treasury.
    /// @param ids Stake IDs to claim.
    function claimRewards(uint160[] calldata ids) external {
        if (ids.length == 0 || ids.length > MAX_STAKES_PER_CLAIM) revert Prohibited();
        IERC20 titanX = IERC20(TITANX);
        uint256 previousBalance = titanX.balanceOf(address(this));
        IFluxStaking(FLUX_STAKING).batchClaim(ids, address(this));
        uint256 claimedAmount = titanX.balanceOf(address(this)) - previousBalance;
        if (claimedAmount == 0) revert NothingToClaim();
        claimedAmount = _processIncentiveFee(claimedAmount, claimRewardsIncentiveFee);
        _addToTreasury(claimedAmount);
        emit RewardsClaimed();
    }

    /// @notice Manually creates a max stake if FLUX balance is available.
    function startStake() external {
        (uint256 fluxAmount, uint32 eligibleDays) = _getAvailableFlux();
        if (fluxAmount == 0) revert NoAllocation();
        IERC20(FLUX).safeIncreaseAllowance(FLUX_STAKING, fluxAmount);
        IFluxStaking(FLUX_STAKING).stake(MAX_DURATION, uint160(fluxAmount));
        lastStakeDay += eligibleDays;
        emit StakeCreated();
    }

    /// @notice Swaps TitanX from treasury and distributes resulting tokens to Holder Vault.
    /// @param infernoMinAmountOut The minimum amount out for the TitanX -> Inferno swap.
    /// @param heliosMinAmountOut The minimum amount out for TitanX -> Helios swap.
    /// @param e280MinAmountOut The minimum amount out for Helios -> Element 280 swap.
    /// @param deadline The deadline for the swaps.
    function distributeTreasury(
        uint256 infernoMinAmountOut,
        uint256 heliosMinAmountOut,
        uint256 e280MinAmountOut,
        uint256 deadline
    ) external originCheck {
        uint32 currentT = Time.blockTs();
        if (currentT < getNextTreasuryDistribution()) revert Cooldown();
        if (treasuryBalance == 0) revert NotAvailable();
        if (!distributionWhitelist[msg.sender]) revert Prohibited();
        uint256 distributionAmount = treasuryBalance > distributionLimit ? distributionLimit : treasuryBalance;
        uint256 amountAfterIncentive = _processIncentiveFee(distributionAmount, distributeTreasuryIncentiveFee);
        (uint256 infernoAmount, uint256 e280Amount) = _processTreasurySwaps(
            amountAfterIncentive, infernoMinAmountOut, heliosMinAmountOut, e280MinAmountOut, deadline
        );

        lastDistribution = currentT;
        IERC20(INFERNO).safeTransfer(HolderVault, infernoAmount);
        IERC20(E280).safeTransfer(HolderVault, e280Amount);

        treasuryBalance -= distributionAmount;
        emit TreasuryDistributed();
    }

    /// @notice Swaps TitanX from day 777 treasury and distributes resulting tokens to Holder Vault.
    /// @param infernoMinAmountOut The minimum amount out for the TitanX -> Inferno swap.
    /// @param heliosMinAmountOut The minimum amount out for TitanX -> Helios swap.
    /// @param e280MinAmountOut The minimum amount out for Helios -> Element 280 swap.
    /// @param deadline The deadline for the swaps.
    function distribute777Treasury(
        uint256 infernoMinAmountOut,
        uint256 heliosMinAmountOut,
        uint256 e280MinAmountOut,
        uint256 deadline
    ) external originCheck {
        uint32 currentT = Time.blockTs();
        if (currentT < getNextTreasuryDistribution()) revert Cooldown();
        if (treasury777Balance == 0) revert NotAvailable();
        if (!distributionWhitelist[msg.sender]) revert Prohibited();
        uint256 distributionAmount = treasury777Balance > distributionLimit ? distributionLimit : treasury777Balance;
        uint256 amountAfterIncentive = _processIncentiveFee(distributionAmount, distributeTreasuryIncentiveFee);
        (uint256 infernoAmount, uint256 e280Amount) = _processTreasurySwaps(
            amountAfterIncentive, infernoMinAmountOut, heliosMinAmountOut, e280MinAmountOut, deadline
        );

        lastDistribution = currentT;
        IERC20(INFERNO).safeTransfer(HolderVault, infernoAmount);
        IERC20(E280).safeTransfer(HolderVault, e280Amount);
        IE369HolderVault(HolderVault).register777CycleTokens(infernoAmount, e280Amount);

        treasury777Balance -= distributionAmount;
        emit TreasuryDistributed();
    }

    // ----------------------- ADMINISTRATIVE FUNCTIONS -------------------- //

    /// @notice Sets the Element 280 Buy & Burn address.
    /// @param _address The new Element 280 Buy & Burn address.
    function setE280BuyBurn(address _address) external onlyOwner {
        if (_address == address(0)) revert ZeroAddress();
        ELMNT_BB = _address;
    }

    /// @notice Sets the Daily Auction limit in TitanX.
    /// @param limit The new Daily Auction limit in TitanX.
    function setDailyAuctionLimit(uint256 limit) external onlyOwner {
        if (limit == 0) revert ZeroInput();
        dailyAuctionLimit = limit;
    }

    /// @notice Sets the minimum Flux required for a manual stake.
    /// @param limit Flux amount in wei.
    function setMinStakeAmount(uint256 limit) external onlyOwner {
        if (limit == 0) revert ZeroInput();
        minStakeAmount = limit;
    }

    /// @notice Sets the Distribution limit in TitanX for treasury swaps.
    /// @param limit The new Distribution limit in TitanX for treasury swaps.
    function setDistributionLimit(uint256 limit) external onlyOwner {
        if (limit == 0) revert ZeroInput();
        distributionLimit = limit;
    }

    /// @notice Sets the cooldown interval for treasury distrbiutions.
    /// @param limit The new cooldown interval in seconds.
    function setDistributionInterval(uint32 limit) external onlyOwner {
        if (limit == 0) revert ZeroInput();
        distributionInterval = limit;
    }

    /// @notice Sets the incentive fee size for claiming rewards.
    /// @param size The size of the incentive fee 1% = 1,000 (0 - 10,000), (Max - 10%).
    function setClaimRewardsIncentiveFee(uint32 size) external onlyOwner {
        if (size > 10_000) revert Prohibited();
        claimRewardsIncentiveFee = size;
    }

    /// @notice Sets the incentive fee size for distributing treasuries.
    /// @param size The size of the incentive fee 1% = 1,000 (0 - 10,000), (Max - 10%).
    function setDistributeTreasuryIncentiveFee(uint32 size) external onlyOwner {
        if (size > 10_000) revert Prohibited();
        distributeTreasuryIncentiveFee = size;
    }

    /// @notice Sets the whitelist status for provided addresses for treasury distributions.
    /// @param accounts List of wallets which status will be changed.
    /// @param isAllowed Status to be set.
    function setDistributionWhitelist(address[] calldata accounts, bool isAllowed) external onlyOwner {
        for (uint256 i = 0; i < accounts.length; i++) {
            distributionWhitelist[accounts[i]] = isAllowed;
        }
    }

    /// @notice Sets the number of seconds to look back for TWAP price calculations.
    /// @param limit The number of seconds to use for TWAP price lookback.
    function setSecondsAgo(uint32 limit) external onlyOwner {
        if (limit == 0) revert ZeroInput();
        secondsAgo = limit;
    }

    /// @notice Sets the allowed price deviation for TitanX/Inferno swaps in TWAP checks.
    /// @param limit The allowed deviation in basis points (e.g., 500 = 5%).
    function setInfernoDeviation(uint32 limit) external onlyOwner {
        if (limit == 0) revert ZeroInput();
        if (limit > BPS_BASE) revert Prohibited();
        infernoDeviation = limit;
    }

    /// @notice Sets the allowed price deviation for TitanX/Helios swaps in TWAP checks.
    /// @param limit The allowed deviation in basis points (e.g., 500 = 5%).
    function setHeliosDeviation(uint32 limit) external onlyOwner {
        if (limit == 0) revert ZeroInput();
        if (limit > BPS_BASE) revert Prohibited();
        heliosDeviation = limit;
    }

    // ---------------------------- VIEW FUNCTIONS ------------------------- //

    /// @notice Returns avalable TitanX amount for the next auction.
    function getNextTreasuryDistribution() public view returns (uint256) {
        return lastDistribution + distributionInterval;
    }

    /// @notice Checks if the next auction can be entered.
    function isAuctionAvailable() public view returns (bool) {
        uint32 availableDays = _getAvailableDaysSince(lastAuctionDay);
        uint256 availableBalance = IERC20(TITANX).balanceOf(address(this)) - treasuryBalance - treasury777Balance;
        return availableDays > 0 && availableBalance >= dailyAuctionLimit;
    }

    /// @notice Returns total TitanX allocated for auctions.
    function getTitanXForAuctions() public view returns (uint256) {
        uint256 availableBalance = IERC20(TITANX).balanceOf(address(this)) - treasuryBalance - treasury777Balance;
        return availableBalance;
    }

    function getStakesClaimableRewardsPerId(uint160[] memory stakeIds)
        external
        view
        returns (uint256[] memory rewards)
    {
        rewards = new uint256[](stakeIds.length);
        uint160[] memory request = new uint160[](1);
        for (uint256 i = 0; i < stakeIds.length; i++) {
            request[0] = stakeIds[i];
            rewards[i] = IFluxStaking(FLUX_STAKING).batchClaimableAmount(request);
        }
    }

    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165) returns (bool) {
        return interfaceId == INTERFACE_ID_ERC165 || interfaceId == INTERFACE_ID_ITITANONBURN;
    }

    // -------------------------- INTERNAL FUNCTIONS ----------------------- //

    /// @notice ITitanOnBurn interface function.
    function onBurn(address, uint256 amount) external {}

    function _getAvailableFlux() internal view returns (uint256, uint32) {
        if (block.timestamp < MINT_START_DATE) revert HubInactive();
        uint32 availableDays = _getAvailableDaysSince(lastStakeDay);
        if (availableDays == 0) return (0, 0);
        uint256 availableBalance = IERC20(FLUX).balanceOf(address(this));
        return (availableBalance < minStakeAmount ? 0 : availableBalance, availableDays);
    }

    function _getAvailableTitanX() internal view returns (uint256, uint32) {
        if (block.timestamp < MINT_START_DATE) revert HubInactive();
        uint32 availableDays = _getAvailableDaysSince(lastAuctionDay);
        if (availableDays == 0) return (0, 0);
        uint256 availableBalance = IERC20(TITANX).balanceOf(address(this)) - treasuryBalance - treasury777Balance;
        if (availableBalance < dailyAuctionLimit) return (0, 0);
        return (dailyAuctionLimit, availableDays);
    }

    function _getAvailableDaysSince(uint32 lastDay) internal view returns (uint32) {
        uint32 daysPassed = Time.daysSince(MINT_START_DATE);
        return daysPassed - lastDay;
    }

    function _processIncentiveFee(uint256 amount, uint32 incentiveFeeSize) internal returns (uint256) {
        uint256 incentiveFee = amount * incentiveFeeSize / INCENTIVE_FEE_BASE;
        IERC20(TITANX).safeTransfer(msg.sender, incentiveFee);
        return amount - incentiveFee;
    }

    function _addToTreasury(uint256 amount) internal {
        uint256 amountToAdd = _getTreasuryAmount(amount);
        uint32 daysPassed = Time.daysSince(FLUX_START_DATE) + 1;
        uint32 cycles = daysPassed / CYCLE_777_DAYS;
        if (cycles > 0 && cycles < MAX_777_CYCLES_NUMBER + 1 && daysPassed <= cycles * CYCLE_777_DAYS + DAY_777_OFFSET)
        {
            treasury777Balance += amountToAdd;
        } else {
            treasuryBalance += amountToAdd;
        }
    }

    function _getTreasuryAmount(uint256 amount) internal view returns (uint256) {
        if (Time.blockTs() < ELEMENT_END_DATE) {
            return amount * TREASURY_PERCENTS / PERCENTAGE_BASE;
        } else {
            return amount;
        }
    }

    function _processTreasurySwaps(
        uint256 distributionAmount,
        uint256 infernoMinAmountOut,
        uint256 heliosMinAmountOut,
        uint256 e280MinAmountOut,
        uint256 deadline
    ) internal returns (uint256, uint256) {
        uint256 buyBurnAmount = distributionAmount * BURN_PERCENTAGE / PERCENTAGE_BASE;
        IERC20(TITANX).safeTransfer(ELMNT_BB, buyBurnAmount);

        uint256 infernoSwapAmount = distributionAmount * INFERNO_SWAP_PERCENTAGE / PERCENTAGE_BASE;
        uint256 infernoAmount = _swapUniswapV3Pool(INFERNO, infernoSwapAmount, infernoMinAmountOut, deadline);
        uint256 infernoBurnAmount = infernoAmount * BURN_PERCENTAGE / PERCENTAGE_BASE;
        _handleTokenBurn(INFERNO, infernoBurnAmount);

        uint256 heliosSwapAmount = distributionAmount - buyBurnAmount - infernoSwapAmount;
        uint256 heliosAmount = _swapUniswapV3Pool(HELIOS, heliosSwapAmount, heliosMinAmountOut, deadline);
        uint256 heliosBurnAmount = heliosAmount * BURN_PERCENTAGE / PERCENTAGE_BASE;
        _handleTokenBurn(HELIOS, heliosBurnAmount);

        uint256 e280Amount = _swapE280(heliosAmount - heliosBurnAmount, e280MinAmountOut, deadline);
        return (infernoAmount - infernoBurnAmount, e280Amount);
    }

    function _swapUniswapV3Pool(address outputToken, uint256 amountIn, uint256 minAmountOut, uint256 deadline)
        private
        returns (uint256)
    {
        _twapCheck(TITANX, outputToken, amountIn, minAmountOut);
        ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({
            tokenIn: TITANX,
            tokenOut: outputToken,
            fee: POOL_FEE_1PERCENT,
            recipient: address(this),
            deadline: deadline,
            amountIn: amountIn,
            amountOutMinimum: minAmountOut,
            sqrtPriceLimitX96: 0
        });
        IERC20(TITANX).safeIncreaseAllowance(UNISWAP_V3_ROUTER, amountIn);
        uint256 amountOut = ISwapRouter(UNISWAP_V3_ROUTER).exactInputSingle(params);
        return amountOut;
    }

    function _twapCheck(address tokenIn, address tokenOut, uint256 amountIn, uint256 minAmountOut) internal view {
        address poolAddress;
        uint32 deviation;
        if (tokenOut == INFERNO) {
            poolAddress = TITANX_INFERNO_POOL;
            deviation = infernoDeviation;
        } else {
            poolAddress = TITANX_HELIOS_POOL;
            deviation = heliosDeviation;
        }
        uint32 _secondsAgo = secondsAgo;
        uint32 oldestObservation = OracleLibrary.getOldestObservationSecondsAgo(poolAddress);
        if (oldestObservation < _secondsAgo) {
            _secondsAgo = oldestObservation;
        }

        (int24 arithmeticMeanTick,) = OracleLibrary.consult(poolAddress, _secondsAgo);
        uint160 sqrtPriceX96 = TickMath.getSqrtRatioAtTick(arithmeticMeanTick);
        uint256 twapAmountOut =
            OracleLibrary.getQuoteForSqrtRatioX96(sqrtPriceX96, uint128(amountIn), tokenIn, tokenOut);
        uint256 lowerBound = (twapAmountOut * (BPS_BASE - deviation)) / BPS_BASE;

        if (minAmountOut < lowerBound) revert TWAP();
    }

    function _swapE280(uint256 amountIn, uint256 minAmountOut, uint256 deadline) internal returns (uint256) {
        if (minAmountOut == 0) revert ZeroInput();
        address[] memory path = new address[](2);
        path[0] = HELIOS;
        path[1] = E280;

        IERC20(HELIOS).safeIncreaseAllowance(UNISWAP_V2_ROUTER, amountIn);
        IUniswapV2Router02(UNISWAP_V2_ROUTER).swapExactTokensForTokensSupportingFeeOnTransferTokens(
            amountIn, minAmountOut, path, address(this), deadline
        );

        return IERC20(E280).balanceOf(address(this));
    }

    function _handleTokenBurn(address tokenAddress, uint256 amountToBurn) internal {
        if (tokenAddress == HELIOS) {
            IERC20(tokenAddress).safeIncreaseAllowance(address(this), amountToBurn);
            ITITANX(tokenAddress).burnTokensToPayAddress(address(this), amountToBurn, 0, 8, DevWallet);
        } else {
            IERC20Burnable(tokenAddress).burn(amountToBurn);
        }
    }
}
IE369HolderVault.sol 10 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

interface IE369HolderVault {
    function register777CycleTokens(uint256 infernoAmount, uint256 e280Amount) external;
    function updateStoredMultipliers(uint32 cycleId, uint256 totalMultipliers) external;
    function updateStoredMultipliersOnBurn(uint32 cycleId, uint256 totalMultipliers, uint256 multiplierDeduction)
        external;
    function setFluxHub(address fluxHub) external;
}
IERC20Burnable.sol 8 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "@openzeppelin/contracts/interfaces/IERC20.sol";

interface IERC20Burnable is IERC20 {
    function burn(uint256 value) external;
}
IFluxAuction.sol 10 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

interface IFluxAuction {
    event UserDeposit(address indexed user, uint256 indexed amount, uint32 indexed day, uint248 id);

    function deposit(uint192 _amount) external;
    function batchClaim(uint64[] calldata _ids) external;
    function batchClaimableAmount(address _user, uint64[] calldata _ids) external view returns (uint256);
}
IFluxStaking.sol 31 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

interface IFluxStaking {
    struct UserRecord {
        uint160 shares;
        uint160 lockedFlux;
        uint128 rewardDebt;
        uint32 endTime;
    }

    event Staked(
        address indexed staker,
        uint256 indexed flux,
        uint152 indexed id,
        uint256 _shares,
        uint32 duration,
        bool isVoluntary
    );

    function stake(uint32 _duration, uint160 _fluxAmount) external returns (uint96 _tokenId, uint144 shares);
    function batchClaimableAmount(uint160[] calldata _ids) external view returns (uint256 toClaim);
    function batchClaim(uint160[] calldata _ids, address _receiver) external;
    function batchUnstake(uint160[] calldata _ids, address _receiver) external;
    function approve(address to, uint256 tokenId) external;
    function balanceOf(address account) external view returns (uint256);
    function ownerOf(uint256 tokenId) external view returns (address);
    function totalSupply() external view returns (uint256);
    function updateRewardsIfNecessary() external;
    function userRecords(uint256 id) external view returns (UserRecord memory);
}
ITitanOnBurn.sol 6 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

interface ITitanOnBurn {
    function onBurn(address user, uint256 amount) external;
}
ITITANX.sol 107 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.10;

interface ITITANX {
    error TitanX_InvalidAmount();
    error TitanX_InsufficientBalance();
    error TitanX_NotSupportedContract();
    error TitanX_InsufficientProtocolFees();
    error TitanX_FailedToSendAmount();
    error TitanX_NotAllowed();
    error TitanX_NoCycleRewardToClaim();
    error TitanX_NoSharesExist();
    error TitanX_EmptyUndistributeFees();
    error TitanX_InvalidBurnRewardPercent();
    error TitanX_InvalidBatchCount();
    error TitanX_InvalidMintLadderInterval();
    error TitanX_InvalidMintLadderRange();
    error TitanX_MaxedWalletMints();
    error TitanX_LPTokensHasMinted();
    error TitanX_InvalidAddress();
    error TitanX_InsufficientBurnAllowance();

    function getBalance() external;

    /**
     * @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);

    function burnTokensToPayAddress(
        address user,
        uint256 amount,
        uint256 userRebatePercentage,
        uint256 rewardPaybackPercentage,
        address rewardPaybackAddress
    ) external;

    function burnTokens(address user, uint256 amount, uint256 userRebatePercentage, uint256 rewardPaybackPercentage)
        external;

    function userBurnTokens(uint256 amount) external;
}
IWETH9.sol 13 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.10;

import "@openzeppelin/contracts/interfaces/IERC20.sol";

/// @title Interface for WETH9
interface IWETH9 is IERC20 {
    /// @notice Deposit ether to get wrapped ether
    function deposit() external payable;

    /// @notice Withdraw wrapped ether to get ether
    function withdraw(uint256) external;
}
constants.sol 78 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "../interfaces/ITitanOnBurn.sol";
import "@openzeppelin/contracts/interfaces/IERC20.sol";

// ===================== Contract Addresses =====================================
address constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address constant TITANX = 0xF19308F923582A6f7c465e5CE7a9Dc1BEC6665B1;
address constant FLUX = 0xBFDE5ac4f5Adb419A931a5bF64B0f3BB5a623d06;
address constant FLUX_STAKING = 0xd605a87187563C94c577a6E57e4a36eC8433B9aE;
address constant FLUX_AUCTIONS = 0x36e5a8105f000029d4B3B99d0C3D0e24aaA52adF;
address constant HELIOS = 0x2614f29C39dE46468A921Fd0b41fdd99A01f2EDf;
address constant INFERNO = 0x00F116ac0c304C570daAA68FA6c30a86A04B5C5F;
address constant E280 = 0xe9A53C43a0B58706e67341C4055de861e29Ee943;

// ===================== POOLS ==================================================
address constant TITANX_WETH_POOL = 0xc45A81BC23A64eA556ab4CdF08A86B61cdcEEA8b;
address constant TITANX_INFERNO_POOL = 0x1E90B67149e688DfB95fD73Acacd8ADefd16d88D;
address constant TITANX_HELIOS_POOL = 0x2C83C54C5612BfD62a78124D4A0eA001278a689c;

// ===================== FLUX ===================================================
uint32 constant FLUX_START_DATE = 1727024400;

// ===================== NFT ====================================================
uint32 constant MINT_START_DATE = FLUX_START_DATE + 60 days;
uint32 constant ELEMENT_END_DATE = FLUX_START_DATE + 2331 days;
uint32 constant MINT_CYCLE_LENGTH = 44;
uint8 constant DEV_PERCENT = 8;

uint256 constant BITPOS_NFT_TIER = 0;
uint256 constant BITMASK_NFT_TIER = (1 << 8) - 1;

uint256 constant BITPOS_MULTIPLIER = 8;
uint256 constant BITMASK_MULTIPLIER = (1 << 16) - 1;

uint256 constant BITPOS_MINT_CYCLE = 24;
uint256 constant BITMASK_MINT_CYCLE = (1 << 32) - 1;

uint256 constant BITPOS_BURN_CYCLE = 56;
uint256 constant BITMASK_BURN_CYCLE = (1 << 32) - 1;

uint256 constant BITPOS_BURN_ADDRESS = 88;
uint256 constant BITMASK_BURN_ADDRESS = (1 << 160) - 1;

// ===================== FLUX HUB ===============================================
uint32 constant MAX_DURATION = 2888 days;
uint32 constant MAX_STAKES_PER_CLAIM = 100;
uint32 constant TREASURY_PERCENTS = 70;
uint32 constant DAY_777_OFFSET = 3;
uint32 constant INFERNO_SWAP_PERCENTAGE = 42;
uint32 constant BURN_PERCENTAGE = 16;

uint32 constant INCENTIVE_FEE_BASE = 100_000;
uint32 constant BPS_BASE = 10_000;
uint32 constant PERCENTAGE_BASE = 100;

// ===================== Holder Vault ===========================================
uint32 constant CYCLE_CREATION_OFFSET = 2;
uint32 constant MAX_777_CYCLES_NUMBER = 4;
uint32 constant CYCLE_777_DAYS = 777;
uint32 constant E369_CYCLE_INTERVAL = 11;
uint16 constant MAX_CYCLES_PER_CLAIM = 100;
uint8 constant BACKING_CLAIM_TAX = 3;

// ===================== UNISWAP Interface ======================================

address constant UNISWAP_V2_FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
address constant UNISWAP_V2_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address constant UNISWAP_V3_ROUTER = 0xE592427A0AEce92De3Edee1F18E0157C05861564;
uint24 constant POOL_FEE_1PERCENT = 10000;

// ===================== Interface IDs ==========================================
bytes4 constant INTERFACE_ID_ERC165 = 0x01ffc9a7;
bytes4 constant INTERFACE_ID_ERC20 = type(IERC20).interfaceId;
bytes4 constant INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 constant INTERFACE_ID_ERC721Metadata = 0x5b5e139f;
bytes4 constant INTERFACE_ID_ITITANONBURN = type(ITitanOnBurn).interfaceId;
OracleLibrary.sol 175 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

// Uniswap
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";

// OpenZeppelin
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {TickMath} from "./TickMath.sol";

/**
 * @notice Adapted Uniswap V3 OracleLibrary computation to be compliant with Solidity 0.8.x and later.
 *
 * Documentation for Auditors:
 *
 * Solidity Version: Updated the Solidity version pragma to ^0.8.0. This change ensures compatibility
 * with Solidity version 0.8.x.
 *
 * Safe Arithmetic Operations: Solidity 0.8.x automatically checks for arithmetic overflows/underflows.
 * Therefore, the code no longer needs to use SafeMath library (or similar) for basic arithmetic operations.
 * This change simplifies the code and reduces the potential for errors related to manual overflow/underflow checking.
 *
 * Overflow/Underflow: With the introduction of automatic overflow/underflow checks in Solidity 0.8.x, the code is inherently
 * safer and less prone to certain types of arithmetic errors.
 *
 * Removal of SafeMath Library: Since Solidity 0.8.x handles arithmetic operations safely, the use of SafeMath library
 * is omitted in this update.
 *
 * Git-style diff for the `consult` function:
 *
 * ```diff
 * function consult(address pool, uint32 secondsAgo)
 *     internal
 *     view
 *     returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)
 * {
 *     require(secondsAgo != 0, 'BP');
 *
 *     uint32[] memory secondsAgos = new uint32[](2);
 *     secondsAgos[0] = secondsAgo;
 *     secondsAgos[1] = 0;
 *
 *     (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) =
 *         IUniswapV3Pool(pool).observe(secondsAgos);
 *
 *     int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
 *     uint160 secondsPerLiquidityCumulativesDelta =
 *         secondsPerLiquidityCumulativeX128s[1] - secondsPerLiquidityCumulativeX128s[0];
 *
 * -   arithmeticMeanTick = int24(tickCumulativesDelta / secondsAgo);
 * +   int56 secondsAgoInt56 = int56(uint56(secondsAgo));
 * +   arithmeticMeanTick = int24(tickCumulativesDelta / secondsAgoInt56);
 *     // Always round to negative infinity
 * -   if (tickCumulativesDelta < 0 && (tickCumulativesDelta % secondsAgo != 0)) arithmeticMeanTick--;
 * +   if (tickCumulativesDelta < 0 && (tickCumulativesDelta % secondsAgoInt56 != 0)) arithmeticMeanTick--;
 *
 * -   uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;
 * +   uint192 secondsAgoUint192 = uint192(secondsAgo);
 * +   uint192 secondsAgoX160 = secondsAgoUint192 * type(uint160).max;
 *     harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));
 * }
 * ```
 */

/// @title Oracle library
/// @notice Provides functions to integrate with V3 pool oracle
library OracleLibrary {
    /// @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool
    /// @param pool Address of the pool that we want to observe
    /// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means
    /// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp
    /// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp
    function consult(address pool, uint32 secondsAgo)
        internal
        view
        returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)
    {
        require(secondsAgo != 0, "BP");

        uint32[] memory secondsAgos = new uint32[](2);
        secondsAgos[0] = secondsAgo;
        secondsAgos[1] = 0;

        (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) =
            IUniswapV3Pool(pool).observe(secondsAgos);

        int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
        uint160 secondsPerLiquidityCumulativesDelta =
            secondsPerLiquidityCumulativeX128s[1] - secondsPerLiquidityCumulativeX128s[0];

        // Safe casting of secondsAgo to int56 for division
        int56 secondsAgoInt56 = int56(uint56(secondsAgo));
        arithmeticMeanTick = int24(tickCumulativesDelta / secondsAgoInt56);
        // Always round to negative infinity
        if (tickCumulativesDelta < 0 && (tickCumulativesDelta % secondsAgoInt56 != 0)) arithmeticMeanTick--;

        // Safe casting of secondsAgo to uint192 for multiplication
        uint192 secondsAgoUint192 = uint192(secondsAgo);
        harmonicMeanLiquidity = uint128(
            (secondsAgoUint192 * uint192(type(uint160).max)) / (uint192(secondsPerLiquidityCumulativesDelta) << 32)
        );
    }

    /// @notice Given a tick and a token amount, calculates the amount of token received in exchange
    /// @param tick Tick value used to calculate the quote
    /// @param baseAmount Amount of token to be converted
    /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination
    /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination
    /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken
    function getQuoteAtTick(int24 tick, uint128 baseAmount, address baseToken, address quoteToken)
        internal
        pure
        returns (uint256 quoteAmount)
    {
        uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);

        // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself
        if (sqrtRatioX96 <= type(uint128).max) {
            uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
            quoteAmount = baseToken < quoteToken
                ? Math.mulDiv(ratioX192, baseAmount, 1 << 192)
                : Math.mulDiv(1 << 192, baseAmount, ratioX192);
        } else {
            uint256 ratioX128 = Math.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);
            quoteAmount = baseToken < quoteToken
                ? Math.mulDiv(ratioX128, baseAmount, 1 << 128)
                : Math.mulDiv(1 << 128, baseAmount, ratioX128);
        }
    }

    /// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation
    /// @param pool Address of Uniswap V3 pool that we want to observe
    /// @return secondsAgo The number of seconds ago of the oldest observation stored for the pool
    function getOldestObservationSecondsAgo(address pool) internal view returns (uint32 secondsAgo) {
        (,, uint16 observationIndex, uint16 observationCardinality,,,) = IUniswapV3Pool(pool).slot0();
        require(observationCardinality > 0, "NI");

        (uint32 observationTimestamp,,, bool initialized) =
            IUniswapV3Pool(pool).observations((observationIndex + 1) % observationCardinality);

        // The next index might not be initialized if the cardinality is in the process of increasing
        // In this case the oldest observation is always in index 0
        if (!initialized) {
            (observationTimestamp,,,) = IUniswapV3Pool(pool).observations(0);
        }

        secondsAgo = uint32(block.timestamp) - observationTimestamp;
    }

    /// @notice Given a tick and a token amount, calculates the amount of token received in exchange
    /// a slightly modified version of the UniSwap library getQuoteAtTick to accept a sqrtRatioX96 as input parameter
    /// @param sqrtRatioX96 The sqrt ration
    /// @param baseAmount Amount of token to be converted
    /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination
    /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination
    /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken
    function getQuoteForSqrtRatioX96(uint160 sqrtRatioX96, uint256 baseAmount, address baseToken, address quoteToken)
        internal
        pure
        returns (uint256 quoteAmount)
    {
        // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself
        if (sqrtRatioX96 <= type(uint128).max) {
            uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
            quoteAmount = baseToken < quoteToken
                ? Math.mulDiv(ratioX192, baseAmount, 1 << 192)
                : Math.mulDiv(1 << 192, baseAmount, ratioX192);
        } else {
            uint256 ratioX128 = Math.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);
            quoteAmount = baseToken < quoteToken
                ? Math.mulDiv(ratioX128, baseAmount, 1 << 128)
                : Math.mulDiv(1 << 128, baseAmount, ratioX128);
        }
    }
}
TickMath.sol 213 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;

/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
    error T();
    error R();

    /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
    int24 internal constant MIN_TICK = -887272;
    /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
    int24 internal constant MAX_TICK = -MIN_TICK;

    /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
    uint160 internal constant MIN_SQRT_RATIO = 4295128739;
    /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
    uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;

    /// @notice Calculates sqrt(1.0001^tick) * 2^96
    /// @dev Throws if |tick| > max tick
    /// @param tick The input tick for the above formula
    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
    /// at the given tick
    function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
        unchecked {
            uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
            if (absTick > uint256(int256(MAX_TICK))) revert T();

            uint256 ratio =
                absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
            if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
            if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
            if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
            if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
            if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
            if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
            if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
            if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
            if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
            if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
            if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
            if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
            if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
            if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
            if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
            if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
            if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
            if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
            if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;

            if (tick > 0) ratio = type(uint256).max / ratio;

            // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
            // we then downcast because we know the result always fits within 160 bits due to our tick input constraint
            // we round up in the division so getTickAtSqrtRatio of the output price is always consistent
            sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
        }
    }

    /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
    /// ever return.
    /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
    /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
    function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
        unchecked {
            // second inequality must be < because the price can never reach the price at the max tick
            if (!(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO)) revert R();
            uint256 ratio = uint256(sqrtPriceX96) << 32;

            uint256 r = ratio;
            uint256 msb = 0;

            assembly {
                let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(5, gt(r, 0xFFFFFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(4, gt(r, 0xFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(3, gt(r, 0xFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(2, gt(r, 0xF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := shl(1, gt(r, 0x3))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly {
                let f := gt(r, 0x1)
                msb := or(msb, f)
            }

            if (msb >= 128) r = ratio >> (msb - 127);
            else r = ratio << (127 - msb);

            int256 log_2 = (int256(msb) - 128) << 64;

            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(63, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(62, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(61, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(60, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(59, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(58, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(57, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(56, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(55, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(54, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(53, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(52, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(51, f))
                r := shr(f, r)
            }
            assembly {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(50, f))
            }

            int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number

            int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
            int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);

            tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
        }
    }
}
Time.sol 38 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

library Time {
    ///@notice Gets the current timestamp
    function blockTs() internal view returns (uint32 ts) {
        assembly {
            ts := timestamp()
        }
    }

    ///@notice Gets the the day count from a timestamp
    function dayCountByT(uint32 t) internal pure returns (uint32 dayCount) {
        assembly {
            let adjustedTime := sub(t, 61200)
            dayCount := div(adjustedTime, 86400)
        }
    }

    ///@notice Gets the week count, since a starting timestamp
    function weekSince(uint32 t) internal view returns (uint32 weeksPassed) {
        assembly {
            let currentTime := timestamp()
            let timeElapsed := sub(currentTime, t)

            weeksPassed := div(timeElapsed, 604800)
        }
    }

    function daysSince(uint32 t) public view returns (uint32 daysPassed) {
        assembly {
            // Get the current block timestamp
            let currentTime := timestamp()

            daysPassed := div(sub(currentTime, t), 86400)
        }
    }
}
ERC721A.sol 1266 lines
// SPDX-License-Identifier: MIT
// ERC721A Contracts v4.3.0
// Creator: Chiru Labs

pragma solidity ^0.8.4;

import "./IERC721A.sol";

/**
 * @dev Interface of ERC721 token receiver.
 */
interface ERC721A__IERC721Receiver {
    function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
        external
        returns (bytes4);
}

/**
 * @title ERC721A
 *
 * @dev Implementation of the [ERC721](https://eips.ethereum.org/EIPS/eip-721)
 * Non-Fungible Token Standard, including the Metadata extension.
 * Optimized for lower gas during batch mints.
 *
 * Token IDs are minted in sequential order (e.g. 0, 1, 2, 3, ...)
 * starting from `_startTokenId()`.
 *
 * The `_sequentialUpTo()` function can be overriden to enable spot mints
 * (i.e. non-consecutive mints) for `tokenId`s greater than `_sequentialUpTo()`.
 *
 * Assumptions:
 *
 * - An owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
 * - The maximum token ID cannot exceed 2**256 - 1 (max value of uint256).
 */
contract ERC721A is IERC721A {
    // Bypass for a `--via-ir` bug (https://github.com/chiru-labs/ERC721A/pull/364).
    struct TokenApprovalRef {
        address value;
    }

    // =============================================================
    //                           CONSTANTS
    // =============================================================

    // Mask of an entry in packed address data.
    uint256 private constant _BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1;

    // The bit position of `numberMinted` in packed address data.
    uint256 private constant _BITPOS_NUMBER_MINTED = 64;

    // The bit position of `numberBurned` in packed address data.
    uint256 private constant _BITPOS_NUMBER_BURNED = 128;

    // The bit position of `aux` in packed address data.
    uint256 private constant _BITPOS_AUX = 192;

    // Mask of all 256 bits in packed address data except the 64 bits for `aux`.
    uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1;

    // The bit position of `startTimestamp` in packed ownership.
    uint256 private constant _BITPOS_START_TIMESTAMP = 160;

    // The bit mask of the `burned` bit in packed ownership.
    uint256 private constant _BITMASK_BURNED = 1 << 224;

    // The bit position of the `nextInitialized` bit in packed ownership.
    uint256 private constant _BITPOS_NEXT_INITIALIZED = 225;

    // The bit mask of the `nextInitialized` bit in packed ownership.
    uint256 private constant _BITMASK_NEXT_INITIALIZED = 1 << 225;

    // The bit position of `extraData` in packed ownership.
    uint256 private constant _BITPOS_EXTRA_DATA = 232;

    // Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`.
    uint256 private constant _BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1;

    // The mask of the lower 160 bits for addresses.
    uint256 private constant _BITMASK_ADDRESS = (1 << 160) - 1;

    // The maximum `quantity` that can be minted with {_mintERC2309}.
    // This limit is to prevent overflows on the address data entries.
    // For a limit of 5000, a total of 3.689e15 calls to {_mintERC2309}
    // is required to cause an overflow, which is unrealistic.
    uint256 private constant _MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000;

    // The `Transfer` event signature is given by:
    // `keccak256(bytes("Transfer(address,address,uint256)"))`.
    bytes32 private constant _TRANSFER_EVENT_SIGNATURE =
        0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;

    // =============================================================
    //                            STORAGE
    // =============================================================

    // The next token ID to be minted.
    uint256 private _currentIndex;

    // The number of tokens burned.
    uint256 private _burnCounter;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    // Mapping from token ID to ownership details
    // An empty struct value does not necessarily mean the token is unowned.
    // See {_packedOwnershipOf} implementation for details.
    //
    // Bits Layout:
    // - [0..159]   `addr`
    // - [160..223] `startTimestamp`
    // - [224]      `burned`
    // - [225]      `nextInitialized`
    // - [232..255] `extraData`
    mapping(uint256 => uint256) private _packedOwnerships;

    // Mapping owner address to address data.
    //
    // Bits Layout:
    // - [0..63]    `balance`
    // - [64..127]  `numberMinted`
    // - [128..191] `numberBurned`
    // - [192..255] `aux`
    mapping(address => uint256) private _packedAddressData;

    // Mapping from token ID to approved address.
    mapping(uint256 => TokenApprovalRef) private _tokenApprovals;

    // Mapping from owner to operator approvals
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    // The amount of tokens minted above `_sequentialUpTo()`.
    // We call these spot mints (i.e. non-sequential mints).
    uint256 private _spotMinted;

    // =============================================================
    //                          CONSTRUCTOR
    // =============================================================

    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
        _currentIndex = _startTokenId();

        if (_sequentialUpTo() < _startTokenId()) _revert(SequentialUpToTooSmall.selector);
    }

    // =============================================================
    //                   TOKEN COUNTING OPERATIONS
    // =============================================================

    /**
     * @dev Returns the starting token ID for sequential mints.
     *
     * Override this function to change the starting token ID for sequential mints.
     *
     * Note: The value returned must never change after any tokens have been minted.
     */
    function _startTokenId() internal view virtual returns (uint256) {
        return 0;
    }

    /**
     * @dev Returns the maximum token ID (inclusive) for sequential mints.
     *
     * Override this function to return a value less than 2**256 - 1,
     * but greater than `_startTokenId()`, to enable spot (non-sequential) mints.
     *
     * Note: The value returned must never change after any tokens have been minted.
     */
    function _sequentialUpTo() internal view virtual returns (uint256) {
        return type(uint256).max;
    }

    /**
     * @dev Returns the next token ID to be minted.
     */
    function _nextTokenId() internal view virtual returns (uint256) {
        return _currentIndex;
    }

    /**
     * @dev Returns the total number of tokens in existence.
     * Burned tokens will reduce the count.
     * To get the total number of tokens minted, please see {_totalMinted}.
     */
    function totalSupply() public view virtual override returns (uint256 result) {
        // Counter underflow is impossible as `_burnCounter` cannot be incremented
        // more than `_currentIndex + _spotMinted - _startTokenId()` times.
        unchecked {
            // With spot minting, the intermediate `result` can be temporarily negative,
            // and the computation must be unchecked.
            result = _currentIndex - _burnCounter - _startTokenId();
            if (_sequentialUpTo() != type(uint256).max) result += _spotMinted;
        }
    }

    /**
     * @dev Returns the total amount of tokens minted in the contract.
     */
    function _totalMinted() internal view virtual returns (uint256 result) {
        // Counter underflow is impossible as `_currentIndex` does not decrement,
        // and it is initialized to `_startTokenId()`.
        unchecked {
            result = _currentIndex - _startTokenId();
            if (_sequentialUpTo() != type(uint256).max) result += _spotMinted;
        }
    }

    /**
     * @dev Returns the total number of tokens burned.
     */
    function _totalBurned() internal view virtual returns (uint256) {
        return _burnCounter;
    }

    /**
     * @dev Returns the total number of tokens that are spot-minted.
     */
    function _totalSpotMinted() internal view virtual returns (uint256) {
        return _spotMinted;
    }

    // =============================================================
    //                    ADDRESS DATA OPERATIONS
    // =============================================================

    /**
     * @dev Returns the number of tokens in `owner`'s account.
     */
    function balanceOf(address owner) public view virtual override returns (uint256) {
        if (owner == address(0)) _revert(BalanceQueryForZeroAddress.selector);
        return _packedAddressData[owner] & _BITMASK_ADDRESS_DATA_ENTRY;
    }

    /**
     * Returns the number of tokens minted by `owner`.
     */
    function _numberMinted(address owner) internal view returns (uint256) {
        return (_packedAddressData[owner] >> _BITPOS_NUMBER_MINTED) & _BITMASK_ADDRESS_DATA_ENTRY;
    }

    /**
     * Returns the number of tokens burned by or on behalf of `owner`.
     */
    function _numberBurned(address owner) internal view returns (uint256) {
        return (_packedAddressData[owner] >> _BITPOS_NUMBER_BURNED) & _BITMASK_ADDRESS_DATA_ENTRY;
    }

    /**
     * Returns the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
     */
    function _getAux(address owner) internal view returns (uint64) {
        return uint64(_packedAddressData[owner] >> _BITPOS_AUX);
    }

    /**
     * Sets the auxiliary data for `owner`. (e.g. number of whitelist mint slots used).
     * If there are multiple variables, please pack them into a uint64.
     */
    function _setAux(address owner, uint64 aux) internal virtual {
        uint256 packed = _packedAddressData[owner];
        uint256 auxCasted;
        // Cast `aux` with assembly to avoid redundant masking.
        assembly {
            auxCasted := aux
        }
        packed = (packed & _BITMASK_AUX_COMPLEMENT) | (auxCasted << _BITPOS_AUX);
        _packedAddressData[owner] = packed;
    }

    // =============================================================
    //                            IERC165
    // =============================================================

    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30000 gas.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        // The interface IDs are constants representing the first 4 bytes
        // of the XOR of all function selectors in the interface.
        // See: [ERC165](https://eips.ethereum.org/EIPS/eip-165)
        // (e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`)
        return interfaceId == 0x01ffc9a7 // ERC165 interface ID for ERC165.
            || interfaceId == 0x80ac58cd // ERC165 interface ID for ERC721.
            || interfaceId == 0x5b5e139f; // ERC165 interface ID for ERC721Metadata.
    }

    // =============================================================
    //                        IERC721Metadata
    // =============================================================

    /**
     * @dev Returns the token collection name.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the token collection symbol.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        if (!_exists(tokenId)) _revert(URIQueryForNonexistentToken.selector);

        string memory baseURI = _baseURI();
        return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : "";
    }

    /**
     * @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, it can be overridden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }

    // =============================================================
    //                     OWNERSHIPS OPERATIONS
    // =============================================================

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) public view virtual override returns (address) {
        return address(uint160(_packedOwnershipOf(tokenId)));
    }

    /**
     * @dev Gas spent here starts off proportional to the maximum mint batch size.
     * It gradually moves to O(1) as tokens get transferred around over time.
     */
    function _ownershipOf(uint256 tokenId) internal view virtual returns (TokenOwnership memory) {
        return _unpackedOwnership(_packedOwnershipOf(tokenId));
    }

    /**
     * @dev Returns the unpacked `TokenOwnership` struct at `index`.
     */
    function _ownershipAt(uint256 index) internal view virtual returns (TokenOwnership memory) {
        return _unpackedOwnership(_packedOwnerships[index]);
    }

    /**
     * @dev Returns whether the ownership slot at `index` is initialized.
     * An uninitialized slot does not necessarily mean that the slot has no owner.
     */
    function _ownershipIsInitialized(uint256 index) internal view virtual returns (bool) {
        return _packedOwnerships[index] != 0;
    }

    /**
     * @dev Initializes the ownership slot minted at `index` for efficiency purposes.
     */
    function _initializeOwnershipAt(uint256 index) internal virtual {
        if (_packedOwnerships[index] == 0) {
            _packedOwnerships[index] = _packedOwnershipOf(index);
        }
    }

    /**
     * @dev Returns the packed ownership data of `tokenId`.
     */
    function _packedOwnershipOf(uint256 tokenId) private view returns (uint256 packed) {
        if (_startTokenId() <= tokenId) {
            packed = _packedOwnerships[tokenId];

            if (tokenId > _sequentialUpTo()) {
                if (_packedOwnershipExists(packed)) return packed;
                _revert(OwnerQueryForNonexistentToken.selector);
            }

            // If the data at the starting slot does not exist, start the scan.
            if (packed == 0) {
                if (tokenId >= _currentIndex) _revert(OwnerQueryForNonexistentToken.selector);
                // Invariant:
                // There will always be an initialized ownership slot
                // (i.e. `ownership.addr != address(0) && ownership.burned == false`)
                // before an unintialized ownership slot
                // (i.e. `ownership.addr == address(0) && ownership.burned == false`)
                // Hence, `tokenId` will not underflow.
                //
                // We can directly compare the packed value.
                // If the address is zero, packed will be zero.
                for (;;) {
                    unchecked {
                        packed = _packedOwnerships[--tokenId];
                    }
                    if (packed == 0) continue;
                    if (packed & _BITMASK_BURNED == 0) return packed;
                    // Otherwise, the token is burned, and we must revert.
                    // This handles the case of batch burned tokens, where only the burned bit
                    // of the starting slot is set, and remaining slots are left uninitialized.
                    _revert(OwnerQueryForNonexistentToken.selector);
                }
            }
            // Otherwise, the data exists and we can skip the scan.
            // This is possible because we have already achieved the target condition.
            // This saves 2143 gas on transfers of initialized tokens.
            // If the token is not burned, return `packed`. Otherwise, revert.
            if (packed & _BITMASK_BURNED == 0) return packed;
        }
        _revert(OwnerQueryForNonexistentToken.selector);
    }

    /**
     * @dev Returns the unpacked `TokenOwnership` struct from `packed`.
     */
    function _unpackedOwnership(uint256 packed) private pure returns (TokenOwnership memory ownership) {
        ownership.addr = address(uint160(packed));
        ownership.startTimestamp = uint64(packed >> _BITPOS_START_TIMESTAMP);
        ownership.burned = packed & _BITMASK_BURNED != 0;
        ownership.extraData = uint24(packed >> _BITPOS_EXTRA_DATA);
    }

    /**
     * @dev Packs ownership data into a single uint256.
     */
    function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) {
        assembly {
            // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
            owner := and(owner, _BITMASK_ADDRESS)
            // `owner | (block.timestamp << _BITPOS_START_TIMESTAMP) | flags`.
            result := or(owner, or(shl(_BITPOS_START_TIMESTAMP, timestamp()), flags))
        }
    }

    /**
     * @dev Returns the `nextInitialized` flag set if `quantity` equals 1.
     */
    function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) {
        // For branchless setting of the `nextInitialized` flag.
        assembly {
            // `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`.
            result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
        }
    }

    // =============================================================
    //                      APPROVAL OPERATIONS
    // =============================================================

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account. See {ERC721A-_approve}.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     */
    function approve(address to, uint256 tokenId) public payable virtual override {
        _approve(to, tokenId, true);
    }

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) public view virtual override returns (address) {
        if (!_exists(tokenId)) _revert(ApprovalQueryForNonexistentToken.selector);

        return _tokenApprovals[tokenId].value;
    }

    /**
     * @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 caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        _operatorApprovals[_msgSenderERC721A()][operator] = approved;
        emit ApprovalForAll(_msgSenderERC721A(), operator, approved);
    }

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /**
     * @dev Returns whether `tokenId` exists.
     *
     * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
     *
     * Tokens start existing when they are minted. See {_mint}.
     */
    function _exists(uint256 tokenId) internal view virtual returns (bool result) {
        if (_startTokenId() <= tokenId) {
            if (tokenId > _sequentialUpTo()) return _packedOwnershipExists(_packedOwnerships[tokenId]);

            if (tokenId < _currentIndex) {
                uint256 packed;
                while ((packed = _packedOwnerships[tokenId]) == 0) --tokenId;
                result = packed & _BITMASK_BURNED == 0;
            }
        }
    }

    /**
     * @dev Returns whether `packed` represents a token that exists.
     */
    function _packedOwnershipExists(uint256 packed) private pure returns (bool result) {
        assembly {
            // The following is equivalent to `owner != address(0) && burned == false`.
            // Symbolically tested.
            result := gt(and(packed, _BITMASK_ADDRESS), and(packed, _BITMASK_BURNED))
        }
    }

    /**
     * @dev Returns whether `msgSender` is equal to `approvedAddress` or `owner`.
     */
    function _isSenderApprovedOrOwner(address approvedAddress, address owner, address msgSender)
        private
        pure
        returns (bool result)
    {
        assembly {
            // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean.
            owner := and(owner, _BITMASK_ADDRESS)
            // Mask `msgSender` to the lower 160 bits, in case the upper bits somehow aren't clean.
            msgSender := and(msgSender, _BITMASK_ADDRESS)
            // `msgSender == owner || msgSender == approvedAddress`.
            result := or(eq(msgSender, owner), eq(msgSender, approvedAddress))
        }
    }

    /**
     * @dev Returns the storage slot and value for the approved address of `tokenId`.
     */
    function _getApprovedSlotAndAddress(uint256 tokenId)
        private
        view
        returns (uint256 approvedAddressSlot, address approvedAddress)
    {
        TokenApprovalRef storage tokenApproval = _tokenApprovals[tokenId];
        // The following is equivalent to `approvedAddress = _tokenApprovals[tokenId].value`.
        assembly {
            approvedAddressSlot := tokenApproval.slot
            approvedAddress := sload(approvedAddressSlot)
        }
    }

    // =============================================================
    //                      TRANSFER OPERATIONS
    // =============================================================

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *
     * 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) public payable virtual override {
        uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);

        // Mask `from` to the lower 160 bits, in case the upper bits somehow aren't clean.
        from = address(uint160(uint256(uint160(from)) & _BITMASK_ADDRESS));

        if (address(uint160(prevOwnershipPacked)) != from) _revert(TransferFromIncorrectOwner.selector);

        (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);

        // The nested ifs save around 20+ gas over a compound boolean condition.
        if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A())) {
            if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
        }

        _beforeTokenTransfers(from, to, tokenId, 1);

        // Clear approvals from the previous owner.
        assembly {
            if approvedAddress {
                // This is equivalent to `delete _tokenApprovals[tokenId]`.
                sstore(approvedAddressSlot, 0)
            }
        }

        // Underflow of the sender's balance is impossible because we check for
        // ownership above and the recipient's balance can't realistically overflow.
        // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
        unchecked {
            // We can directly increment and decrement the balances.
            --_packedAddressData[from]; // Updates: `balance -= 1`.
            ++_packedAddressData[to]; // Updates: `balance += 1`.

            // Updates:
            // - `address` to the next owner.
            // - `startTimestamp` to the timestamp of transfering.
            // - `burned` to `false`.
            // - `nextInitialized` to `true`.
            _packedOwnerships[tokenId] =
                _packOwnershipData(to, _BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked));

            // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
            if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
                uint256 nextTokenId = tokenId + 1;
                // If the next slot's address is zero and not burned (i.e. packed value is zero).
                if (_packedOwnerships[nextTokenId] == 0) {
                    // If the next slot is within bounds.
                    if (nextTokenId != _currentIndex) {
                        // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
                        _packedOwnerships[nextTokenId] = prevOwnershipPacked;
                    }
                }
            }
        }

        // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean.
        uint256 toMasked = uint256(uint160(to)) & _BITMASK_ADDRESS;
        assembly {
            // Emit the `Transfer` event.
            log4(
                0, // Start of data (0, since no data).
                0, // End of data (0, since no data).
                _TRANSFER_EVENT_SIGNATURE, // Signature.
                from, // `from`.
                toMasked, // `to`.
                tokenId // `tokenId`.
            )
        }
        if (toMasked == 0) _revert(TransferToZeroAddress.selector);

        _afterTokenTransfers(from, to, tokenId, 1);
    }

    /**
     * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) public payable virtual override {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @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 memory _data)
        public
        payable
        virtual
        override
    {
        transferFrom(from, to, tokenId);
        if (to.code.length != 0) {
            if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
                _revert(TransferToNonERC721ReceiverImplementer.selector);
            }
        }
    }

    /**
     * @dev Hook that is called before a set of serially-ordered token IDs
     * are about to be transferred. This includes minting.
     * And also called before burning one token.
     *
     * `startTokenId` - the first token ID to be transferred.
     * `quantity` - the amount to be transferred.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
     * transferred to `to`.
     * - When `from` is zero, `tokenId` will be minted for `to`.
     * - When `to` is zero, `tokenId` will be burned by `from`.
     * - `from` and `to` are never both zero.
     */
    function _beforeTokenTransfers(address from, address to, uint256 startTokenId, uint256 quantity) internal virtual {}

    /**
     * @dev Hook that is called after a set of serially-ordered token IDs
     * have been transferred. This includes minting.
     * And also called after one token has been burned.
     *
     * `startTokenId` - the first token ID to be transferred.
     * `quantity` - the amount to be transferred.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
     * transferred to `to`.
     * - When `from` is zero, `tokenId` has been minted for `to`.
     * - When `to` is zero, `tokenId` has been burned by `from`.
     * - `from` and `to` are never both zero.
     */
    function _afterTokenTransfers(address from, address to, uint256 startTokenId, uint256 quantity) internal virtual {}

    /**
     * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target contract.
     *
     * `from` - Previous owner of the given token ID.
     * `to` - Target address that will receive the token.
     * `tokenId` - Token ID to be transferred.
     * `_data` - Optional data to send along with the call.
     *
     * Returns whether the call correctly returned the expected magic value.
     */
    function _checkContractOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
        private
        returns (bool)
    {
        try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns (
            bytes4 retval
        ) {
            return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector;
        } catch (bytes memory reason) {
            if (reason.length == 0) {
                _revert(TransferToNonERC721ReceiverImplementer.selector);
            }
            assembly {
                revert(add(32, reason), mload(reason))
            }
        }
    }

    // =============================================================
    //                        MINT OPERATIONS
    // =============================================================

    /**
     * @dev Mints `quantity` tokens and transfers them to `to`.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `quantity` must be greater than 0.
     *
     * Emits a {Transfer} event for each mint.
     */
    function _mint(address to, uint256 quantity) internal virtual {
        uint256 startTokenId = _currentIndex;
        if (quantity == 0) _revert(MintZeroQuantity.selector);

        _beforeTokenTransfers(address(0), to, startTokenId, quantity);

        // Overflows are incredibly unrealistic.
        // `balance` and `numberMinted` have a maximum limit of 2**64.
        // `tokenId` has a maximum limit of 2**256.
        unchecked {
            // Updates:
            // - `address` to the owner.
            // - `startTimestamp` to the timestamp of minting.
            // - `burned` to `false`.
            // - `nextInitialized` to `quantity == 1`.
            _packedOwnerships[startTokenId] =
                _packOwnershipData(to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0));

            // Updates:
            // - `balance += quantity`.
            // - `numberMinted += quantity`.
            //
            // We can directly add to the `balance` and `numberMinted`.
            _packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);

            // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean.
            uint256 toMasked = uint256(uint160(to)) & _BITMASK_ADDRESS;

            if (toMasked == 0) _revert(MintToZeroAddress.selector);

            uint256 end = startTokenId + quantity;
            uint256 tokenId = startTokenId;

            if (end - 1 > _sequentialUpTo()) _revert(SequentialMintExceedsLimit.selector);

            do {
                assembly {
                    // Emit the `Transfer` event.
                    log4(
                        0, // Start of data (0, since no data).
                        0, // End of data (0, since no data).
                        _TRANSFER_EVENT_SIGNATURE, // Signature.
                        0, // `address(0)`.
                        toMasked, // `to`.
                        tokenId // `tokenId`.
                    )
                }
                // The `!=` check ensures that large values of `quantity`
                // that overflows uint256 will make the loop run out of gas.
            } while (++tokenId != end);

            _currentIndex = end;
        }
        _afterTokenTransfers(address(0), to, startTokenId, quantity);
    }

    /**
     * @dev Mints `quantity` tokens and transfers them to `to`.
     *
     * This function is intended for efficient minting only during contract creation.
     *
     * It emits only one {ConsecutiveTransfer} as defined in
     * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309),
     * instead of a sequence of {Transfer} event(s).
     *
     * Calling this function outside of contract creation WILL make your contract
     * non-compliant with the ERC721 standard.
     * For full ERC721 compliance, substituting ERC721 {Transfer} event(s) with the ERC2309
     * {ConsecutiveTransfer} event is only permissible during contract creation.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `quantity` must be greater than 0.
     *
     * Emits a {ConsecutiveTransfer} event.
     */
    function _mintERC2309(address to, uint256 quantity) internal virtual {
        uint256 startTokenId = _currentIndex;
        if (to == address(0)) _revert(MintToZeroAddress.selector);
        if (quantity == 0) _revert(MintZeroQuantity.selector);
        if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) _revert(MintERC2309QuantityExceedsLimit.selector);

        _beforeTokenTransfers(address(0), to, startTokenId, quantity);

        // Overflows are unrealistic due to the above check for `quantity` to be below the limit.
        unchecked {
            // Updates:
            // - `balance += quantity`.
            // - `numberMinted += quantity`.
            //
            // We can directly add to the `balance` and `numberMinted`.
            _packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);

            // Updates:
            // - `address` to the owner.
            // - `startTimestamp` to the timestamp of minting.
            // - `burned` to `false`.
            // - `nextInitialized` to `quantity == 1`.
            _packedOwnerships[startTokenId] =
                _packOwnershipData(to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0));

            if (startTokenId + quantity - 1 > _sequentialUpTo()) _revert(SequentialMintExceedsLimit.selector);

            emit ConsecutiveTransfer(startTokenId, startTokenId + quantity - 1, address(0), to);

            _currentIndex = startTokenId + quantity;
        }
        _afterTokenTransfers(address(0), to, startTokenId, quantity);
    }

    /**
     * @dev Safely mints `quantity` tokens and transfers them to `to`.
     *
     * Requirements:
     *
     * - If `to` refers to a smart contract, it must implement
     * {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
     * - `quantity` must be greater than 0.
     *
     * See {_mint}.
     *
     * Emits a {Transfer} event for each mint.
     */
    function _safeMint(address to, uint256 quantity, bytes memory _data) internal virtual {
        _mint(to, quantity);

        unchecked {
            if (to.code.length != 0) {
                uint256 end = _currentIndex;
                uint256 index = end - quantity;
                do {
                    if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
                        _revert(TransferToNonERC721ReceiverImplementer.selector);
                    }
                } while (index < end);
                // This prevents reentrancy to `_safeMint`.
                // It does not prevent reentrancy to `_safeMintSpot`.
                if (_currentIndex != end) revert();
            }
        }
    }

    /**
     * @dev Equivalent to `_safeMint(to, quantity, '')`.
     */
    function _safeMint(address to, uint256 quantity) internal virtual {
        _safeMint(to, quantity, "");
    }

    /**
     * @dev Mints a single token at `tokenId`.
     *
     * Note: A spot-minted `tokenId` that has been burned can be re-minted again.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` must be greater than `_sequentialUpTo()`.
     * - `tokenId` must not exist.
     *
     * Emits a {Transfer} event for each mint.
     */
    function _mintSpot(address to, uint256 tokenId) internal virtual {
        if (tokenId <= _sequentialUpTo()) _revert(SpotMintTokenIdTooSmall.selector);
        uint256 prevOwnershipPacked = _packedOwnerships[tokenId];
        if (_packedOwnershipExists(prevOwnershipPacked)) _revert(TokenAlreadyExists.selector);

        _beforeTokenTransfers(address(0), to, tokenId, 1);

        // Overflows are incredibly unrealistic.
        // The `numberMinted` for `to` is incremented by 1, and has a max limit of 2**64 - 1.
        // `_spotMinted` is incremented by 1, and has a max limit of 2**256 - 1.
        unchecked {
            // Updates:
            // - `address` to the owner.
            // - `startTimestamp` to the timestamp of minting.
            // - `burned` to `false`.
            // - `nextInitialized` to `true` (as `quantity == 1`).
            _packedOwnerships[tokenId] =
                _packOwnershipData(to, _nextInitializedFlag(1) | _nextExtraData(address(0), to, prevOwnershipPacked));

            // Updates:
            // - `balance += 1`.
            // - `numberMinted += 1`.
            //
            // We can directly add to the `balance` and `numberMinted`.
            _packedAddressData[to] += (1 << _BITPOS_NUMBER_MINTED) | 1;

            // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean.
            uint256 toMasked = uint256(uint160(to)) & _BITMASK_ADDRESS;

            if (toMasked == 0) _revert(MintToZeroAddress.selector);

            assembly {
                // Emit the `Transfer` event.
                log4(
                    0, // Start of data (0, since no data).
                    0, // End of data (0, since no data).
                    _TRANSFER_EVENT_SIGNATURE, // Signature.
                    0, // `address(0)`.
                    toMasked, // `to`.
                    tokenId // `tokenId`.
                )
            }

            ++_spotMinted;
        }

        _afterTokenTransfers(address(0), to, tokenId, 1);
    }

    /**
     * @dev Safely mints a single token at `tokenId`.
     *
     * Note: A spot-minted `tokenId` that has been burned can be re-minted again.
     *
     * Requirements:
     *
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}.
     * - `tokenId` must be greater than `_sequentialUpTo()`.
     * - `tokenId` must not exist.
     *
     * See {_mintSpot}.
     *
     * Emits a {Transfer} event.
     */
    function _safeMintSpot(address to, uint256 tokenId, bytes memory _data) internal virtual {
        _mintSpot(to, tokenId);

        unchecked {
            if (to.code.length != 0) {
                uint256 currentSpotMinted = _spotMinted;
                if (!_checkContractOnERC721Received(address(0), to, tokenId, _data)) {
                    _revert(TransferToNonERC721ReceiverImplementer.selector);
                }
                // This prevents reentrancy to `_safeMintSpot`.
                // It does not prevent reentrancy to `_safeMint`.
                if (_spotMinted != currentSpotMinted) revert();
            }
        }
    }

    /**
     * @dev Equivalent to `_safeMintSpot(to, tokenId, '')`.
     */
    function _safeMintSpot(address to, uint256 tokenId) internal virtual {
        _safeMintSpot(to, tokenId, "");
    }

    // =============================================================
    //                       APPROVAL OPERATIONS
    // =============================================================

    /**
     * @dev Equivalent to `_approve(to, tokenId, false)`.
     */
    function _approve(address to, uint256 tokenId) internal virtual {
        _approve(to, tokenId, false);
    }

    /**
     * @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:
     *
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function _approve(address to, uint256 tokenId, bool approvalCheck) internal virtual {
        address owner = ownerOf(tokenId);

        if (approvalCheck && _msgSenderERC721A() != owner) {
            if (!isApprovedForAll(owner, _msgSenderERC721A())) {
                _revert(ApprovalCallerNotOwnerNorApproved.selector);
            }
        }

        _tokenApprovals[tokenId].value = to;
        emit Approval(owner, to, tokenId);
    }

    // =============================================================
    //                        BURN OPERATIONS
    // =============================================================

    /**
     * @dev Equivalent to `_burn(tokenId, false)`.
     */
    function _burn(uint256 tokenId) internal virtual {
        _burn(tokenId, false);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
        uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);

        address from = address(uint160(prevOwnershipPacked));

        (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);

        if (approvalCheck) {
            // The nested ifs save around 20+ gas over a compound boolean condition.
            if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A())) {
                if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
            }
        }

        _beforeTokenTransfers(from, address(0), tokenId, 1);

        // Clear approvals from the previous owner.
        assembly {
            if approvedAddress {
                // This is equivalent to `delete _tokenApprovals[tokenId]`.
                sstore(approvedAddressSlot, 0)
            }
        }

        // Underflow of the sender's balance is impossible because we check for
        // ownership above and the recipient's balance can't realistically overflow.
        // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256.
        unchecked {
            // Updates:
            // - `balance -= 1`.
            // - `numberBurned += 1`.
            //
            // We can directly decrement the balance, and increment the number burned.
            // This is equivalent to `packed -= 1; packed += 1 << _BITPOS_NUMBER_BURNED;`.
            _packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;

            // Updates:
            // - `address` to the last owner.
            // - `startTimestamp` to the timestamp of burning.
            // - `burned` to `true`.
            // - `nextInitialized` to `true`.
            _packedOwnerships[tokenId] = _packOwnershipData(
                from,
                (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
            );

            // If the next slot may not have been initialized (i.e. `nextInitialized == false`) .
            if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
                uint256 nextTokenId = tokenId + 1;
                // If the next slot's address is zero and not burned (i.e. packed value is zero).
                if (_packedOwnerships[nextTokenId] == 0) {
                    // If the next slot is within bounds.
                    if (nextTokenId != _currentIndex) {
                        // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`.
                        _packedOwnerships[nextTokenId] = prevOwnershipPacked;
                    }
                }
            }
        }

        emit Transfer(from, address(0), tokenId);
        _afterTokenTransfers(from, address(0), tokenId, 1);

        // Overflow not possible, as `_burnCounter` cannot be exceed `_currentIndex + _spotMinted` times.
        unchecked {
            _burnCounter++;
        }
    }

    // =============================================================
    //                     EXTRA DATA OPERATIONS
    // =============================================================

    /**
     * @dev Directly sets the extra data for the ownership data `index`.
     */
    function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {
        uint256 packed = _packedOwnerships[index];
        if (packed == 0) _revert(OwnershipNotInitializedForExtraData.selector);
        uint256 extraDataCasted;
        // Cast `extraData` with assembly to avoid redundant masking.
        assembly {
            extraDataCasted := extraData
        }
        packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA);
        _packedOwnerships[index] = packed;
    }

    /**
     * @dev Called during each token transfer to set the 24bit `extraData` field.
     * Intended to be overridden by the cosumer contract.
     *
     * `previousExtraData` - the value of `extraData` before transfer.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
     * transferred to `to`.
     * - When `from` is zero, `tokenId` will be minted for `to`.
     * - When `to` is zero, `tokenId` will be burned by `from`.
     * - `from` and `to` are never both zero.
     */
    function _extraData(address from, address to, uint24 previousExtraData) internal view virtual returns (uint24) {}

    /**
     * @dev Returns the next extra data for the packed ownership data.
     * The returned result is shifted into position.
     */
    function _nextExtraData(address from, address to, uint256 prevOwnershipPacked) private view returns (uint256) {
        uint24 extraData = uint24(prevOwnershipPacked >> _BITPOS_EXTRA_DATA);
        return uint256(_extraData(from, to, extraData)) << _BITPOS_EXTRA_DATA;
    }

    // =============================================================
    //                       OTHER OPERATIONS
    // =============================================================

    /**
     * @dev Returns the message sender (defaults to `msg.sender`).
     *
     * If you are writing GSN compatible contracts, you need to override this function.
     */
    function _msgSenderERC721A() internal view virtual returns (address) {
        return msg.sender;
    }

    /**
     * @dev Converts a uint256 to its ASCII string decimal representation.
     */
    function _toString(uint256 value) internal pure virtual returns (string memory str) {
        assembly {
            // The maximum value of a uint256 contains 78 digits (1 byte per digit), but
            // we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
            // We will need 1 word for the trailing zeros padding, 1 word for the length,
            // and 3 words for a maximum of 78 digits. Total: 5 * 0x20 = 0xa0.
            let m := add(mload(0x40), 0xa0)
            // Update the free memory pointer to allocate.
            mstore(0x40, m)
            // Assign the `str` to the end.
            str := sub(m, 0x20)
            // Zeroize the slot after the string.
            mstore(str, 0)

            // Cache the end of the memory to calculate the length later.
            let end := str

            // We write the string from rightmost digit to leftmost digit.
            // The following is essentially a do-while loop that also handles the zero case.
            // prettier-ignore
            for { let temp := value } 1 {} {
                str := sub(str, 1)
                // Write the character to the pointer.
                // The ASCII index of the '0' character is 48.
                mstore8(str, add(48, mod(temp, 10)))
                // Keep dividing `temp` until zero.
                temp := div(temp, 10)
                // prettier-ignore
                if iszero(temp) { break }
            }

            let length := sub(end, str)
            // Move the pointer 32 bytes leftwards to make room for the length.
            str := sub(str, 0x20)
            // Store the length.
            mstore(str, length)
        }
    }

    /**
     * @dev For more efficient reverts.
     */
    function _revert(bytes4 errorSelector) internal pure {
        assembly {
            mstore(0x00, errorSelector)
            revert(0x00, 0x04)
        }
    }
}
IERC721A.sol 294 lines
// SPDX-License-Identifier: MIT
// ERC721A Contracts v4.3.0
// Creator: Chiru Labs

pragma solidity ^0.8.4;

/**
 * @dev Interface of ERC721A.
 */
interface IERC721A {
    /**
     * The caller must own the token or be an approved operator.
     */
    error ApprovalCallerNotOwnerNorApproved();

    /**
     * The token does not exist.
     */
    error ApprovalQueryForNonexistentToken();

    /**
     * Cannot query the balance for the zero address.
     */
    error BalanceQueryForZeroAddress();

    /**
     * Cannot mint to the zero address.
     */
    error MintToZeroAddress();

    /**
     * The quantity of tokens minted must be more than zero.
     */
    error MintZeroQuantity();

    /**
     * The token does not exist.
     */
    error OwnerQueryForNonexistentToken();

    /**
     * The caller must own the token or be an approved operator.
     */
    error TransferCallerNotOwnerNorApproved();

    /**
     * The token must be owned by `from`.
     */
    error TransferFromIncorrectOwner();

    /**
     * Cannot safely transfer to a contract that does not implement the
     * ERC721Receiver interface.
     */
    error TransferToNonERC721ReceiverImplementer();

    /**
     * Cannot transfer to the zero address.
     */
    error TransferToZeroAddress();

    /**
     * The token does not exist.
     */
    error URIQueryForNonexistentToken();

    /**
     * The `quantity` minted with ERC2309 exceeds the safety limit.
     */
    error MintERC2309QuantityExceedsLimit();

    /**
     * The `extraData` cannot be set on an unintialized ownership slot.
     */
    error OwnershipNotInitializedForExtraData();

    /**
     * `_sequentialUpTo()` must be greater than `_startTokenId()`.
     */
    error SequentialUpToTooSmall();

    /**
     * The `tokenId` of a sequential mint exceeds `_sequentialUpTo()`.
     */
    error SequentialMintExceedsLimit();

    /**
     * Spot minting requires a `tokenId` greater than `_sequentialUpTo()`.
     */
    error SpotMintTokenIdTooSmall();

    /**
     * Cannot mint over a token that already exists.
     */
    error TokenAlreadyExists();

    /**
     * The feature is not compatible with spot mints.
     */
    error NotCompatibleWithSpotMints();

    // =============================================================
    //                            STRUCTS
    // =============================================================

    struct TokenOwnership {
        // The address of the owner.
        address addr;
        // Stores the start time of ownership with minimal overhead for tokenomics.
        uint64 startTimestamp;
        // Whether the token has been burned.
        bool burned;
        // Arbitrary data similar to `startTimestamp` that can be set via {_extraData}.
        uint24 extraData;
    }

    // =============================================================
    //                         TOKEN COUNTERS
    // =============================================================

    /**
     * @dev Returns the total number of tokens in existence.
     * Burned tokens will reduce the count.
     * To get the total number of tokens minted, please see {_totalMinted}.
     */
    function totalSupply() external view returns (uint256);

    // =============================================================
    //                            IERC165
    // =============================================================

    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified)
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);

    // =============================================================
    //                            IERC721
    // =============================================================

    /**
     * @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`,
     * checking first that contract recipients are aware of the ERC721 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 be 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, bytes calldata data) external payable;

    /**
     * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external payable;

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {safeTransferFrom}
     * whenever possible.
     *
     * 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 payable;

    /**
     * @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 payable;

    /**
     * @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 caller.
     *
     * 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);

    // =============================================================
    //                        IERC721Metadata
    // =============================================================

    /**
     * @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);

    // =============================================================
    //                           IERC2309
    // =============================================================

    /**
     * @dev Emitted when tokens in `fromTokenId` to `toTokenId`
     * (inclusive) is transferred from `from` to `to`, as defined in the
     * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309) standard.
     *
     * See {_mintERC2309} for more details.
     */
    event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed from, address indexed to);
}

Read Contract

DevWallet 0xb115e4df → address
ELMNT_BB 0x816b44fd → address
HolderVault 0xf7cc662d → address
claimRewardsIncentiveFee 0x8b05c538 → uint32
dailyAuctionLimit 0xdb1992b3 → uint256
distributeTreasuryIncentiveFee 0x9d813593 → uint32
distributionInterval 0x71201a0e → uint32
distributionLimit 0xdf3851e3 → uint256
distributionWhitelist 0x9aa695e1 → bool
getNextTreasuryDistribution 0x5fb56896 → uint256
getStakesClaimableRewardsPerId 0x68215fcb → uint256[]
getTitanXForAuctions 0xab2da610 → uint256
heliosDeviation 0xd5472a9c → uint32
infernoDeviation 0x3929a4af → uint32
isAuctionAvailable 0x05134362 → bool
lastAuctionDay 0x653a34e2 → uint32
lastDistribution 0xa717639c → uint32
lastStakeDay 0xba29281c → uint32
minStakeAmount 0xf1887684 → uint256
owner 0x8da5cb5b → address
pendingOwner 0xe30c3978 → address
secondsAgo 0x633dd145 → uint32
supportsInterface 0x01ffc9a7 → bool
treasury777Balance 0x947b43f3 → uint256
treasuryBalance 0x313dab20 → uint256

Write Contract 21 functions

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

acceptOwnership 0x79ba5097
No parameters
claimAuctions 0x33016eb7
uint64[] ids
claimRewards 0xf1127f1a
uint160[] ids
distribute777Treasury 0x209164cb
uint256 infernoMinAmountOut
uint256 heliosMinAmountOut
uint256 e280MinAmountOut
uint256 deadline
distributeTreasury 0xddbe3c1d
uint256 infernoMinAmountOut
uint256 heliosMinAmountOut
uint256 e280MinAmountOut
uint256 deadline
enterAuction 0x74f7cd4e
No parameters
onBurn 0x45a1b92c
address
uint256 amount
renounceOwnership 0x715018a6
No parameters
setClaimRewardsIncentiveFee 0x85c9c051
uint32 size
setDailyAuctionLimit 0x64c45409
uint256 limit
setDistributeTreasuryIncentiveFee 0x833be384
uint32 size
setDistributionInterval 0x2c935467
uint32 limit
setDistributionLimit 0xe37750e5
uint256 limit
setDistributionWhitelist 0x403755f5
address[] accounts
bool isAllowed
setE280BuyBurn 0x8e805a7c
address _address
setHeliosDeviation 0xf22bb62e
uint32 limit
setInfernoDeviation 0xfca2086b
uint32 limit
setMinStakeAmount 0xeb4af045
uint256 limit
setSecondsAgo 0x1ad7b127
uint32 limit
startStake 0x28e9d35b
No parameters
transferOwnership 0xf2fde38b
address newOwner

Recent Transactions

No transactions found for this address