Cryo Explorer Ethereum Mainnet

Address Contract Verified

Address 0x7d93d533674C71a70c31dd583efCD4aC6D59D839
Balance 0 ETH
Nonce 1
Code Size 12989 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

12989 bytes
0x608080604052600436101561008b575b50361561001b57600080fd5b73c02aaa39b223fe8d0a0e5c4f27ead9083c756cc23b1561008657604051630d0e30db60e41b81526000816004813473c02aaa39b223fe8d0a0e5c4f27ead9083c756cc25af1801561007a5761006d57005b6000610078916128f4565b005b6040513d6000823e3d90fd5b600080fd5b600090813560e01c90816204dce3146127d6575080630c3ecffe146127b1578063120ec08614612793578063138a572c146127195780631b04b77d146126d257806323e27a64146125ad57806337099065146125385780634412161a1461245e5780635283837e146124305780635c3983c21461218a57806365c228c914611f50578063665f8efb146115ca578063670cdc4f146111bc57806368ffd4fb146111875780636ed7ce531461114e578063715018a6146110e957806372618aac1461089e578063786226d31461085f57806379ba5097146107da5780637c3911c8146105f25780638540ac55146105cb5780638da5cb5b146105a45780639e7029b514610586578063aa2dbae514610537578063c3c12d59146104e9578063c71f815d14610474578063cddd89b814610413578063d32d459914610380578063e30c397814610357578063f2c13242146102ec578063f2fde38b1461027f578063f46aa059146102635763fab3a7930361000f573461026057602036600319011261026057610217612895565b61021f612e1b565b63ffffffff811615610251576001805463ffffffff60d01b191660d09290921b63ffffffff60d01b1691909117905580f35b63af458c0760e01b8252600482fd5b80fd5b503461026057806003193601126102605761027c612d2c565b80f35b50346102605760203660031901126102605761029961280c565b6102a1612e1b565b600180546001600160a01b0319166001600160a01b0392831690811790915582549091167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e227008380a380f35b5034610260576020366003190112610260576080906040906001600160a01b0361031461280c565b1681526006602052206001815491015463ffffffff6040519261033a8460ff8316612822565b61ffff8160081c16602085015260181c1660408301526060820152f35b50346102605780600319360112610260576001546040516001600160a01b039091168152602090f35b5034610260576020366003190112610260576001600160a01b036103a261280c565b168152600b60205260408120604051918260208354918281520192825260208220915b8181106103f4576103f0856103dc818703826128f4565b604051918291602083526020830190612845565b0390f35b82546001600160a01b03168452602090930192600192830192016103c5565b50346102605760403660031901126102605761042d61280c565b6001600160a01b03168152600b602052604081208054602435929083101561026057602061045b8484612a66565b905460405160039290921b1c6001600160a01b03168152f35b50346102605760203660031901126102605761048e612895565b610496612e1b565b63ffffffff8116156104da576001805463ffffffff60b01b191660b09290921b63ffffffff60b01b169190911790556000805160206132688339815191528180a180f35b632b0039c760e21b8252600482fd5b50346102605760203660031901126102605760409081906001600160a01b0361051061280c565b168152600a602052205462ffffff82519160018060a01b038116835260a01c166020820152f35b5034610260576020366003190112610260576103f090610572906040906001600160a01b0361056461280c565b168152600960205220612981565b604051918291602083526020830190612a25565b50346102605780600319360112610260576020600254604051908152f35b5034610260578060031936011261026057546040516001600160a01b039091168152602090f35b5034610260578060031936011261026057602063ffffffff60015460d01c16604051908152f35b50346102605760c03660031901126102605761060c61280c565b6024356001600160a01b038116908190036107d65760443562ffffff81168091036107d2576084359261ffff84168094036107ce5760a4359063ffffffff82168092036107ca5761065b612e1b565b6001600160a01b031693841580156107c2575b6107b35761067b85612fda565b156107a4576040519161068d836128a8565b6002835260208301918252604083019081526060830191606435835286885260066020526040882093516003811015610790578454915162ffffff1990921660ff9091161760089190911b62ffff00161783556001919061070f9063ffffffff905b51855466ffffffff0000001916911660181b66ffffffff00000016178455565b5191015560405191610720836128d9565b82526020808301918252838552600a815260408086209351845493516001600160b81b03199094166001600160a01b03919091161760a09390931b62ffffff60a01b1692909217909255918352600890528120805460ff191690556000805160206132688339815191528180a180f35b634e487b7160e01b89526021600452602489fd5b63de5db6f760e01b8652600486fd5b63d92e233d60e01b8652600486fd5b50831561066e565b8580fd5b8480fd5b8380fd5b8280fd5b5034610260578060031936011261026057600154336001600160a01b039091160361084c57600180546001600160a01b0319908116909155815433918116821783556001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08380a380f35b63118cdaa760e01b815233600452602490fd5b50346102605760203660031901126102605760209060ff906040906001600160a01b0361088a61280c565b168152600884522054166040519015158152f35b5034610260576060366003190112610260576108b861280c565b906024359160443590604051633af32abf60e01b8152336004820152602081602481739634e1cdc25106b892a8ccba014441e8a1e842a15afa908115610e285784916110af575b50156110a15761090e81612ac6565b94929193904210611092578115611083576001600160a01b031680865260076020526040862042905593600381101561106f5760018103610c3957508261095491612d1f565b90604051636eb1769f60e11b8152306004820152737a250d5630b4cf539739df2c5dacb4c659f2488d6024820152602081604481885afa8015610c2e5783908790610bf8575b6109a49250612aa3565b858060405192602084019063095ea7b360e01b8252737a250d5630b4cf539739df2c5dacb4c659f2488d60248601526044850152604484526109e76064856128f4565b83519082895af16109f66131d6565b81610bbd575b5080610bb3575b15610b5b575b50838552600b602052604085209560405190816020895491828152019888526020882090885b818110610b3c57505050610a4a8288999896979803836128f4565b737a250d5630b4cf539739df2c5dacb4c659f2488d3b156107ce57610a8785936040519586948594635c11d79560e01b8652309260048701612eb9565b038183737a250d5630b4cf539739df2c5dacb4c659f2488d5af18015610b3157610b1c575b5050610af591610af0610ae2925b60405163a9059cbb60e01b602082015233602482015260448101919091529283906064820190565b03601f1981018452836128f4565b613160565b7fb1adc1caa391260f22ed6f4e0d2dc9042c252c43465666a433197f1e44a3e3df8180a180f35b81610b26916128f4565b6107d6578238610aac565b6040513d84823e3d90fd5b82546001600160a01b03168b526020909a019960019283019201610a2f565b610bad90610ba760405163095ea7b360e01b6020820152737a250d5630b4cf539739df2c5dacb4c659f2488d602482015288604482015260448152610ba16064826128f4565b87613160565b85613160565b38610a09565b50843b1515610a03565b8051801592508215610bd2575b5050386109fc565b8192509060209181010312610bf4576020610bed9101612d12565b3880610bca565b8680fd5b50506020813d602011610c26575b81610c13602093836128f4565b8101031261008657826109a4915161099a565b3d9150610c06565b6040513d88823e3d90fd5b94959294919392916002036110605784610c5291612d1f565b604051636eb1769f60e11b815230600482015273e592427a0aece92de3edee1f18e0157c058615646024820152602081604481875afa8015611055578290889061101f575b610ca19250612aa3565b868060405192602084019063095ea7b360e01b825273e592427a0aece92de3edee1f18e0157c058615646024860152604485015260448452610ce46064856128f4565b83519082885af1610cf36131d6565b81610fe4575b5080610fda575b15610f82575b508286526008602052604086205460ff1615610e4757828652600960205260408620916040519260a084018481106001600160401b03821117610e335791610d58610da0949260209694604052612981565b835284830191308352604084019788526060840190815260808401918252604051978895869563c04b8d5960e01b87528860048801525160a0602488015260c4870190612a25565b93516001600160a01b031660448601525160648501525160848401525160a483015203818773e592427a0aece92de3edee1f18e0157c058615645af18015610e2857610af593610ae293610af092610df9575b50610aba565b610e1a9060203d602011610e21575b610e1281836128f4565b810190612a94565b5038610df3565b503d610e08565b6040513d86823e3d90fd5b634e487b7160e01b89526041600452602489fd5b9060209391838752600a8552604087209260405193610e65856128d9565b546001600160a01b03811680865260a09190911c62ffffff16969094018690526040519561010087016001600160401b03811188821017610f6e57604090815286885260208089019687528882019283523060608a0190815260808a0194855260a08a0195865260c08a0196875260e08a018c8152925163414bf38960e01b815299516001600160a01b0390811660048c01529751881660248b0152925162ffffff1660448a015291518616606489015291516084880152915160a4870152915160c4860152905190911660e484015282610104818773e592427a0aece92de3edee1f18e0157c058615645af18015610e2857610af593610ae293610af092610df95750610aba565b634e487b7160e01b8a52604160045260248afd5b610fd490610fce60405163095ea7b360e01b602082015273e592427a0aece92de3edee1f18e0157c05861564602482015289604482015260448152610fc86064826128f4565b86613160565b84613160565b38610d06565b50833b1515610d00565b8051801592508215610ff9575b505038610cf9565b819250906020918101031261101b5760206110149101612d12565b3880610ff1565b8780fd5b50506020813d60201161104d575b8161103a602093836128f4565b810103126100865781610ca19151610c97565b3d915061102d565b6040513d89823e3d90fd5b632b0039c760e21b8652600486fd5b634e487b7160e01b86526021600452602486fd5b631e9acf1760e31b8652600486fd5b63b0782df760e01b8652600486fd5b6282b42960e81b8352600483fd5b90506020813d6020116110e1575b816110ca602093836128f4565b810103126107d2576110db90612d12565b386108ff565b3d91506110bd565b5034610260578060031936011261026057611102612e1b565b600180546001600160a01b03199081169091558154908116825581906001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a380f35b5034610260576020366003190112610260576020906040906001600160a01b0361117661280c565b168152600783522054604051908152f35b5034610260576020366003190112610260576111a1612e1b565b6004356002556000805160206132688339815191528180a180f35b503461026057604036600319011261026057604051633af32abf60e01b8152336004820152602081602481739634e1cdc25106b892a8ccba014441e8a1e842a15afa908115610b31578291611590575b50156115825761121a612c38565b919091421061157357801561156457816112379142600355612d1f565b604051636eb1769f60e11b8152306004820152737a250d5630b4cf539739df2c5dacb4c659f2488d602482015260208160448173058e7b30200d001130232e8fbfdf900590e0baa95afa8015610e28578290859061152e575b61129a9250612aa3565b838060405192602084019063095ea7b360e01b8252737a250d5630b4cf539739df2c5dacb4c659f2488d60248601526044850152604484526112dd6064856128f4565b8351908273058e7b30200d001130232e8fbfdf900590e0baa95af16113006131d6565b816114f7575b50806114d9575b1561148d575b50826040516113236060826128f4565b60028152604036602083013773058e7b30200d001130232e8fbfdf900590e0baa961134d82612cf5565b5273aa26754dd0c8310cb70f3b66daeab52c8cff3c3061136c82612d02565b52737a250d5630b4cf539739df2c5dacb4c659f2488d3b15611489576113b1926040519384928392635c11d79560e01b84526024359130916004359060048701612eb9565b038183737a250d5630b4cf539739df2c5dacb4c659f2488d5af1801561147e57611460575b5061141161141f611439926113e9612d2c565b60405163a9059cbb60e01b602082015233602482015260448101919091529182906064820190565b03601f1981018352826128f4565b73058e7b30200d001130232e8fbfdf900590e0baa9613160565b7fa0fd03f88165f654ebe32949d70ea031e17b72959483ac8c9ebe73888bb601278180a180f35b61141f836114756114399495611411946128f4565b939250506113d6565b6040513d85823e3d90fd5b5080fd5b6114d39061141f60405163095ea7b360e01b6020820152737a250d5630b4cf539739df2c5dacb4c659f2488d60248201528660448201526044815261141f6064826128f4565b38611313565b5073058e7b30200d001130232e8fbfdf900590e0baa93b151561130d565b805180159250821561150c575b505038611306565b81925090602091810103126107ce5760206115279101612d12565b3880611504565b50506020813d60201161155c575b81611549602093836128f4565b810103126107d2578161129a9151611290565b3d915061153c565b631e9acf1760e31b8352600483fd5b63b0782df760e01b8352600483fd5b6282b42960e81b8152600490fd5b90506020813d6020116115c2575b816115ab602093836128f4565b81010312611489576115bc90612d12565b3861120c565b3d915061159e565b503461026057806003193601126102605763ffffffff60015460d01c16604051633850c7bd60e01b815260e081600481732c83c54c5612bfd62a78124d4a0ea001278a689c5afa801561147e5783918491611ec0575b5061ffff16908115611e965761ffff60019116019061ffff8211611c415761ffff90816040519363252c09d760e01b85521606166004820152608081602481732c83c54c5612bfd62a78124d4a0ea001278a689c5afa90811561147e5783908492611e71575b509015611df2575b63ffffffff1663ffffffff42160363ffffffff8111611c175790818163ffffffff80941610611dea575b50168015611dc057604051906116cf6060836128f4565b6002825260208201916040368437816116e782612cf5565b52836116f282612d02565b5283604051809463883bdbfd60e01b825260248201936020600484015251809452604482019093835b818110611d9e575050819293500381732c83c54c5612bfd62a78124d4a0ea001278a689c5afa91821561147e5783908493611c8c575b5061176861175e82612d02565b5160060b91612cf5565b5160060b900391667fffffffffffff198312667fffffffffffff841317611c41576001600160a01b0361179a82612d02565b5116906001600160a01b03906117af90612cf5565b51169003906001600160a01b038211611c41578060060b9260060b8315611c7857667fffffffffffff198114600019851416611c645783810560020b938582129182611c55575b5050611c2b575b6001600160a01b038181026001600160c01b0316919091049003611c175760201b640100000000600160c01b031615611c035760020b9080821215611bfd57818103915b620d89e88311611bee576001831615611bdc576001600160881b036ffffcb933bd6fad37aa2d162d1a5940015b169260028116611bc0575b60048116611ba4575b60088116611b88575b60108116611b6c575b60208116611b50575b60408116611b34575b60808116611b18575b6101008116611afc575b6102008116611ae0575b6104008116611ac4575b6108008116611aa8575b6110008116611a8c575b6120008116611a70575b6140008116611a54575b6180008116611a38575b620100008116611a1c575b620200008116611a01575b6204000081166119e6575b62080000166119cd575b81126119a6575b60209163ffffffff811661199e5781905b831c60ff91909116016001600160a01b031690506fffffffffffffffffffffffffffffffff81116119875761197a8161197f92612c0e565b6130fa565b604051908152f35b6119948161199992613035565b613094565b61197f565b600190611942565b81156119b9576000199190910490611931565b634e487b7160e01b81526012600452602490fd5b6b048a170391f7dc42444e8fa290920260801c9161192a565b6d2216e584f5fa1ea926041bedfe9890930260801c92611920565b926e5d6af8dedb81196699c329225ee6040260801c92611915565b926f09aa508b5b7a84e1c677de54f3e99bc90260801c9261190a565b926f31be135f97d08fd981231505542fcfa60260801c926118ff565b926f70d869a156d2a1b890bb3df62baf32f70260801c926118f5565b926fa9f746462d870fdf8a65dc1f90e061e50260801c926118eb565b926fd097f3bdfd2022b8845ad8f792aa58250260801c926118e1565b926fe7159475a2c29b7443b29c7fa6e889d90260801c926118d7565b926ff3392b0822b70005940c7a398e4b70f30260801c926118cd565b926ff987a7253ac413176f2b074cf7815e540260801c926118c3565b926ffcbe86c7900a88aedcffc83b479aa3a40260801c926118b9565b926ffe5dee046a99a2a811c461f1969c30530260801c926118af565b926fff2ea16466c96a3843ec78b326b528610260801c926118a6565b926fff973b41fa98c081472e6896dfb254c00260801c9261189d565b926fffcb9843d60f6159c9db58835c9266440260801c92611894565b926fffe5caca7e10e4e61c3624eaa0941cd00260801c9261188b565b926ffff2e50f5f656932ef12357cf3c7fdcc0260801c92611882565b926ffff97272373d413259a46990580e213a0260801c92611879565b6001600160881b03600160801b61186e565b6315e4079d60e11b8252600482fd5b81611841565b634e487b7160e01b82526012600452602482fd5b634e487b7160e01b83526011600452602483fd5b91627fffff198114611c415760001901916117fd565b634e487b7160e01b84526011600452602484fd5b0760060b1515905038806117f6565b634e487b7160e01b85526011600452602485fd5b634e487b7160e01b85526012600452602485fd5b9250503d8084843e611c9e81846128f4565b8201916040818403126107d25780516001600160401b0381116107ce5781019083601f830112156107ce57815191611cd583612930565b92611ce360405194856128f4565b80845260208085019160051b8301019186831161101b57602001905b828210611d86575050506020810151906001600160401b0382116107ca57019280601f850112156107ce578351611d3581612930565b94611d4360405196876128f4565b81865260208087019260051b820101928311610bf457602001905b828210611d6e5750505038611751565b60208091611d7b84612e44565b815201910190611d5e565b60208091611d9384612e67565b815201910190611cff565b855163ffffffff1683526020958601958995508894509092019160010161171b565b60405162461bcd60e51b8152602060048201526002602482015261042560f41b6044820152606490fd5b9050386116b8565b5060405163252c09d760e01b815260048101839052608081602481732c83c54c5612bfd62a78124d4a0ea001278a689c5afa801561147e5763ffffffff918491611e3f575b50905061168e565b611e61915060803d608011611e6a575b611e5981836128f4565b810190612e75565b50505038611e37565b503d611e4f565b9050611e8c915060803d608011611e6a57611e5981836128f4565b9291505038611686565b60405162461bcd60e51b81526020600482015260026024820152614e4960f01b6044820152606490fd5b91505060e0813d60e011611f48575b81611edc60e093836128f4565b810103126107d657611eed81612e44565b5060208101518060020b036107d657611f0860408201612e58565b90611f1560608201612e58565b91611f2260808301612e58565b5060a082015160ff8116036107ce57611f4060c061ffff9301612d12565b509190611620565b3d9150611ecf565b50346102605760a036600319011261026057611f6a61280c565b6024356001600160401b0381116107d657366023820112156107d657806004013591611f9583612930565b91611fa360405193846128f4565b83835260208301906024829560051b82010190368211610bf457602401915b81831061216a57505050611fd46127fb565b92611fdd612882565b91611fe6612e1b565b6001600160a01b03169283156107b3576002815110801561214e575b61213f5761200f84612fda565b156107a457838652600b602052604086209051916001600160401b03831161212b57600160401b831161212b578154838355808410612110575b5090865260208620865b8381106120f357505050506040519261206b846128a8565b6001845261ffff602085019116815263ffffffff60408501921682526060840192604435845285526006602052604085209351600381101561106f578454915162ffffff1990921660ff9091161760089190911b62ffff0016178355600191906120da9063ffffffff906106ef565b519101556000805160206132688339815191528180a180f35b82516001600160a01b031681830155602090920191600101612053565b82885260208820612125918101908501612c21565b38612049565b634e487b7160e01b87526041600452602487fd5b6350b6fed960e01b8652600486fd5b50836001600160a01b0361216183612cf5565b51161415612002565b82356001600160a01b038116810361101b57815260209283019201611fc2565b50346102605760a0366003190112610260576121a461280c565b90602435916001600160401b03831161148957366023840112156114895782600401356121d081612915565b936121de60405195866128f4565b81855236602483830101116107d25781849260246020930183880137850101526122066127fb565b9061220f612882565b90612218612e1b565b6001600160a01b03169182156124215761223183612fda565b156124125760405191612243836128a8565b6002835261ffff602084019216825263ffffffff604084019116815260608301916044358352848652600660205260408620935160038110156123fe578454915162ffffff1990921660ff9091161760089190911b62ffff0016178355600191906122b39063ffffffff906106ef565b5191015580825260096020526040822083516001600160401b0381116123ea576122dd8254612947565b601f81116123af575b50602094601f821160011461234d579484958293949592612342575b50508160011b916000199060031b1c19161790555b8152600860205260408120805460ff191660011790556000805160206132688339815191528180a180f35b015190503880612302565b601f1982169583865280862091865b8881106123975750836001959697981061237e575b505050811b019055612317565b015160001960f88460031b161c19169055388080612371565b9192602060018192868501518155019401920161235c565b6123da9083865260208620601f840160051c810191602085106123e0575b601f0160051c0190612c21565b386122e6565b90915081906123cd565b634e487b7160e01b84526041600452602484fd5b634e487b7160e01b87526021600452602487fd5b63de5db6f760e01b8452600484fd5b63d92e233d60e01b8452600484fd5b5034610260578060031936011261026057606061244b612c38565b9060405192835260208301526040820152f35b50346102605760803660031901126102605761247861280c565b906044359161ffff83168303611489576064359063ffffffff821682036107d6576124a1612e1b565b6001600160a01b03168083526005602052604083205490939015612529578293612514935260066020526124f460408520916024356001840155829062ffff0082549160081b169062ffff001916179055565b9066ffffffff00000082549160181b169066ffffffff0000001916179055565b6000805160206132688339815191528180a180f35b631fcf8c4760e11b8352600483fd5b503461026057806003193601126102605760405180916020600454928381520191600482527f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b915b818110612597576103f0856103dc818703826128f4565b8254845260209093019260019283019201612580565b5034610260576020366003190112610260576125c761280c565b6125cf612e1b565b6001600160a01b03166125e181612ef2565b156126c3578082526006602052816001604082208281550155808252600b602052604082208054838255806126a9575b5050808252600a602052816040812055808252600960205281604081206126388154612947565b80612667575b505052600860205260408120805460ff191690556000805160206132688339815191528180a180f35b601f811160011461267d5750555b81388061263e565b8183526020832061269991601f0160051c810190600101612c21565b8082528160208120915555612675565b6126bc9184526020842090810190612c21565b3880612611565b631fcf8c4760e11b8252600482fd5b50346102605760203660031901126102605760806127176126f96126f461280c565b612ac6565b91604094939451948552602085015260408401526060830190612822565bf35b50346102605760203660031901126102605760043561ffff81168082036107d657612742612e1b565b601e8110908115612787575b506104da576001805461ffff60a01b191660a09290921b61ffff60a01b169190911790556000805160206132688339815191528180a180f35b6101f49150113861274e565b50346102605780600319360112610260576020600354604051908152f35b5034610260578060031936011261026057602061ffff60015460a01c16604051908152f35b90503461148957816003193601126114895760209063ffffffff60015460b01c168152f35b6064359061ffff8216820361008657565b600435906001600160a01b038216820361008657565b90600382101561282f5752565b634e487b7160e01b600052602160045260246000fd5b906020808351928381520192019060005b8181106128635750505090565b82516001600160a01b0316845260209384019390920191600101612856565b6084359063ffffffff8216820361008657565b6004359063ffffffff8216820361008657565b608081019081106001600160401b038211176128c357604052565b634e487b7160e01b600052604160045260246000fd5b604081019081106001600160401b038211176128c357604052565b90601f801991011681019081106001600160401b038211176128c357604052565b6001600160401b0381116128c357601f01601f191660200190565b6001600160401b0381116128c35760051b60200190565b90600182811c92168015612977575b602083101461296157565b634e487b7160e01b600052602260045260246000fd5b91607f1691612956565b906040519182600082549261299584612947565b8084529360018116908115612a0357506001146129bc575b506129ba925003836128f4565b565b90506000929192526020600020906000915b8183106129e75750509060206129ba92820101386129ad565b60209193508060019154838589010152019101909184926129ce565b9050602092506129ba94915060ff191682840152151560051b820101386129ad565b919082519283825260005b848110612a51575050826000602080949584010152601f8019910116010190565b80602080928401015182828601015201612a30565b8054821015612a7e5760005260206000200190600090565b634e487b7160e01b600052603260045260246000fd5b90816020910312610086575190565b91908201809211612ab057565b634e487b7160e01b600052601160045260246000fd5b6001600160a01b03166000818152600660205260409081902090519192612aec836128a8565b815460ff8116600381101561282f5784526001602085019361ffff8360081c16855263ffffffff604087019360181c16835201549060608501918252845191600383101561282f5760009215612529576040516370a0823160e01b8152306004820152906020826024818b5afa918215610e28578492612bd8575b509161ffff612ba2612bab93612710955190818111600014612bd05750925b839a8752600760205263ffffffff604088205491511690612aa3565b96511690612c0e565b049351906003821015612bbc575090565b634e487b7160e01b81526021600452602490fd5b905092612b86565b9091506020813d602011612c06575b81612bf4602093836128f4565b810103126107d257519061ffff612b67565b3d9150612be7565b81810292918115918404141715612ab057565b818110612c2c575050565b60008155600101612c21565b6040516370a0823160e01b815230600482015260208160248173058e7b30200d001130232e8fbfdf900590e0baa95afa90811561007a57600091612cc3575b506002549081811115612cbb5750905b81612710612cb76003549261ffff612cac6001549563ffffffff8760b01c1690612aa3565b9460a01c1690612c0e565b0491565b905090612c87565b906020823d602011612ced575b81612cdd602093836128f4565b8101031261026057505138612c77565b3d9150612cd0565b805115612a7e5760200190565b805160011015612a7e5760400190565b5190811515820361008657565b91908203918211612ab057565b6040516370a0823160e01b815230600482015260009060208160248173aa26754dd0c8310cb70f3b66daeab52c8cff3c305afa908115610b31578291612de9575b508015612dda5773aa26754dd0c8310cb70f3b66daeab52c8cff3c303b156114895760405190630852cd8d60e31b8252600482015281816024818373aa26754dd0c8310cb70f3b66daeab52c8cff3c305af18015610b3157612dcd575050565b81612dd7916128f4565b50565b631e9acf1760e31b8252600482fd5b90506020813d602011612e13575b81612e04602093836128f4565b81010312611489575138612d6d565b3d9150612df7565b6000546001600160a01b03163303612e2f57565b63118cdaa760e01b6000523360045260246000fd5b51906001600160a01b038216820361008657565b519061ffff8216820361008657565b51908160060b820361008657565b919082608091031261008657815163ffffffff811681036100865791612e9d60208201612e67565b91612eb66060612eaf60408501612e44565b9301612d12565b90565b9192608093612ede92979695978452602084015260a0604084015260a0830190612845565b6001600160a01b0390951660608201520152565b6000818152600560205260409020548015612fd3576000198101818111612ab057600454600019810191908211612ab057818103612f82575b5050506004548015612f6c5760001901612f46816004612a66565b8154906000199060031b1b19169055600455600052600560205260006040812055600190565b634e487b7160e01b600052603160045260246000fd5b612fbb612f93612fa4936004612a66565b90549060031b1c9283926004612a66565b819391549060031b91821b91600019901b19161790565b90556000526005602052604060002055388080612f2b565b5050600090565b8060005260056020526040600020541560001461302f57600454600160401b8110156128c357613016612fa48260018594016004556004612a66565b9055600454906000526005602052604060002055600190565b50600090565b81810291600091600019828209928480851094039380850394146130895783600160401b111561307a575090600160401b910990828211900360c01b910360401c1790565b63227bc15360e01b8152600490fd5b925050505060401c90565b6000670de0b6b3a7640000820291600019670de0b6b3a76400008209918380841093039280840393146130f157600160801b83101561307a5750600160801b90670de0b6b3a7640000900990828211900360801b910360801c1790565b50505060801c90565b6000670de0b6b3a7640000820291600019670de0b6b3a764000082099183808410930392808403931461315757600160c01b83101561307a5750600160c01b90670de0b6b3a7640000900990828211900360401b910360c01c1790565b50505060c01c90565b6000806131899260018060a01b03169360208151910182865af16131826131d6565b9083613206565b80519081151591826131b3575b505061319f5750565b635274afe760e01b60005260045260246000fd5b81925090602091810103126100865760206131ce9101612d12565b153880613196565b3d15613201573d906131e782612915565b916131f560405193846128f4565b82523d6000602084013e565b606090565b9061322c575080511561321b57805190602001fd5b630a12f52160e11b60005260046000fd5b8151158061325e575b61323d575090565b639996b31560e01b60009081526001600160a01b0391909116600452602490fd5b50803b1561323556fed31db595e63c8c511251c64d762f85a7be231a06110bdc5194333af53b50d689a264697066735822122069c10a7880c05f443d2df3c41842533ac1c77e1a7125978b7874c068fe306a8864736f6c634300081a0033

Verified Source Code Full 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);
    }
}
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";
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);
}
IERC20Permit.sol 90 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.20;

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}
EnumerableSet.sol 378 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes32 value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}
IUniswapV2Router01.sol 95 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,
        uint amountADesired,
        uint amountBDesired,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB, uint liquidity);
    function addLiquidityETH(
        address token,
        uint amountTokenDesired,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external payable returns (uint amountToken, uint amountETH, uint liquidity);
    function removeLiquidity(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB);
    function removeLiquidityETH(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountToken, uint amountETH);
    function removeLiquidityWithPermit(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountA, uint amountB);
    function removeLiquidityETHWithPermit(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountToken, uint amountETH);
    function swapExactTokensForTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapTokensForExactTokens(
        uint amountOut,
        uint amountInMax,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);
    function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
        external
        returns (uint[] memory amounts);
    function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        returns (uint[] memory amounts);
    function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);

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

import './IUniswapV2Router01.sol';

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

    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
    function swapExactETHForTokensSupportingFeeOnTransferTokens(
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external payable;
    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
}
IUniswapV3Pool.sol 24 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
{

}
IUniswapV3SwapCallback.sol 21 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;
}
IUniswapV3PoolActions.sol 103 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 40 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 121 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 23 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);
}
H420BuyBurnV2.sol 350 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.26;

import "@openzeppelin/contracts/interfaces/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable2Step.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "./interfaces/IWETH9.sol";
import "./interfaces/IERC20Burnable.sol";
import "./lib/OracleLibrary.sol";
import "./lib/TickMath.sol";
import "./lib/Constants.sol";

/// @title H420 Buy&Burn V2 Contract
contract H420BuyBurnV2 is Ownable2Step {
    using EnumerableSet for EnumerableSet.AddressSet;
    using SafeERC20 for *;

    enum SwapTypes {
        DISABLED,
        UNI_V2,
        UNI_V3
    }

    struct SwapTokenSettings {
        SwapTypes swapType;
        uint16 incentiveBps;
        uint32 interval;
        uint256 capPerSwap;
    }

    struct SingleSwapOptionsV3 {
        address tokenOut;
        uint24 fee;
    }

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

    /// @notice Basis point incentive fee paid out for calling Buy & Burn.
    uint16 public buyBurnIncentiveFeeBps = 42;
    /// @notice Cooldown for Buy & Burns in seconds.
    uint32 public buyBurnInterval = 6 hours;
    /// @notice Time used for TitanX price calculation.
    uint32 public titanXPriceLookback = 15 minutes;
    /// @notice The maximum amount of E280 that can be swapped per Buy & Burn.
    uint256 public capPerSwapBuyBurn = 2_000_000_000 ether;
    /// @notice Time of the last Buy & Burn in seconds.
    uint256 public lastBuyBurn;

    /// @notice Currently enabled tokens.
    EnumerableSet.AddressSet private _enabledTokens;
    /// @notice Swap settings per token.
    mapping(address => SwapTokenSettings) public swapSettings;
    /// @notice Times of last swap per token.
    mapping(address => uint256) public swapTimes;
    /// @notice Does token utilize multihop swaps.
    mapping(address => bool) public isMultihopSwap;
    /// @notice Hashed path for a token utilizing Uniswap V3 multihop path.
    mapping(address => bytes) public multihopSwapOptionsV3;
    /// @notice Output token info for Uniswap V3 single swap.
    mapping(address => SingleSwapOptionsV3) public swapOptionsV3;
    /// @notice Path of a swap for Uniswap V2 protocol.
    mapping(address => address[]) public swapOptionsV2;

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

    event SettingsUpdate();
    event TokenSwap();
    event BuyBurn();

    // ------------------------------- ERRORS ------------------------------ //

    error Prohibited();
    error ZeroAddress();
    error ZeroInput();
    error Cooldown();
    error InsufficientBalance();
    error IncorrectPathSettings();
    error TokenNotEnabled();
    error DuplicateSwapToken();
    error Unauthorized();

    // ------------------------------ MODIFIERS ---------------------------- //

    modifier onlyWhitelisted() {
        if (!WL_REGISTRY.isWhitelisted(msg.sender)) revert Unauthorized();
        _;
    }

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

    constructor(address _owner) Ownable(_owner) {}

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

    receive() external payable {
        IWETH9(WETH9).deposit{value: msg.value}();
    }

    /// @notice Swaps whitelisted tokens.
    /// @param token Address of a token to swap.
    /// @param minAmountOut Minimum amount of tokens to receive from swap.
    /// @param deadline Deadline timestamp to perform the swap.
    function swapToken(address token, uint256 minAmountOut, uint256 deadline) external onlyWhitelisted {
        (uint256 amount, uint256 incentive, uint256 nextAvailable, SwapTypes swapType) = getSwapParams(token);
        if (block.timestamp < nextAvailable) revert Cooldown();
        if (amount == 0) revert InsufficientBalance();

        swapTimes[token] = block.timestamp;
        if (swapType == SwapTypes.UNI_V2) {
            _handleV2Swap(token, amount - incentive, minAmountOut, deadline);
        } else if (swapType == SwapTypes.UNI_V3) {
            _handleV3Swap(token, amount - incentive, minAmountOut, deadline);
        } else revert Prohibited();

        IERC20(token).safeTransfer(msg.sender, incentive);
        emit TokenSwap();
    }

    /// @notice Buys and burns H420 tokens using E280 balance.
    /// @param minAmountOut The minimum amount out for E280 -> H420 swap.
    /// @param deadline The deadline for the swaps.
    function buyAndBurn(uint256 minAmountOut, uint256 deadline) external onlyWhitelisted {
        (uint256 amount, uint256 incentive, uint256 nextAvailable) = getBuyBurnParams();
        if (block.timestamp < nextAvailable) revert Cooldown();
        if (amount == 0) revert InsufficientBalance();
        
        lastBuyBurn = block.timestamp;
        _swapE280ToH420(amount - incentive, minAmountOut, deadline);
        burnH420Tokens();

        IERC20(E280).safeTransfer(msg.sender, incentive);
        emit BuyBurn();
    }

    /// @notice Burns all H420 tokens available in the contract.
    function burnH420Tokens() public {
        IERC20Burnable h420 = IERC20Burnable(H420);
        uint256 totalBalance = h420.balanceOf(address(this));
        if (totalBalance == 0) revert InsufficientBalance();
        h420.burn(totalBalance);
    }

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

    /// @notice Sets the incentive fee basis points (bps) for Buy & Burn calls.
    /// @param bps The incentive fee in basis points (30 - 500), (100 bps = 1%).
    function setBuyBurnIncentiveFee(uint16 bps) external onlyOwner {
        if (bps < 30 || bps > 500) revert Prohibited();
        buyBurnIncentiveFeeBps = bps;
        emit SettingsUpdate();
    }

    /// @notice Sets the Buy & Burn interval.
    /// @param limit The new interval in seconds.
    function setBuyBurnInterval(uint32 limit) external onlyOwner {
        if (limit == 0) revert Prohibited();
        buyBurnInterval = limit;
        emit SettingsUpdate();
    }

    /// @notice Sets the cap per swap for E280 -> H420 swaps during Buy & Burn calls.
    /// @param limit The new cap limit in WEI applied to E280 balance.
    function setCapPerSwapBuyBurn(uint256 limit) external onlyOwner {
        capPerSwapBuyBurn = limit;
        emit SettingsUpdate();
    }

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

    /// @notice Adds a swap token that requires a Uniswap V2 swap.
    /// @param token Address of the token to be enabled.
    /// @param path Array of addresses from input token to output token. (Supports Multihop)
    /// @param capPerSwap Maximum amount of tokens to be swapped in a single call.
    /// @param incentiveBps Basis points to be paid out as incentive to the caller (1% = 100 bps).
    /// @param interval Cooldown time in seconds.
    function addUniswapV2Token(address token, address[] memory path, uint256 capPerSwap, uint16 incentiveBps, uint32 interval) external onlyOwner {
        if (token == address(0)) revert ZeroAddress();
        if (path.length < 2 || path[0] != token) revert IncorrectPathSettings();
        if (!_enabledTokens.add(token)) revert DuplicateSwapToken();
        swapOptionsV2[token] = path;
        swapSettings[token] = SwapTokenSettings(SwapTypes.UNI_V2, incentiveBps, interval, capPerSwap);
        emit SettingsUpdate();
    }

    /// @notice Adds a swap token that requires a Uniswap V3 Single swap.
    /// @param token Address of the token to be enabled.
    /// @param tokenOut Address of the output token.
    /// @param poolFee Fee of the V3 pool between input and output tokens.
    /// @param capPerSwap Maximum amount of tokens to be distributed in a single call.
    /// @param incentiveBps Basis points to be paid out as incentive to the caller (1% = 100 bps).
    /// @param interval Cooldown time in seconds.
    function addUniswapV3Token(address token, address tokenOut, uint24 poolFee, uint256 capPerSwap, uint16 incentiveBps, uint32 interval) external onlyOwner {
        if (token == address(0) || tokenOut == address(0)) revert ZeroAddress();
        if (!_enabledTokens.add(token)) revert DuplicateSwapToken();
        swapSettings[token] = SwapTokenSettings(SwapTypes.UNI_V3, incentiveBps, interval, capPerSwap);
        swapOptionsV3[token] = SingleSwapOptionsV3(tokenOut, poolFee);
        isMultihopSwap[token] = false;
        emit SettingsUpdate();
    }

    /// @notice Adds a swap token that requires a Uniswap V3 Multihop swap.
    /// @param token Address of the token to be enabled.
    /// @param path Hashed path for the swap.
    /// @param capPerSwap Maximum amount of tokens to be distributed in a single call.
    /// @param incentiveBps Basis points to be paid out as incentive to the caller (1% = 100 bps).
    /// @param interval Cooldown time in seconds.
    function addUniswapV3MultihopToken(address token, bytes memory path, uint256 capPerSwap, uint16 incentiveBps, uint32 interval) external onlyOwner {
        if (token == address(0)) revert ZeroAddress();
        if (!_enabledTokens.add(token)) revert DuplicateSwapToken();
        swapSettings[token] = SwapTokenSettings(SwapTypes.UNI_V3, incentiveBps, interval, capPerSwap);
        multihopSwapOptionsV3[token] = path;
        isMultihopSwap[token] = true;
        emit SettingsUpdate();
    }

    /// @notice Removes a swap token from whitelisted tokens.
    /// @param token Address of the token to edit.
    /// @param capPerSwap Maximum amount of tokens to be distributed in a single call.
    /// @param incentiveBps Basis points to be paid out as incentive to the caller (1% = 100 bps).
    /// @param interval Cooldown time in seconds.
    function editTokenSettings(address token, uint256 capPerSwap, uint16 incentiveBps, uint32 interval) external onlyOwner {
        if (!_enabledTokens.contains(token)) revert TokenNotEnabled();
        SwapTokenSettings storage settings = swapSettings[token];
        settings.capPerSwap = capPerSwap;
        settings.incentiveBps = incentiveBps;
        settings.interval = interval;
        emit SettingsUpdate();
    }

    /// @notice Removes a swap token from whitelisted tokens.
    /// @param token Address of the token to be disabled.
    function disableToken(address token) external onlyOwner {
        if (!_enabledTokens.remove(token)) revert TokenNotEnabled();
        delete swapSettings[token];
        delete swapOptionsV2[token];
        delete swapOptionsV3[token];
        delete multihopSwapOptionsV3[token];
        delete isMultihopSwap[token];
        emit SettingsUpdate();
    }

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

    /// @notice Returns parameters for the next token swap.
    /// @param token Address of the token to be used in a swap.
    /// @return amount Total token amount used in the next swap.
    /// @return incentive Token amount paid out as incentive to the caller.
    /// @return nextAvailable Timestamp in seconds when next swap will be available.
    /// @return swapType Type of the swap to be performed.
    function getSwapParams(address token) public view returns (uint256 amount, uint256 incentive, uint256 nextAvailable, SwapTypes swapType) {
        SwapTokenSettings memory settings = swapSettings[token];
        if (settings.swapType == SwapTypes.DISABLED) revert TokenNotEnabled();
        uint256 balance = IERC20(token).balanceOf(address(this));
        amount = balance > settings.capPerSwap ? settings.capPerSwap : balance;
        nextAvailable = swapTimes[token] + settings.interval;
        incentive = _applyBps(amount, settings.incentiveBps);
        swapType = settings.swapType;
    }

    /// @notice Returns parameters for the next Buy & Burn.
    /// @return amount Total E280 amount used in the next Buy & Burn.
    /// @return incentive E280 amount paid out as incentive to the caller.
    /// @return nextAvailable Timestamp in seconds when next Buy & Burn will be available.
    function getBuyBurnParams() public view returns (uint256 amount, uint256 incentive, uint256 nextAvailable) {
        uint256 balance = IERC20(E280).balanceOf(address(this));
        amount = balance > capPerSwapBuyBurn ? capPerSwapBuyBurn : balance;
        nextAvailable = lastBuyBurn + buyBurnInterval;
        incentive = _applyBps(amount, buyBurnIncentiveFeeBps);
    }

    /// @notice Returns a list of all enabled swap tokens.
    function getEnabledTokens() external view returns (address[] memory) {
        return _enabledTokens.values();
    }

    /// @notice Returns a full Uniswap path for a V2 swap token.
    function getUniswapV2Path(address token) external view returns (address[] memory) {
        return swapOptionsV2[token];
    }

    /// @notice Returns current TitanX price in HLX/TITANX pool.
    function getCurrentTitanPrice() public view returns (uint256) {
        uint32 _secondsAgo = titanXPriceLookback;
        uint32 oldestObservation = OracleLibrary.getOldestObservationSecondsAgo(TITANX_HLX_POOL);
        if (oldestObservation < _secondsAgo) _secondsAgo = oldestObservation;

        (int24 arithmeticMeanTick,) = OracleLibrary.consult(TITANX_HLX_POOL, _secondsAgo);
        uint160 sqrtPriceX96 = TickMath.getSqrtRatioAtTick(arithmeticMeanTick);
        return OracleLibrary.getQuoteForSqrtRatioX96(sqrtPriceX96, 1 ether, HLX, TITANX);
    }

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

    function _applyBps(uint256 amount, uint16 incentiveBps) internal pure returns (uint256) {
        return (amount * incentiveBps) / BPS_BASE;
    }

    function _swapE280ToH420(uint256 amountIn, uint256 minAmountOut, uint256 deadline) internal {
        IERC20(E280).safeIncreaseAllowance(UNISWAP_V2_ROUTER, amountIn);
        address[] memory path = new address[](2);
        path[0] = E280;
        path[1] = H420;
        IUniswapV2Router02(UNISWAP_V2_ROUTER).swapExactTokensForTokensSupportingFeeOnTransferTokens(
            amountIn, minAmountOut, path, address(this), deadline
        );
    }

    function _handleV2Swap(address token, uint256 amountIn, uint256 minAmountOut, uint256 deadline) internal {
        IERC20(token).safeIncreaseAllowance(UNISWAP_V2_ROUTER, amountIn);
        address[] memory path = swapOptionsV2[token];
        IUniswapV2Router02(UNISWAP_V2_ROUTER).swapExactTokensForTokensSupportingFeeOnTransferTokens(
            amountIn, minAmountOut, path, address(this), deadline
        );
    }

    function _handleV3Swap(address token, uint256 amountIn, uint256 minAmountOut, uint256 deadline) internal {
        IERC20(token).safeIncreaseAllowance(UNISWAP_V3_ROUTER, amountIn);
        if (isMultihopSwap[token]) {
            ISwapRouter.ExactInputParams memory params = ISwapRouter.ExactInputParams({
                path: multihopSwapOptionsV3[token],
                recipient: address(this),
                deadline: deadline,
                amountIn: amountIn,
                amountOutMinimum: minAmountOut
            });
            ISwapRouter(UNISWAP_V3_ROUTER).exactInput(params);
        } else {
            SingleSwapOptionsV3 memory options = swapOptionsV3[token];
            ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({
                tokenIn: token,
                tokenOut: options.tokenOut,
                fee: options.fee,
                recipient: address(this),
                deadline: deadline,
                amountIn: amountIn,
                amountOutMinimum: minAmountOut,
                sqrtPriceLimitX96: 0
            });
            ISwapRouter(UNISWAP_V3_ROUTER).exactInputSingle(params);
        }
    }
}
IERC20Burnable.sol 9 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;

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

interface IERC20Burnable is IERC20 {
    function burn(uint256 value) external;
    function totalBurned() external view returns (uint256);
}
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;
}
IWhitelistRegistry.sol 7 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.22;

interface IWhitelistRegistry {
    function isWhitelisted(address account) external view returns (bool);
    function setWhitelisted(address[] calldata accounts, bool _isWhitelisted) external;
}
Constants.sol 20 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.22;

import "../interfaces/IWhitelistRegistry.sol";

// ===================== Contract Addresses ======================
address constant H420 = 0xaa26754dD0C8310cB70F3B66DAeAb52c8cFf3c30;
address constant HLX = 0x2614f29C39dE46468A921Fd0b41fdd99A01f2EDf;
address constant TITANX = 0xF19308F923582A6f7c465e5CE7a9Dc1BEC6665B1;
address constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address constant E280 = 0x058E7b30200d001130232e8fBfDF900590E0bAA9;

address constant TITANX_HLX_POOL = 0x2C83C54C5612BfD62a78124D4A0eA001278a689c;
address constant UNISWAP_V2_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address constant UNISWAP_V3_ROUTER = 0xE592427A0AEce92De3Edee1F18E0157C05861564;

uint24 constant POOL_FEE_1PERCENT = 10000;
uint16 constant BPS_BASE = 100_00;

IWhitelistRegistry constant WL_REGISTRY = IWhitelistRegistry(0x9634E1Cdc25106B892a8cCbA014441E8A1E842a1);
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;
        }
    }
}

Read Contract

buyBurnIncentiveFeeBps 0x0c3ecffe → uint16
buyBurnInterval 0x0004dce3 → uint32
capPerSwapBuyBurn 0x9e7029b5 → uint256
getBuyBurnParams 0x5283837e → uint256, uint256, uint256
getCurrentTitanPrice 0x665f8efb → uint256
getEnabledTokens 0x37099065 → address[]
getSwapParams 0x1b04b77d → uint256, uint256, uint256, uint8
getUniswapV2Path 0xd32d4599 → address[]
isMultihopSwap 0x786226d3 → bool
lastBuyBurn 0x120ec086 → uint256
multihopSwapOptionsV3 0xaa2dbae5 → bytes
owner 0x8da5cb5b → address
pendingOwner 0xe30c3978 → address
swapOptionsV2 0xcddd89b8 → address
swapOptionsV3 0xc3c12d59 → address, uint24
swapSettings 0xf2c13242 → uint8, uint16, uint32, uint256
swapTimes 0x6ed7ce53 → uint256
titanXPriceLookback 0x8540ac55 → uint32

Write Contract 15 functions

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

acceptOwnership 0x79ba5097
No parameters
addUniswapV2Token 0x65c228c9
address token
address[] path
uint256 capPerSwap
uint16 incentiveBps
uint32 interval
addUniswapV3MultihopToken 0x5c3983c2
address token
bytes path
uint256 capPerSwap
uint16 incentiveBps
uint32 interval
addUniswapV3Token 0x7c3911c8
address token
address tokenOut
uint24 poolFee
uint256 capPerSwap
uint16 incentiveBps
uint32 interval
burnH420Tokens 0xf46aa059
No parameters
buyAndBurn 0x670cdc4f
uint256 minAmountOut
uint256 deadline
disableToken 0x23e27a64
address token
editTokenSettings 0x4412161a
address token
uint256 capPerSwap
uint16 incentiveBps
uint32 interval
renounceOwnership 0x715018a6
No parameters
setBuyBurnIncentiveFee 0x138a572c
uint16 bps
setBuyBurnInterval 0xc71f815d
uint32 limit
setCapPerSwapBuyBurn 0x68ffd4fb
uint256 limit
setTitanXPriceLookback 0xfab3a793
uint32 time
swapToken 0x72618aac
address token
uint256 minAmountOut
uint256 deadline
transferOwnership 0xf2fde38b
address newOwner

Recent Transactions

No transactions found for this address