ETH Price: $2,806.63 (+1.14%)

Transaction Decoder

Block:
21137921 at Nov-07-2024 07:40:59 PM +UTC
Transaction Fee:
0.09249851165246064 ETH $259.61
Gas Used:
5,129,128 Gas / 18.03396438 Gwei

Emitted Events:

430 UniswapV3Factory.PoolCreated( token0=0xC02aaA39...83C756Cc2, token1=Kerosine, fee=3000, tickSpacing=60, pool=UniswapV3Pool )
431 UniswapV3Pool.Initialize( sqrtPriceX96=17649478601533540191099463262623, tick=108128 )
432 Kerosine.Transfer( from=[Receiver] GnosisSafeProxy, to=UniswapV3Pool, amount=779999999999999999999890 )
433 UniswapV3Pool.Mint( sender=NonfungiblePositionManager, owner=NonfungiblePositionManager, tickLower=92100, tickUpper=108120, amount=6356000161339114119336, amount0=0, amount1=779999999999999999999890 )
434 NonfungiblePositionManager.Transfer( from=0x00000000...000000000, to=[Receiver] GnosisSafeProxy, tokenId=852551 )
435 NonfungiblePositionManager.IncreaseLiquidity( tokenId=852551, liquidity=6356000161339114119336, amount0=0, amount1=779999999999999999999890 )
436 GnosisSafeProxy.0x442e715f626346e8c54381002da614f62bee8d27386535b2521ec8540898556e( 0x442e715f626346e8c54381002da614f62bee8d27386535b2521ec8540898556e, 0fad32dc7a63ba874e8ecc0409e2d09d89a65f72797a17030b751ecdf0c36f10, 0000000000000000000000000000000000000000000000000000000000000000 )

Account State Difference:

  Address   Before After State Difference Code
0x1F98431c...6ea31F984
(Uniswap V3: Factory)
0x86362a4C...d318aa5E9
0.628580008057704652 Eth
Nonce: 2448
0.536081496405244012 Eth
Nonce: 2449
0.09249851165246064
0x905f81B3...6aFA8f9A0
(Uniswap V3: KEROSENE 2)
0 Eth
Nonce: 0
0 Eth
Nonce: 1
From: 0 To: 6692769878913858360560467823136102592012463784489264575165570280760558589126574461378858350568451319647664459410923079077208564598397738178767494828922655422985869175102859725537196242972414784706438735329959665227091212277765693404041971087893612236043347323240060478964483956693911474821384058392838194122726790651962717286942512088523889466401580032392404789536524550795353180365095195946593505509549267656483324692053427713814726065385590418307094139581460834648951477897564190771549770751450950857043043975214731275817219849561974320314961921266148987538497027340032536796633437552119511710836141398918885658149281095633642957399063327457725457040322184611500822749186563244937423985982732164535998148403077636737868247390839700662423723320223630648745886782228512826821156264249531282164650917950956242201307776996033989278981277468170373814974921444211953647000082086564597589311687267144141511610718414935843293853161491853181548233349219125986947626496599257930389934859901158433353888133101131189818946391132614738787699199197976609563801135793612477045400427238611629900626292300440789185195550993177696414149787731293094130351751823152165519763851634562513246594410654112766781899566555613085551830352624688229030153203409000655945973681299572924878758423456723817199123096022724170900454415146571650803159092520072467234381270152820522803421530271383390910252389487362886724650111789493611238291911981801020017855095957541092795791558908932283088571803690419222561175088092725277584506516854812438742381115447619881426046569873556305470198502343594522767805643940663294198245797271942010256224062309339018821833383735863402475244469012284566335519895007700141807803476556053766195261412847278290444298790892503177633568153722085579659594384955662841172728749229385503385278425932488297732018192263633140132378823267058375474766638989605796051098466360039862833827754430424198487427941601279925207491456721301383487920561858998495091568795923030602400599791929938000009706801981118091297454089378879689593937331213634673787113662750009913642433950968177624636013606336759678093546004438098854378856508790537221501485003021411980408364950523037747885801821182414014271540801510224310772465253285834204088800867361830912162115831618622288576373042395738042548620340930964669730257237179772884777946980829312459808129327872835860158168902501515030954924938400912668902907653968262405360054662762311384330569784561861320858525101223801788556391429373077238105293426870622255088037150028916597569602828497758401322678223988625411904832883132608881012933505110797906042793188291230134211922271478911076662352159920866476398317254189037531358304890193924571938427939050097405507300997148603142416701923678553490479322434483830694631844668880625306702597320422131073854014631184712227354625136108545204540133878014667850959950104246928118713377276193082758425545509735815597437121523258499463982626287139213447859582749507327951444730596196666711632307506388935820104080419991029515906472299419802206570875029288883512324542393448898865120499458006982734447995311270006919448532678941348564542472207640209934666108401832649835432424162339447108827632112769848629365577099638003600845210881094496699368521787762813020162680590882019060130175589350259374008088265944161309444712932339730114965680503769453337540913144874918225255456240177825218517238118896050100283416311191296187146249843379660697990799628078954160414744499344639637552058222635184855218626161856301714031829076776557459967916835527368814244734603821502464511530202655730573752117041938361099623994948969096524981636734988341059327122206654264543154267210909389728809438365081247282861373202021397370421840765168111220206303063581034258592897403142338565477840642393704127224716882227207622915178420925443630882347779079082672397219361099187795756734963068573460326891075839526487418136554984387639799977635879610913812418205299841088975222464369512193252721744257357762806394989641035468933932235183149627604181069361362118695653994605385626077737792494551347887918034791978634862446683122767532343566424673435829898928922984906885395418974207108940723160310194820658893375420557758896628527937801264586929398804928068169656944298256071127231803138614094573623181793156538974162364998124298884039136830614959844093391241767199381732892221114953379006455393578180978391635328325518025078574224598240376056703375073766290125537667919828579863169625857964814168683833808835602385299678826235499663660494718261785824483426453093714884945082354332596299192396748499645939284800177828543844534953744632239730635684891890984359935172968972685187900954923218632899248057645880038505882486031330853618147964820354182658165648163543089313026140586414480304279341825927995019227862437653058661267021112933229464600364754856734132169299226380768358364840421709073833297074186975706702354988873557551440718570177897635799043067971111357999630908404093125649531658169869109013098903242517013144682711728489058613477906402830537554996154328330289836414168351290253879080033412965473976306304598424611939845068459075048690182820840574692132707083488980617313300042947052349562671582261127462412249051519183578713237923741985544095261085631068819606329271394452016417920520291909342822799809949239185611982718739363836076184058664227507245745901853029675108028554845659384919617482248136987020998240802122550492990167248595303672091755775987253090680300790515394739945697315919694600077949722340737647978334948251305211065725334473752896474624283960731504007773757847111932196198502575059155467184208980334432083428765419923024133591538610551903091572981443158637229086216106915243692025421549881384708834108348499492325139872051672404771622765093813072632116411007296745604831821144478272943258914447294548397014851045837256948200315726184282005249185730002862427568871557462916355644332753338933166714213331248362996966561156052096482631779791693210737738741647462973270054532495808959380661953274091127929090759095498797384276881451118248029364171768000690364334559482607709059391684020737080033308940212046526282155762536260355431055241019858098361164095726641178657567957313036461063481803849152926055822993083526658673025258341449581553885606612952265586716378032469220268679255306176319721554158400560353389574045999865197357104595913764577813517755740181452496199105138528705907190544608545391238359973937284586302726665745246155061478281416697024628058220719553371143928629776372498925853052859153324311260295097460129149494460405665857515605480852417564013528063963333339520501492946243589530017156477320459320793638961478971219258239308373075344053778112640726000621456817918543753219208027508803913104777601394630778983833110767563169987074055765840653755316343489896642111420627917895908977261501606993124059696210463118705046360573450971178892178405189312958667313573520887447511350872280871462520329415455885343528801489358774834015411563026959025442143813427276523830070736604749241327556623616809292203323611655267947400942844929505490752945788469281241347601947238672068884342284069588935170550999168411866213949685548157225274475810709820539738088587255782186413635355015043095577923360717068158109418434550840323901447487859417989633325890396999168758609191750938645377679172246878626548740891127014311631570657880704697362653826768978423977482342923007825563754726129764767965119519155088717658297355136264273495044584267854840874031482658356309301932938787000058939213393882060290165959308537075944873773072072234742208213409242623444206895486252787160743347831756674493238821447371838704517472496251828881042290498298777372235153493824080545472305394934891649317246760675351141991610279855234622244797098182198496740576754939752308180069656203560088835812467615611593007533955908339291163566751796602917304837874637165342023503578195685622390287283657183998489014871741663021310320692517425608686664920539098144961420752271531384514643252040676907232962962827009598361319697991875056685417104501134748749865828517526323307741724292552816001366746764661051369615670814418691992301234711964550670497945159946976596777897132672274351457955347477092478125755481268669022878169749075896997166255251385410001642264728834639400820486839930748713784424721749813301280889666587758576894002344282235249058342878622003653737992300188681763939818860843983741814926500364113413072710877746502863323300394834559037459221560396753726124129596882365847474140426252285462427178764124900555383935164521611297728712058546492032189182518735576483640835197044351709920558279283978604110295267226763423962453701389657628880826665752571635500683715392044508275921786713266774778496475154438291140667588294719840761637574565825508142285005784095585443400131364145541460200260937303705770826183539594392782189913235389564873861974553163403345379949985934295950231928780341049326213073095488590691252377062381617847470195372887724849678409222002749865417432088426288872869746207240958396948951988993266093566568870837689956396661100856821532500263412134187032874252955195094000516891726479724700547562210287144912645913013224210666593882005171115038389203802824468679860914754648570493711072988850557989534229713542766307881317614162102094432486177621175683411958990907445974211949822648778040947145682451822515620891793225894544416050328243105221830824310956198419600613436137281745467823433887058262369550143175322156155414587303311124370250618315174222313761224373180504506972314800468165404194482951643919025731648362917996631875712795112389377530146548696048389192933853947420319359810186085849398136163721635582005812928656079588841826573187389111563949999863683462697552541528907707035684225103238844418525569486498656101892866664243879033517811933675556085097519873510565773453992745624554799739238714025205699873074022250389120969652809459759625183186683721163968641755215854818012672140232969049203022760008121356637976314281912634235556864387420501538909440461908246388285842824886536429475764459745260071889472430642704155992662790973244957938332474957079668509977062836028833757447273281791832045646453053154211522784286581566051439952650634124141397145198469361938939458236969577352030417188770017082902115034574095693057399927011169042260005211106712332280301135761108372468462180590757610289028104505503399034847147016157195838434598999910359089865724980848644212447486057909013888203766213145306560202205674927450922409382509265038357440755056056738335916182270130005228739753092711827105162314921600876927791233723546047177147936848484946334148465139775294841002895589082944709555201333494094904948783557430461088091345164036566116672064432339562998612354193888264011926525258009635177544008482654224060386365970585185493431954615152858419184617842027716576895623008849735791614135274313385122288137521479789795745638765047934891769213419691883930204465298966978446392111592063215553394374203418896032439545763818729515498100283945828162872234922737040603581648143004581893825364873205730336595368029612093642154382497035697970721422543790362267555034166846305029930890152211447856619241148545682569478872529718978600387249256218583174401609512003673348011359864526345905270289688679832686303197555308635328801996503837762954972509490357287758121054295338412410254534147494370085378908988188729554925261386598444931002299196411641689272856027774907939774922296956079639790739716134846066919346922613840322573251597621089605025695974747021113455723205020513167315859684988571412462486055515539987283216132370561541767521644999480796427804299371075339666081265651436521144515674408915313606660683549925233160017202508958815915547426293603048383450347650755537227637410234633333534225470361191455655173828604494336756241910530073707006948302652167934619042231126460239935566353248776357687697544507386813374502469396135403349375060538332360845947925334759635729381752838372634037048868771574461258682759804588511002075959520188786976558469488758757919403410761903409434757878853007002243643396374301479160949579112294672862676767266375537116933962303935996526700976123261880573182650697487422250313928102498912078879286879713071473440323472565998623320693343673495844618742134954377590183423867266052565649158503791383505836258752222650072404476803916969566077714635246064458197443105867533769195144074918416295392013185104617428747663228855403374477850500789302659300139091710183995450336949954551071985268559281978523981565806896934990041381328044011183100874210643574573230356619697799847786289308651018428525975111697137148843124520076223513208647313375239887199018394122160505666436657917822223415046456487287362422831788581762149752371136044167237681092260097271876655973384733710659036989855714832120136710765771161288941199795951587479971406197521905766933131269883403270868166476621289571928613354261785362340340992084724523158987160082046796831350732785059482097148855462045622100532995932613726128891391859485769839564359426467086318459003942541173337049741381345546468391184769044194692810914387291215882455501296742369890588889869254231188501216198358994578905517234462627464066776707911682624369630640355495483862182229753892014271712237769300885114566523944986097711668454379956704970487964482327361420370891674210027279553373449676878365409121553592881449678447958421984180692922000023011731300171811903301317858904054481799395439768267424910505651834704223509545867338770439906329831116485641102074318448865536186495774925894195916696058589309177532688783483715156911372959483699090310029095826526353438474149464652038109411590546662735251698282231602191666185633945039213286046514164043351826707598175619766640694099039530096145717453091918927264882649975577573986721859789819238816050762341614840768752413274176340394012015895931395091454394641143332562157270188766521078007222856619207828301669879710355960437469633367985960640148195617230269011363314854105731892035725147682815885800199969172361501059979103341711658461796233216782490450221408524630959015704228741147900558108430367234367640251997409005736060715986091330295805334365025426524661806015944892969138533277973220939167150383935537412631539028357286868577407088474800067281477228522272559196964101491983431560500088519300260096673120182435714214394904780652823998648349990642414628946977262379117713290285713961811202248673582530840570911045385070007814406784257336616847743303983342219316671854005833422735481671743585851651532673849565641442386447825878726909070039456823343888437248474760679356587152789082976644948908171767318478882514412234224244684840635663584163234983932029813861389422266845285640698318266674572712008179884823075946539399535841133365155447014160241266662747618943285205716713074468867417251688624306928222972577061784751619872897276952973731411300373215758767004175424013086776721621571304130886708959706624229479979035443798126827329227350825832981469003802177101244526058840588481322812641041704237095961677371953053897549545407715987767217468139507938368492516447791014237350706971739573384679581585230397760167713641301327929449442231155068641442199805474075621443438441177943115000522495088700138229504293697382879836619704962541645804695250535551005502723484375517172024788306200990589550889643179653744831634920460909642126489172204584381789114949935257147490577403530450211418724990160132129616565966863043613131267730355600266387637507162705000430402572483548817155714801957078282253948773497108141996702268885050719588401843899061761959270682492938378167907045045909004339649676805789482824557160535818683092003505349257094164920112531213353750844057475694741241469454279098250657488992539114447616811906401911069449732194314787061320627911251593314074452278785723957807721063144454435909058049547147485706931140434706434394267429107457439662666936929810451994459831588991601075303887882804359646714177927859419191580941003963851619480858724702819518575673505333881976808629701861630164834285420740380402236729781721964950050864968107564274080458251355262970951431967012983782287457523098177198987460854847186172265784247598984672747151347441049546210004636745761182053054070233594287293056989916750928486994001090692084649775006056903712644137143868077838754358190000443911654979377627696667285282180990968837541865546416946541719380247859330791086392653798004256635953795457918700428927901255385156117720512988507860672541054663728348154583971956907675837051352987379894776535513909474349599109573287707922161302648015604521558524079316771123472906982850670656720768233786936129560628355795113352418699689344923122115724059803651244860175652790298573192006249200061006034048543230955538717363605972106250435418247056713804470129773356687413006368131100277551000340799947128906874511461666091188687795112415425205910244414017401965411193540008434747631929506933981429378535887918719145926569402694434957290693320384714991608916461767888106426260430163505885693862779614308481499280514675877414820906423132360114440304083794679850024726599340774921905055005081200198144544565593560277246972986973320565851832371374389432455818021948044779324821991318738805244373581341133506878035984996173985175685240932299355705565105753508146821047474042976838606077321091162014148578616515743425504527825783197232253109175386214237493346801483030895577814081170722784508963919662993364384093399170855624303287700774783165339827413065100229559359226097306537502461833137911894809658102710154851229640668894733250918028398915955337449559057566567760073876346070749475443747039096774573700223495239547752073030196657497864029732137264632427334186537414334164724917742607068922093059256036165272942851638319347883452745211691949181748193726879027900861503980275053048405802273145556340904895510415887762860852172069609882260856347186935759800483667842393174182078416199609369013497571189966190694730805817219377830456105331672327988227677485850798879694505894232085477078853806208596715403223967550719867651621358041946540747854438351973452689905685901353486476543750725046714691508191873715351126869988866905068673033152388794211257242309225569471781979454654723492504514400153515116169449339284041481204684971355563429002055474498456876129154081794270649190953583996788413839984284574719074629131107622492008660810852413813600493262313993467741604659467804673029920334863298701297964477845349415195990775912841936774773562012602709109933038813535618579694361403588106949962473465619817639279575613402114566804277820163154452712773632625824490997409808467662535132097158028967619466800122195273699226803839405324640418957826506935919306745369517658512151975565581743494036746013152172022370062156778943671512027689469417351152776509849053718586757697974363797744587204271642284152045357966108096299709226836436225320410354653558073284343065691509360010227291920367649981629566300970299557708439845259426262280974034181075969262363452187613003517939404289302190067330494403400329211731747463624870923013964911929371720744074872553439351168935502984010819223202116333540439256547171320179090678925352807128715314200287781126245859738951357854256101185483055686967159431125527287494533659064573671381523440059604173968085188759265626980470279578677473177296646541522558098940837541547296690166585629610374611534700072580994989514533526062025261091894824354572775864107713860190729766558702453686665919909887417709486675566740977142713818911296065267437770340739666534380361175234965360162922090662220554900995085611790874029372562444717653285509943575726536260510092218740523806866303885911504300701998824858185404824680796407597560824094058012692489216285039116357721206538635747720610037522970321786028044534714743362160220486636266098605490606640343648690696604599821072724395101028931661722607294057225679450052595991743290649057540454433922017593459034887277824282422555882791110139246662989249723412748450842498427410472252458119307352891798768230941086543919892178743661600976703490598824110259593953617655524761843952559511573291898755884323715063954610751228090078197979783886082528824383506339219271896088901485606974519231815479171257015682861146514543036470872646782194115367194652130495628024830768008956245514465973905172213731034721679481947977993334474863415753071526937010296869319746417154942881555168292136728639745884153030637667337179652084438590354494806602711499002437653044969707951592796556080476370098153935863991452267988880241900356664116338278130219554899778454992509490423657400379331379145897659455210427952137428660427285188032768864640281596051168491972125600821222826035865579868058745103497383862845277826954106775734274106233108472339181622416878926398148812598288252571214635236256365467619785387324793438026266051060679884327010702810239429419173107035646338834672901743146679039251557752324013478264366942730198364623697959248077069994559067478158502747429394083099610798015939939279905017956359825983456065949998739539626128483942174253054007639122689732477700609909035378281886568149185179320872996992146225812528407615611812543011689490108788573254473291868026995674807821252957629488193117174169990027910079478017394542730642575774365570358594039991903147934070315794790782676863589234762660197671654338872002298689209572358476085612241408144683902973118894847520422280765974582827438560744602197371601531415159880121091125351416680270542115321820758136763374256697909362353144130720977143460831372879827278163937855317117940076959696468891626279851696277414623138961577837673510571743090146009181921155324497669868719022313690585358428270086853880859870960063294669613024393176005186901770164174504802306334898321396519554341805098682135875428372107066010355130736611745298263433580697682357878205717324859263321218736803969778428932242538626960534168534813037448774645791597148508686877732090001783003221062212042485979994539558210381240764705336975190933362020186572565627569752217085342291817124129390257192682230917484887069937598451160543458488139347180378568735657573810059577106106951566250611221908049800749321016422468876861090660906009500049783473699305759436927341763190824902046135054427429686101864129716535291567983066500447587579789890262891436580120638197126253846525667634166699372519659923831128957557064489866935762027043649080546838106773452047694205831329406119988924105898522134595933181330309388657803655060032916067419841112594363275551696054118911187918314263726972838815086494480640190492418595808513695188834754660387467231665406192704395080962526140128891258702426152898446682151348503274962308567459329662090416995470557521612534098919835737335515648232010515947752989140103766432236556224848943309480831483959062850752538521559306037093547600614051854215248344314947139259514594266477236598513293975419698566623170531287418700441729386557744377991527858482927230979253828276183923907351545867815533572107532832650632355662018055697086617545624768428616338930742955854727376216218784545950835826727483130177958855444187623017627867642780301895446872344976368476488889231254829590823881732106262372047809352080206258601402834474883535599452573993736697271806066712869817614842050069330010433107908550806526823393811148149584397699707856559715960032098254594635523758498579694484397304355731670889804916566716577971682434744163263814048650795980829399060388087853116656471826342418228544814112989330644955172731778047503589938683783485608261703053358918814709344372328271577724549110830833855534915174667210581958515088093963829901821694038071240526954642202812704034922376943578144545227351944807635272916189933240092127734796772194535903437625316048694031320304526088066266206932045102330090623774657880102828274317601357398451612556566895519201860126566453624230466867135143603846009472640090427480434031835017807867174637160858938744635230647469890677420533955115805599671878264711174071150228495302118872168914676323778954492721683144434456540321851006906964373956022017483675740883584516763580448696207708917119710933587186739268123253085607109167478108114217065055111572433385741773935535877575244655689732325521654097922625618603473523914887013659515681343978810721835020816890102858480621516056681456460400754614037543101270874148582302928516671200427026990938148510120029257048423569452507632315017930153622375244463809281343099004987288474666878014794336720695855807015699930270489807233026668014219177533511976907424809611540634541530342681696958168676406011669038749247102119413422373991017892430736922497008621609702403770291614048608829770245717204570861156912646368515082828128667427226595933349189548767190531234647230137764977874246069161918896789969508218141049576123083201281686401736926879343128650473102080682411429290942687916391678637964104282338670052911856761252749435122616487721643971333197216789207928817824019157232579491904280878839871073521999541053187483861229634979693775053792739835075495990303914785026545467252347075841198756100537884535704912331583594896411201982217018801287087205558805053361643554962910379614755477076714721137418340212578705795719253110782552803927786867658942138305134385682784010342018999054269514955484572005316972812627707005982365136567457835569340622340426725519720725325385811307958180944148650294917305920809042826637835471884760250545092056059533610024446206438250173727536061079804800772207816151650688074740266102680620986385213529502625004767083977574013760927108714767815105520537913094609625539949334484958859801814746495894712756004507917904292020549405604907352729833011328628100830924177823861369807919409999266143430466972343447845907661330496603621068338253478223878440226337409819664825985777080247975646999151043359877273533193012036582855561267443910272928774519286087836902594753440157940476747856962594367436626203904821541693171667690595876761295460837704857645007285162159379105051028889790370550087306076282689770615476405459415709235156142603977296583740373126980660580125449153043027171932273694993463609015668036107117571508983008226744175638913033207077166670150801924100861006658313703192491423261441146833702784814244271126660400471253761658906490800243717515597399951476511185937686528293359519338502361542548641652595683389944799326925571544087442278000536671679031760591146847045985054039665812533998029887620279384989452913620203038993497107594685264829238811169681800486855912853337309007607336755006439255498395616054497536228720261060328456083329974224678470712576400489723364534771052472035149464799535330296761004810966014199559488632633642731573264900969955823346005230886156691313112843213042162190243950355455282084443954384475163143576580517987200302013791071563414668023854925728415020372193045868602514160419555564793882767134825870436206456056765261701644037134867535582182200131073914115787569711657000009337313872854690685344504886549237148679275314634173026789960173165270898253760792691054759535850329747651650907988484012056302545362076441709220030474588404239497775442988048956136442401094758458656855997153081464227051763933695074092782914491207417339410133925856250035669040750815170323002419097787903139378372814094196282723705677793392088953010772677240332058234390657867333647647315272250287422976780524401583964271177641253986003390772467898777038297319536622217867928928390758538361591864545992329849358590538721578868035049583416832183676727347911476746754066433209474701442078510936087284699870355681204542488687364958404472880339194639580020418137455853176053102489056839705419165123239656729425762407588060745812526438261141548477815669637402088190927841013477230328587299687109989275646888304177816594299078884273018301720835844558662498891652311484984085854225071207257227758130412650851182231925137958038461979769271897133467382222934099655167871873341320251812049942512830070559308433952889125858982466411392640988411709772561336342137366849397852856376408601426960888476489726737696031515077395287629040146578868561715732192017455963987076524246955993269568583913220286193911680899151196554993336516795363628320170017177912805095092590511846587419873939462883480924261269762998084358949248874125113144268251975911480108805197722510835988107638990779317054272255915106401473392662578519765018802237081610784826958813424479550658651763588644076365568318128226807418290802814522099967861562554357134010327060017756073059535860614395537690426472943771704303983002622208997199192690006524333201584379975746204726269979857141561673439803581706306009458932303904546984432114507740040022337128694743569474564211100549190165117635440260502217360440256310273290451490577722628837642635033551471166643183027970646989837237342066326187389927765282223789438930932050101789525227790833859416071852236457863462236382711594302806505298465441177569056431019351219995635762286219006039347841287192004406151121378921755240869569943354506533299200747181655942589402302191021507210403765147672446693580821926773479358911849408936433804334596892573943423230524082924202985151181544604747107966005037768880612780099586034457755358286367656052847756184943571600757657413563411503397231654002085263237515155172411618058075941566969227061427217929226356468568357485331714864320027470756583944003509754079173282434586336505135718102327309221669371911208382448974395273264671405944072220146086677314374617187012514411976840106388131914172455883622569072326868340365102448512716090105879161062814068348385450188404545328212510143039455639853901271694202973325801151161336615486329692431653210153107310767381793338067525454744592453859633456369130037817872784548364031518845036629002937655474673353538382325449059738679616755807446763898449610186566683014876737749103704910382513856107874828425024736779182934266562568544383434071731637440075648741593011782076578360856536773358322252905348061754105251349289710916862844713580881200435670305648238860625943682874558432193727595983756311559644599887631412200366710125541054946439564664266268336264378452688896367122323477935180388917350257966081807846726701642120553578699415417951273836552956634972578069953851485051955769466948823416891698073970624875811770923517707903302914964365584951496775713765977128833652401364370667073833260231619293961593643120177675724000091454310341480663690515628817936104949203307849117515023520618731486495616696876500959011244601901607408156837472866989131412998039262547183830763392829685737521177798594796448831100786895833858553769994413587645695279724955759558136955213741428819868365611739526690487709731214348953251322758216502228184239582338067288754467685264837841493419558013464335150169951303263272271478996742993792318271475327209406763677922998957586532063423937134319240733888659237537021383118474879892888822569945813875647763484901893478153154579123589711211282017597435379627831055260514897186766213588336515284203815104037564286850709561029832902810984733353111916254127693704247946466482859827426429288338763440019148899274584996829013836269244821422940277737049136630466847203743395764576405526136950627945030346539504363108650715860864303064865539005566969431683913977157487429954270135331922560254350968485141635979871380835486141914337236744856796278422747039731091656619895321575131030242373637561360203083691273839066015383917836842008150172989610350709187177048244831722544118515488078194320941751081976743008991510501706949397251900971094375686049421773905363465332682314228065537015144498906866588180279015682592139959889067434425036514903133912749451347687293496517612187261000557977516379675460519673245525631936698310481199044443900747856756905659141650157577555103730877977702378760628943399238658711250965972251421916243534249201243214643009909973817825729685556894030129311956595484830811688181418043387310762462604286033330285933941761168174706479917910854648713767139060090898551067358734173960708300557032428463797235893893093415006889998813839868050220031651105813958346272466182737636260761369483803346756159247209477982426656521125657165400379953386508816546421576313466626841528615547744580336619496282772998475302382589972067628220793814058758264654952925640427661472938867881718582120908301791592693013696258582501447646943317507159898542221548738683863081543722026680835779275129386964280732617419375662109048219720654168648165461268182928346916336407603917840571211831800680106444914332040045484898673441923406215619309023466849320336132042262337977553559513120820133966234733137823614827175249007780332701771643957417741313180337152263434112817384611417203665799967543668367090252475617306381962198611256643580962719555119018784997714510706620613026199127946209106361221592632362601635165569303800065168075831463606629156155422589808869604036463279287695590946363024620847534208416230123085698584834334578210253497784217408692156843931033135193173316509579587618144257333604446362423733679219765165759578722899928461646049550958573425692874510178983238241242765478958634711449282075515918281610551884289025189488605728860351544366109253803630020647652341778057393848058870076668508698999411560219214219152251009140750536085697377077047507421908171375105108299686015414888153475265381260475758172921314682186819541280902703412818563912335451527924470320918687362533746596203708142461525829814609858093688117399887688025060649293140749754985865177915208347114152837137412775681229513243428793926026925052702364154559785250629966196495849932872825613604947747697074404709376960628730859590463852461882371993802184616282154762535745735912851649374483571589795430607535735113960728806579149870954558835510760084273275159475616125582286207627516403864409549288099585129008050631879765277676626983926279498167464379612702873201884851890443875298576817652921347589525263794407989885579278255744075503216457211095571544013762928121310700027578781009690352253484117851120988363091898672038004276590426172187837832040805838624241891478892529553544979134115452638645224700095611971424564603305274089494690779396353753623061746072337239921057687964188469070714083972563972855704322733508666668144888347653261821591739422724799172874081821113875670341469106869175604445873959043120831795577539150147269892135827801169645472494323587183537128173923944620242816784875204231114463319639552313159972585827197237150561400177640193677860467793669925500943023938597314992881054799109414543299497126851841338846622803728828287340697696714345790567203665044614505000607719625517136783460972898921054612240132124150858880461387734526842669154869217467746294676388324402031831245785897074736877037855932169927406510036566954292183026372400456471748980804006024099235610935994431171444810635946460223330488533745800977295533604779409664356520443381259331316244471485322356869924828711615690426041472047352736003773597854789838311656713613525861363836604213198885593681767990197045813825351602043267810665230949134946721200557395849000746792503729670885379604091762164360819333976515712911168552535018376935544115031225361741491921839061156425979628884344085449990220987414972598044986842299187382151313701007871329741455174170003635385292909339803909153827751767375866718667704959360889070046657237549696594597799649737170964299300411304613275756411991741939751583456018657959415502761348000211419324366904043781818121897112834112471862702350691360354543027770372536125612247024070450696087404665085668355329644731081101786788827738022624516630975460039035829211749586302308396537141183949150865005178355854913692488810919390439451076830045829397529386561332900460507243959859596768569842229098553197976242145823443344852749780450718089273945655212854713004043652412956765569177769308035243035802153071956431758440876747044713630341083052897999114445837393918097460278637877041993689909045342711500321000513763797429062202426707624236002149622520382749603385500383571401600749400041127520804371690654653430423969293017430566631269101850014595188393407131737334851233637149422547064698138430877841701980442322205066014404801830757756985634151759381042048617860006224873062262248311875831916566922128353086962470910045301562700396835768741344396712744812043975334060293278185345518716840531204728092979168345706919704561363171675454797288461925605009612615712813686959671062539568058062921961768107091256958246395618676880158897605264303224061423146528798890711845626632000510080751071217733927092356770012895963474077569621186998967324989471277634805237024330213444384236031731245634386950303339791994986827113683004546913029900385408197016021699470149718933389024213089189271054565064149635680474629585579091876153290033813036273438392120471099868801229966532399455666471650817374489191559520558298823641059139349308671822295973253300971969614323481969474980408461994681470482919965177185739414150118014012861732427038847912776796620779593417866122874007949796642882604255591266475450772719119297305027532074848979483687227938887827219783028672253213315842886333124470504811926659658616546285384295036213498662727427914083495510784705555898393043350948870081399715184710354072556078820021962954048007290004077059144914119705211558680857941136465556864389207690214924370643363369128391101273934455547182481440069247169536415764736175497496160747517006541035901529687499349258294895283942415552239535939507863358310256694446682993136091593487338778132630065610040124993189310814186198112647877376509045577220684892888622074897380255262052374490273832917214218071616492965184632255072938386869388096824759590889550647164304896445862314296310627710753894276265279750763829747420067783905579121090219912072937555171275677341680476510452479441411174929946352932386656977195010171596478837446908696011126272514491605726172700494668361596035635447020861260242423374929252407427454842460909494918935556699049181501781983513987551769312508566598101656153150004372643091278034590770627181497536569491700021079636957028616771506951822115298088600768615423961351324161868155584431030882934786598979261258180001591020978880083547176295548936837705978681109140952238516102370959584907662402129522332042961052413979710347572058490392981606647759907183973563971799358879208181831961500519548372228870534480910130160900921408280368000201551785635801761635045497835699092842941573698713076798277479246888094644228944594599236301934337191483234835954561034740253871484818378638135770156535943457848447109069850235294688607236788390167158168564155878815654031795409680029856689401089226753648839333162157465843323896862444321972186083172877136568707249994697948046123098588186273718045042779871186139646179736310533576034236598901329921052476279467446113552938588631775684847351063272930800624542869430256992811870230090652712837787604676589065670955241904718054126247084507999745265999505442876928333861906890597308883878142217967943450017537090352035549761040133286911803728654109338210249381399433882436586352825976523914061424122526348409055331050331793857023907157005155792912244676740728748436535874256634368988219020340694070736407400432166518777909317711974341392754810720706930381405101086122097536206357407575804609506501925665310925477509789635869047073173260618613345990532232681114132614294241223374296312146768423236986503744358093940354548217286030681284066186360817862591023025319766205750598087394917599343521073753424359016808506088628984433715463914802791554958040641650364058756489438779751068315492769693536637965937069385016770727623148160456743152131514100053567362098424437869925040645807862691821978699625085743514411244544698543076346762261894198275171551293714472042567695306487422213728796688188764616797484053535200920472045861827928534323754233658588923674994640007822457394129663802490012911232018838450040478881738989434547265333686079575665219513814531123493686880767123269802286592861354643320498537604498357639970303188621681189690256228681171583267185905452199826110817797956934426413022869110094387029192461470082794097982426632442393149344076213253061822108868907473316691730581324004096792331277221825973440184263010830797434274576232142750362903900159440963649316540934749594600577648144339287625828918996070284899271977528803129185508039613714701825610893160617830687142819192126897390174347546565262053578407587805610097762388449419969783518257389181328060430338073758015714304092633488951673934973357136250874356614560125781580953458903224418847435859069603485783080395527561823552993232410984167711122431356148631945294633778954039107117580212040322403782863587048980167477140484977872502495475146818584967536924087963128346617064259327047592238994191148796300262064250689378153584150732944052462121397822400608553362793728345230572524834039775581768762886940631578758935805763095230508166534202854160003414571837436402896407262404854984033769545433509384659422887678296385805940065033700634471349457075031229061798299794068766037951379853847322618749240748630770195327947861515529172298683753852252439990766191440287402686175429300939452339012191104704701329902344394032710077769977014857108032903386533037069322813336379680524817052723852005714472033424234352492690173149281490547923599554485582014400606491643711937552027323939710123106809804939244049761854227514298254973191672242429807723992542514185586217464503380569990897902856589522019066134081312741262780920023270636817819799679435477751917377735096949544865931759718339156580257207005086612382253842673113541780154386914188508408830605520979672619329395343026114364568760807068625231521895438345099866323810347239182238547739684214799760030829484784816400856450654953672850517937069294563006574443528477473800342564613336974465928491753157114092232653906907788364164466361859444089816614752049303876185485645161764180090466373242722425808310375775800571542916370150010443951026498415661945214062008436041717984263242150929483000431542666590273899896833527666460072233050962281228577803579826190615356226729893674023249482071811627395750942047509274836780284775651634740590193902002526147975168703624648379560532969643118714628521936783965556482777472880591621830993224414549241372802341165366094493828738300071995209668137510861861005456937816105169831312756600622666413643455626493987720348232238678495750944433599993142416176650899149689400782677285420005403840939751117822316432137239975989106621200746461083445864635144543186629279032673457654342882637477355354499567170400790075540326273721856726795999060128683253802451132507881517634324962836988632097413302041544186902878688580981333968072721787609800443276541692079191161788632295576768917727830438132848574405762012279909378583573220810477070776948819632991958448867486037207688090368490164106684151650157801104123173437448000917603213376203651496253027575840565019859018628971362652688432603339862213409307941902741776879756331719454731232859184246677107982765969602706149393749648768037157788357093828302088671059739572775178905760601308059844564377159184444987855257032376644229010587702588624601343308108902746957077633830893998110584205913255427478625949609690413825270241439551162707325931349261574422975898558327255493497861579559013289702644675418399385834905854920384210150995523329998984070579312306463126405091333607394930193356014494746742758709900987951925631985685392365977325526945046730427031366888224042831737655982318326194714470209695293172607021564993955153685505051128742987906223127330601095914662095451064027192040021431492164656747158637755534234356759572136560981098213970447795145849031419353587903688298348708676127365665170518178368639708136352636424691433235544530895182910133630452118574814179484194038418314631160093867919492715281706823732283339569961604816623753150596457045912108112887465250809078120466044678183481710780738342446554960945281992281939159421210773847425212379757323023360211151893663025928850044528546763001126662548510287606502257255192744105592011159794635189863929275441324429768497981577303161583929118910518509066565336353985810850385067358000887121564451455694619791787916519261746866295462285081334727694521716314601373841563506645344923483628274978628817111232285571718990829209384360985564712485158872727984130316003929525240580347281553271680633529065614500164230541515806111398924593841459918888814661913682496738062907480547221229178437337375115832489131712203846237191036220431967938129758426670101986314739175824814866571890633685205732958682105281011938614628929092329397788505515331560330555941544712837084475872539291743234540513172100382482317165505936654238682391207800410237077687215847686759506198369118929696756184976819963193797954499960325114236698531038193132534313545881830103191073652876790033822039549746432827833394947743195621662128066049224999479121481247865565925938049354999134806832275028704975075606085493141185968743147817521511308098526640473061807284058030377797845492266902391656855819816997855947538003309442011295559182348890703707162639038140961329948306495431411860696191012204517455402354816298257916866114811357574223344173732210646394355883451730043199897407841375918008227256991030988141001048266213819746754103350986892905814019908749513884763640465428303470946086817460648037454428180174401045766862087470207371258872312154787353467989672332585742429181540016056455840929083034100120616940540304479329643387811033170015366234446138318658437754011873179086807010458351464012808430985411303407108284781792036774666775451408956673185948423808049414847687678709814053505157383534601756520844542044802126937726038931296383553250422212352373525145359489873669042361811876847615132757416754208248993073547522855527516347237714222468612886944977764582305809999533323828505337828380328121457481380569746660848255476726752794880333092279353859025673907855640878547868461542490775601339204832539146934662425358904984423778617472623919270411689118027809655249111852406341397785456181535892538210765889882838527474498389699250300534866399738554283112611079597675419401843725066496553095697204368565842055385873219056066069159088073309983407909068885495511012293572471287749079930801937148046814888504152976926795605011414822691073808621499613724959736138846565344998300562399664625812668419120287356516496115745530900345191513043637482625576907814504695535302397521687410681742903592187874691551351242480720629895683567614646582714859031999505340396449715831043558604375081155748847002441577898059129450162113190163287623583012560986456606725227435264381835810987186486884549046512918305775827482779112496012605893962064408468733682834915419962982886640331007229031805004674495942730280798773616540306716012820273185804451427659842469683366457164529200762446572734500738294793837293721618314673666912397559698834396636441472808339608152874752139565848397440364511209777009104812479956213055653802219950599898228177725016842431088041086103409709082733478866283181965643142177186395586281639182274084087205622449381150022556489826821000612928062250744694610570176400838152713668145369177636984909267674888079702891065532920186013853253044570303249267578214984945457726636014230985444263103150084095500874613800714818654816541180815154735269831111195398003076290389570593537190394581045673747563331290439479461533200031072300095705355823500223662445674353605829223919770172308624443803957047113342390314131171512471987794129188990155109708961774784256831422445879042628203781413751004729394779350746625482772449327046944324631835294428886216289469763925245087993463285918635087645146543279732653217028500199372250335742638266475219833312198388847546208111011983235290378512379623338919706248300352122406142457258512357168042692415311132772084696675032204458859015666122919018463047300779261255474034966179812257843194845698737422593862808577901380152608379950691747000274416937858849992562241942012019627991279252311788049189108608043969987683487424979842304195076058862715850987996634863129433304002544325641195235092360718837413877013873490571098057123467018037535117223891424919045434757160315797011064252079620116531343356145862612395048669066617393869958665760575140277427075463557151331460315936540986202315951579142560556917844371822997493375428964909759390544695611244412236086305348546279946850736730284075637757660625136938085725929876564651988901544292092685850917681436875330396598541967995275447307032302225989359879074307231312324136763183675635314103971354142324591840420829483113614820029072914633893153824832532279296716940376353361683354408151615024920568432318775077336542867975531090974241197924802484501991926626049383925721528958714224281125878890597216684275475675406492575248199901048607239914067450987190729918970288950484807402574986326781368709079779631535058577805016388189763557549150686836584645964989935518629363658149914306192056989778182149847035512604180884627230283680418761224201635554960271162629177177952493029327474173187147272207928132526855812786513441780763224170888826512609115272449468334204878920453443977125432026518791277706108414737631883703026528252263749887679552194453134875511264811235272838282724985492156896429714507557581561550179195223918180736644821651390355725691288299422294603475000357893672887935679552837805386097270761211778068461658881245517534169388003599139211888884477053269179391924090264579980397621133372963575977190836374250195980509976246356415900025294268191042742220395444239437254360083549193592363341640559997489406903191582545180952763878909422967878425486399077535568790519749438349262609763647310436400265919854842703468121734677819694482923120048407281644250768414868732792165557752777515936263384849516592058340895251206449740363644465889780712860750947067267707041837603721518832205875363044272620485237254261511863684791741821686735056321241125616560944643748857940253378974078431143847689508986503667430777020607630153403127877204719198798737425415294576899327234661287024873124581365416982410334836161368508166728776582418586192357687389374004185463057246421393734585546459321200065594210290023523978948474064572469305714967394094200335479207897784117638648457221572853844547542332589257910191780040108683814148811322855610267658996787133736891922427350818251285182550659583831829133212749150332046958273051501822670941092405612823496016037038786566935149350030382232523955558506403333312197666676278199722944216509774160526455528867535027366564024577062896678335942117352157813932790382275351115917044120316911127637256214654352483177162458100531153635096545864802763794927016172175335189510236948700509140019565228149835984902290271017244261183515320422099980581125434886112424791973926942270375061362674042036822767648066897365182157445254124244117667620907454998199677128415973783949569800506821590606976573563835241204441949096241005888551897731536826990156031665848587881706835139044902773609344243820869142368656415415565349330101959590625753032906262546934435742993407100839217613861983464619209007522683001091386972853823376261548391790573424933861687981922224491844353104725356734084213394079795764474997426397756082344061915301518727625153314148333702844140782560437683499089808902272475283533350157826795157890751704272530826299077917851704987627979798715958841080806684023575467737220292346500757561374355574513204444274400749865493799790924439681350325066064586012414094696973898220434055284392661271714673942390579217802818190000036022438312665550725136479799355442433254797750076031822967196075878224688488572906678499079289877281142559617995708760143240893453487131163403144553181220363042410572633186532996727197510230850359011184069882294832360481711395414410072468618989626651579439204407315390265260577050477349803660388451454173611612928482454398111117889937260109199026417842696016092494396082876166452602302900874247518441527659670423247334327385463086638346103357123859909632922070292658827250311524907910334846783365036858706432420360945080429704229907504338143140344435207290591045063228152958477409950496207631249188106265675902396878695074401783143452013409684646477253349799255931608798280010162752491665194777786341703158138350590458859231189597866904836528699177222716490975286206733198789109212328276829921699740920605540103746954837777258965088630797514478377834293410219451145064913330998304282047739881142855461410891264265466709457404598447696206956242992011875991454343243787103923641403496978315653973232867686547482774753458890389234272659397327884901523916730269490069989809473475110100272336485355234071700587159142275430344302996103858296972705617887465687140579591858619839510864789244322813767591759585681173560652542288376103769192373690581076286096266339204384866878971798096696392669890731454825627927464561207910369284834375349505506348819806653381480183030313322483535071301848132200737352518290843887587925709380140122455050926734212054876767868523007990282818470470097100171965424547067579857218646963182210231600433666308965010255953128550081587923631629946289483021392048817009061509563644361397394554356589449605754538635593913412510369167226479352361343748812989715319389699068425313024399275205959085534493116109344949018874836494310209424118765198615494826171746208879949653914777464103648894388293655485302631055886291840783750651797098931597331378461967125907254661275387174663782813628330638846450302111040966601034278092166128830827365304478486784827205581073205972054473668869762834246206511654350150223194293948482764725537828180168159865028585565561714370066960723793510904272076920907022729583217991549240394780560711153484634098473564507147556086413609398515154083952069659635116178756329270086531521726868739567763627739418341848854019118817263210645778884584153815467585453669914328608560155187642499082
(beaverbuild)
12.878836125041135921 Eth12.879092581441135921 Eth0.0002564564
0xC36442b4...7Ab11FE88
0xd0953aC4...32e303532
0xf3768D6e...130BD5394

Execution Trace

GnosisSafeProxy.6a761202( )
  • GnosisSafe.execTransaction( to=0xC36442b4a4522E871399CD717aBDD847Ab11FE88, value=0, data=0xAC9650D80000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000008413EAD562000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC2000000000000000000000000F3768D6E78E65FC64B8F12FFC824452130BD53940000000000000000000000000000000000000000000000000000000000000BB800000000000000000000000000000000000000DEC48A8556F450092D9129E19F00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000016488316456000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC2000000000000000000000000F3768D6E78E65FC64B8F12FFC824452130BD53940000000000000000000000000000000000000000000000000000000000000BB800000000000000000000000000000000000000000000000000000000000167C4000000000000000000000000000000000000000000000000000000000001A658000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000A52BE27D76E24F7FFF92000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000A52BE27D76E24F7FFF92000000000000000000000000D0953AC488190BBD59240E0A59F697E32E30353200000000000000000000000000000000000000000000000000000000672D19B700000000000000000000000000000000000000000000000000000000, operation=0, safeTxGas=0, baseGas=0, gasPrice=0, gasToken=0x0000000000000000000000000000000000000000, refundReceiver=0x0000000000000000000000000000000000000000, signatures=0x3E3B25CA4F65CE3BCA09E49C807E09BBE7B3A5624C53DF67F0A91066C065B03C1E9585DD23AA1D691E6DD412F3E6EF3DBC62B9A7266240897536B7EEA7FC762D1B ) => ( success=True )
    • Null: 0x000...001.0fad32dc( )
    • NonfungiblePositionManager.multicall( data=[E+rVYgAAAAAAAAAAAAAAAMAqqjmyI/6NCg5cTyfq2Qg8dWzCAAAAAAAAAAAAAAAA83aNbnjmX8ZLjxL/yCRFITC9U5QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALuAAAAAAAAAAAAAAAAAAAAAAAAADexIqFVvRQCS2RKeGf, iDFkVgAAAAAAAAAAAAAAAMAqqjmyI/6NCg5cTyfq2Qg8dWzCAAAAAAAAAAAAAAAA83aNbnjmX8ZLjxL/yCRFITC9U5QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALuAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWfEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABplgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAClK+J9duJPf/+SAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAApSvifXbiT3//kgAAAAAAAAAAAAAAANCVOsSIGQu9WSQOCln2l+MuMDUyAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGctGbc=] ) => ( results=[AAAAAAAAAAAAAAAAkF+Bs35nPMif13fRfhrylq+o+aA=, AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANAkcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAViPOLc0r2XgqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKUr4n124k9//5I=] )
      • NonfungiblePositionManager.createAndInitializePoolIfNecessary( token0=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, token1=0xf3768D6e78E65FC64b8F12ffc824452130BD5394, fee=3000, sqrtPriceX96=17649478601533540191099463262623 ) => ( pool=0x905f81B37e673Cc89Fd777d17e1AF296aFA8f9A0 )
        • UniswapV3Factory.getPool( 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, 0xf3768D6e78E65FC64b8F12ffc824452130BD5394, 3000 ) => ( 0x0000000000000000000000000000000000000000 )
        • UniswapV3Factory.createPool( tokenA=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, tokenB=0xf3768D6e78E65FC64b8F12ffc824452130BD5394, fee=3000 ) => ( pool=0x905f81B37e673Cc89Fd777d17e1AF296aFA8f9A0 )
          • UniswapV3Pool.61016060( )
            • UniswapV3Factory.STATICCALL( )
            • UniswapV3Pool.initialize( sqrtPriceX96=17649478601533540191099463262623 )
            • NonfungiblePositionManager.mint( params=[{name:token0, type:address, order:1, indexed:false, value:0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, valueString:0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2}, {name:token1, type:address, order:2, indexed:false, value:0xf3768D6e78E65FC64b8F12ffc824452130BD5394, valueString:0xf3768D6e78E65FC64b8F12ffc824452130BD5394}, {name:fee, type:uint24, order:3, indexed:false, value:3000, valueString:3000}, {name:tickLower, type:int24, order:4, indexed:false, value:92100, valueString:92100}, {name:tickUpper, type:int24, order:5, indexed:false, value:108120, valueString:108120}, {name:amount0Desired, type:uint256, order:6, indexed:false, value:0, valueString:0}, {name:amount1Desired, type:uint256, order:7, indexed:false, value:779999999999999999999890, valueString:779999999999999999999890}, {name:amount0Min, type:uint256, order:8, indexed:false, value:0, valueString:0}, {name:amount1Min, type:uint256, order:9, indexed:false, value:779999999999999999999890, valueString:779999999999999999999890}, {name:recipient, type:address, order:10, indexed:false, value:0xd0953aC488190BbD59240E0A59F697e32e303532, valueString:0xd0953aC488190BbD59240E0A59F697e32e303532}, {name:deadline, type:uint256, order:11, indexed:false, value:1731008951, valueString:1731008951}] ) => ( tokenId=852551, liquidity=6356000161339114119336, amount0=0, amount1=779999999999999999999890 )
              • UniswapV3Pool.STATICCALL( )
              • UniswapV3Pool.mint( recipient=0xC36442b4a4522E871399CD717aBDD847Ab11FE88, tickLower=92100, tickUpper=108120, amount=6356000161339114119336, data=0x000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC2000000000000000000000000F3768D6E78E65FC64B8F12FFC824452130BD53940000000000000000000000000000000000000000000000000000000000000BB8000000000000000000000000D0953AC488190BBD59240E0A59F697E32E303532 ) => ( amount0=0, amount1=779999999999999999999890 )
                • Kerosine.balanceOf( 0x905f81B37e673Cc89Fd777d17e1AF296aFA8f9A0 ) => ( 0 )
                • NonfungiblePositionManager.uniswapV3MintCallback( amount0Owed=0, amount1Owed=779999999999999999999890, data=0x000000000000000000000000C02AAA39B223FE8D0A0E5C4F27EAD9083C756CC2000000000000000000000000F3768D6E78E65FC64B8F12FFC824452130BD53940000000000000000000000000000000000000000000000000000000000000BB8000000000000000000000000D0953AC488190BBD59240E0A59F697E32E303532 )
                  • Kerosine.transferFrom( from=0xd0953aC488190BbD59240E0A59F697e32e303532, to=0x905f81B37e673Cc89Fd777d17e1AF296aFA8f9A0, amount=779999999999999999999890 ) => ( True )
                  • Kerosine.balanceOf( 0x905f81B37e673Cc89Fd777d17e1AF296aFA8f9A0 ) => ( 779999999999999999999890 )
                  • UniswapV3Pool.positions( 9BDD4BC3480802CB77518F2DA0A2DCDB810D49B9DF10B2DF888BA6AB023BAA88 ) => ( liquidity=6356000161339114119336, feeGrowthInside0LastX128=0, feeGrowthInside1LastX128=0, tokensOwed0=0, tokensOwed1=0 )
                    File 1 of 6: GnosisSafeProxy
                    // SPDX-License-Identifier: LGPL-3.0-only
                    pragma solidity >=0.7.0 <0.9.0;
                    
                    /// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
                    /// @author Richard Meissner - <[email protected]>
                    interface IProxy {
                        function masterCopy() external view returns (address);
                    }
                    
                    /// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
                    /// @author Stefan George - <[email protected]>
                    /// @author Richard Meissner - <[email protected]>
                    contract GnosisSafeProxy {
                        // singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
                        // To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
                        address internal singleton;
                    
                        /// @dev Constructor function sets address of singleton contract.
                        /// @param _singleton Singleton address.
                        constructor(address _singleton) {
                            require(_singleton != address(0), "Invalid singleton address provided");
                            singleton = _singleton;
                        }
                    
                        /// @dev Fallback function forwards all transactions and returns all received return data.
                        fallback() external payable {
                            // solhint-disable-next-line no-inline-assembly
                            assembly {
                                let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
                                // 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
                                if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
                                    mstore(0, _singleton)
                                    return(0, 0x20)
                                }
                                calldatacopy(0, 0, calldatasize())
                                let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
                                returndatacopy(0, 0, returndatasize())
                                if eq(success, 0) {
                                    revert(0, returndatasize())
                                }
                                return(0, returndatasize())
                            }
                        }
                    }
                    
                    /// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
                    /// @author Stefan George - <[email protected]>
                    contract GnosisSafeProxyFactory {
                        event ProxyCreation(GnosisSafeProxy proxy, address singleton);
                    
                        /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
                        /// @param singleton Address of singleton contract.
                        /// @param data Payload for message call sent to new proxy contract.
                        function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) {
                            proxy = new GnosisSafeProxy(singleton);
                            if (data.length > 0)
                                // solhint-disable-next-line no-inline-assembly
                                assembly {
                                    if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) {
                                        revert(0, 0)
                                    }
                                }
                            emit ProxyCreation(proxy, singleton);
                        }
                    
                        /// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed.
                        function proxyRuntimeCode() public pure returns (bytes memory) {
                            return type(GnosisSafeProxy).runtimeCode;
                        }
                    
                        /// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address.
                        function proxyCreationCode() public pure returns (bytes memory) {
                            return type(GnosisSafeProxy).creationCode;
                        }
                    
                        /// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer.
                        ///      This method is only meant as an utility to be called from other methods
                        /// @param _singleton Address of singleton contract.
                        /// @param initializer Payload for message call sent to new proxy contract.
                        /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
                        function deployProxyWithNonce(
                            address _singleton,
                            bytes memory initializer,
                            uint256 saltNonce
                        ) internal returns (GnosisSafeProxy proxy) {
                            // If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it
                            bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce));
                            bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton)));
                            // solhint-disable-next-line no-inline-assembly
                            assembly {
                                proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt)
                            }
                            require(address(proxy) != address(0), "Create2 call failed");
                        }
                    
                        /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
                        /// @param _singleton Address of singleton contract.
                        /// @param initializer Payload for message call sent to new proxy contract.
                        /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
                        function createProxyWithNonce(
                            address _singleton,
                            bytes memory initializer,
                            uint256 saltNonce
                        ) public returns (GnosisSafeProxy proxy) {
                            proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
                            if (initializer.length > 0)
                                // solhint-disable-next-line no-inline-assembly
                                assembly {
                                    if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) {
                                        revert(0, 0)
                                    }
                                }
                            emit ProxyCreation(proxy, _singleton);
                        }
                    
                        /// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction
                        /// @param _singleton Address of singleton contract.
                        /// @param initializer Payload for message call sent to new proxy contract.
                        /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
                        /// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized.
                        function createProxyWithCallback(
                            address _singleton,
                            bytes memory initializer,
                            uint256 saltNonce,
                            IProxyCreationCallback callback
                        ) public returns (GnosisSafeProxy proxy) {
                            uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback)));
                            proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback);
                            if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce);
                        }
                    
                        /// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce`
                        ///      This method is only meant for address calculation purpose when you use an initializer that would revert,
                        ///      therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory.
                        /// @param _singleton Address of singleton contract.
                        /// @param initializer Payload for message call sent to new proxy contract.
                        /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract.
                        function calculateCreateProxyWithNonceAddress(
                            address _singleton,
                            bytes calldata initializer,
                            uint256 saltNonce
                        ) external returns (GnosisSafeProxy proxy) {
                            proxy = deployProxyWithNonce(_singleton, initializer, saltNonce);
                            revert(string(abi.encodePacked(proxy)));
                        }
                    }
                    
                    interface IProxyCreationCallback {
                        function proxyCreated(
                            GnosisSafeProxy proxy,
                            address _singleton,
                            bytes calldata initializer,
                            uint256 saltNonce
                        ) external;
                    }

                    File 2 of 6: UniswapV3Factory
                    // SPDX-License-Identifier: BUSL-1.1
                    pragma solidity =0.7.6;
                    import './interfaces/IUniswapV3Factory.sol';
                    import './UniswapV3PoolDeployer.sol';
                    import './NoDelegateCall.sol';
                    import './UniswapV3Pool.sol';
                    /// @title Canonical Uniswap V3 factory
                    /// @notice Deploys Uniswap V3 pools and manages ownership and control over pool protocol fees
                    contract UniswapV3Factory is IUniswapV3Factory, UniswapV3PoolDeployer, NoDelegateCall {
                        /// @inheritdoc IUniswapV3Factory
                        address public override owner;
                        /// @inheritdoc IUniswapV3Factory
                        mapping(uint24 => int24) public override feeAmountTickSpacing;
                        /// @inheritdoc IUniswapV3Factory
                        mapping(address => mapping(address => mapping(uint24 => address))) public override getPool;
                        constructor() {
                            owner = msg.sender;
                            emit OwnerChanged(address(0), msg.sender);
                            feeAmountTickSpacing[500] = 10;
                            emit FeeAmountEnabled(500, 10);
                            feeAmountTickSpacing[3000] = 60;
                            emit FeeAmountEnabled(3000, 60);
                            feeAmountTickSpacing[10000] = 200;
                            emit FeeAmountEnabled(10000, 200);
                        }
                        /// @inheritdoc IUniswapV3Factory
                        function createPool(
                            address tokenA,
                            address tokenB,
                            uint24 fee
                        ) external override noDelegateCall returns (address pool) {
                            require(tokenA != tokenB);
                            (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
                            require(token0 != address(0));
                            int24 tickSpacing = feeAmountTickSpacing[fee];
                            require(tickSpacing != 0);
                            require(getPool[token0][token1][fee] == address(0));
                            pool = deploy(address(this), token0, token1, fee, tickSpacing);
                            getPool[token0][token1][fee] = pool;
                            // populate mapping in the reverse direction, deliberate choice to avoid the cost of comparing addresses
                            getPool[token1][token0][fee] = pool;
                            emit PoolCreated(token0, token1, fee, tickSpacing, pool);
                        }
                        /// @inheritdoc IUniswapV3Factory
                        function setOwner(address _owner) external override {
                            require(msg.sender == owner);
                            emit OwnerChanged(owner, _owner);
                            owner = _owner;
                        }
                        /// @inheritdoc IUniswapV3Factory
                        function enableFeeAmount(uint24 fee, int24 tickSpacing) public override {
                            require(msg.sender == owner);
                            require(fee < 1000000);
                            // tick spacing is capped at 16384 to prevent the situation where tickSpacing is so large that
                            // TickBitmap#nextInitializedTickWithinOneWord overflows int24 container from a valid tick
                            // 16384 ticks represents a >5x price change with ticks of 1 bips
                            require(tickSpacing > 0 && tickSpacing < 16384);
                            require(feeAmountTickSpacing[fee] == 0);
                            feeAmountTickSpacing[fee] = tickSpacing;
                            emit FeeAmountEnabled(fee, tickSpacing);
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title The interface for the Uniswap V3 Factory
                    /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees
                    interface IUniswapV3Factory {
                        /// @notice Emitted when the owner of the factory is changed
                        /// @param oldOwner The owner before the owner was changed
                        /// @param newOwner The owner after the owner was changed
                        event OwnerChanged(address indexed oldOwner, address indexed newOwner);
                        /// @notice Emitted when a pool is created
                        /// @param token0 The first token of the pool by address sort order
                        /// @param token1 The second token of the pool by address sort order
                        /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
                        /// @param tickSpacing The minimum number of ticks between initialized ticks
                        /// @param pool The address of the created pool
                        event PoolCreated(
                            address indexed token0,
                            address indexed token1,
                            uint24 indexed fee,
                            int24 tickSpacing,
                            address pool
                        );
                        /// @notice Emitted when a new fee amount is enabled for pool creation via the factory
                        /// @param fee The enabled fee, denominated in hundredths of a bip
                        /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee
                        event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);
                        /// @notice Returns the current owner of the factory
                        /// @dev Can be changed by the current owner via setOwner
                        /// @return The address of the factory owner
                        function owner() external view returns (address);
                        /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled
                        /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context
                        /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee
                        /// @return The tick spacing
                        function feeAmountTickSpacing(uint24 fee) external view returns (int24);
                        /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist
                        /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
                        /// @param tokenA The contract address of either token0 or token1
                        /// @param tokenB The contract address of the other token
                        /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
                        /// @return pool The pool address
                        function getPool(
                            address tokenA,
                            address tokenB,
                            uint24 fee
                        ) external view returns (address pool);
                        /// @notice Creates a pool for the given two tokens and fee
                        /// @param tokenA One of the two tokens in the desired pool
                        /// @param tokenB The other of the two tokens in the desired pool
                        /// @param fee The desired fee for the pool
                        /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
                        /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
                        /// are invalid.
                        /// @return pool The address of the newly created pool
                        function createPool(
                            address tokenA,
                            address tokenB,
                            uint24 fee
                        ) external returns (address pool);
                        /// @notice Updates the owner of the factory
                        /// @dev Must be called by the current owner
                        /// @param _owner The new owner of the factory
                        function setOwner(address _owner) external;
                        /// @notice Enables a fee amount with the given tickSpacing
                        /// @dev Fee amounts may never be removed once enabled
                        /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)
                        /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount
                        function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
                    }
                    // SPDX-License-Identifier: BUSL-1.1
                    pragma solidity =0.7.6;
                    import './interfaces/IUniswapV3PoolDeployer.sol';
                    import './UniswapV3Pool.sol';
                    contract UniswapV3PoolDeployer is IUniswapV3PoolDeployer {
                        struct Parameters {
                            address factory;
                            address token0;
                            address token1;
                            uint24 fee;
                            int24 tickSpacing;
                        }
                        /// @inheritdoc IUniswapV3PoolDeployer
                        Parameters public override parameters;
                        /// @dev Deploys a pool with the given parameters by transiently setting the parameters storage slot and then
                        /// clearing it after deploying the pool.
                        /// @param factory The contract address of the Uniswap V3 factory
                        /// @param token0 The first token of the pool by address sort order
                        /// @param token1 The second token of the pool by address sort order
                        /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
                        /// @param tickSpacing The spacing between usable ticks
                        function deploy(
                            address factory,
                            address token0,
                            address token1,
                            uint24 fee,
                            int24 tickSpacing
                        ) internal returns (address pool) {
                            parameters = Parameters({factory: factory, token0: token0, token1: token1, fee: fee, tickSpacing: tickSpacing});
                            pool = address(new UniswapV3Pool{salt: keccak256(abi.encode(token0, token1, fee))}());
                            delete parameters;
                        }
                    }
                    // SPDX-License-Identifier: BUSL-1.1
                    pragma solidity =0.7.6;
                    /// @title Prevents delegatecall to a contract
                    /// @notice Base contract that provides a modifier for preventing delegatecall to methods in a child contract
                    abstract contract NoDelegateCall {
                        /// @dev The original address of this contract
                        address private immutable original;
                        constructor() {
                            // Immutables are computed in the init code of the contract, and then inlined into the deployed bytecode.
                            // In other words, this variable won't change when it's checked at runtime.
                            original = address(this);
                        }
                        /// @dev Private method is used instead of inlining into modifier because modifiers are copied into each method,
                        ///     and the use of immutable means the address bytes are copied in every place the modifier is used.
                        function checkNotDelegateCall() private view {
                            require(address(this) == original);
                        }
                        /// @notice Prevents delegatecall into the modified method
                        modifier noDelegateCall() {
                            checkNotDelegateCall();
                            _;
                        }
                    }
                    // SPDX-License-Identifier: BUSL-1.1
                    pragma solidity =0.7.6;
                    import './interfaces/IUniswapV3Pool.sol';
                    import './NoDelegateCall.sol';
                    import './libraries/LowGasSafeMath.sol';
                    import './libraries/SafeCast.sol';
                    import './libraries/Tick.sol';
                    import './libraries/TickBitmap.sol';
                    import './libraries/Position.sol';
                    import './libraries/Oracle.sol';
                    import './libraries/FullMath.sol';
                    import './libraries/FixedPoint128.sol';
                    import './libraries/TransferHelper.sol';
                    import './libraries/TickMath.sol';
                    import './libraries/LiquidityMath.sol';
                    import './libraries/SqrtPriceMath.sol';
                    import './libraries/SwapMath.sol';
                    import './interfaces/IUniswapV3PoolDeployer.sol';
                    import './interfaces/IUniswapV3Factory.sol';
                    import './interfaces/IERC20Minimal.sol';
                    import './interfaces/callback/IUniswapV3MintCallback.sol';
                    import './interfaces/callback/IUniswapV3SwapCallback.sol';
                    import './interfaces/callback/IUniswapV3FlashCallback.sol';
                    contract UniswapV3Pool is IUniswapV3Pool, NoDelegateCall {
                        using LowGasSafeMath for uint256;
                        using LowGasSafeMath for int256;
                        using SafeCast for uint256;
                        using SafeCast for int256;
                        using Tick for mapping(int24 => Tick.Info);
                        using TickBitmap for mapping(int16 => uint256);
                        using Position for mapping(bytes32 => Position.Info);
                        using Position for Position.Info;
                        using Oracle for Oracle.Observation[65535];
                        /// @inheritdoc IUniswapV3PoolImmutables
                        address public immutable override factory;
                        /// @inheritdoc IUniswapV3PoolImmutables
                        address public immutable override token0;
                        /// @inheritdoc IUniswapV3PoolImmutables
                        address public immutable override token1;
                        /// @inheritdoc IUniswapV3PoolImmutables
                        uint24 public immutable override fee;
                        /// @inheritdoc IUniswapV3PoolImmutables
                        int24 public immutable override tickSpacing;
                        /// @inheritdoc IUniswapV3PoolImmutables
                        uint128 public immutable override maxLiquidityPerTick;
                        struct Slot0 {
                            // the current price
                            uint160 sqrtPriceX96;
                            // the current tick
                            int24 tick;
                            // the most-recently updated index of the observations array
                            uint16 observationIndex;
                            // the current maximum number of observations that are being stored
                            uint16 observationCardinality;
                            // the next maximum number of observations to store, triggered in observations.write
                            uint16 observationCardinalityNext;
                            // the current protocol fee as a percentage of the swap fee taken on withdrawal
                            // represented as an integer denominator (1/x)%
                            uint8 feeProtocol;
                            // whether the pool is locked
                            bool unlocked;
                        }
                        /// @inheritdoc IUniswapV3PoolState
                        Slot0 public override slot0;
                        /// @inheritdoc IUniswapV3PoolState
                        uint256 public override feeGrowthGlobal0X128;
                        /// @inheritdoc IUniswapV3PoolState
                        uint256 public override feeGrowthGlobal1X128;
                        // accumulated protocol fees in token0/token1 units
                        struct ProtocolFees {
                            uint128 token0;
                            uint128 token1;
                        }
                        /// @inheritdoc IUniswapV3PoolState
                        ProtocolFees public override protocolFees;
                        /// @inheritdoc IUniswapV3PoolState
                        uint128 public override liquidity;
                        /// @inheritdoc IUniswapV3PoolState
                        mapping(int24 => Tick.Info) public override ticks;
                        /// @inheritdoc IUniswapV3PoolState
                        mapping(int16 => uint256) public override tickBitmap;
                        /// @inheritdoc IUniswapV3PoolState
                        mapping(bytes32 => Position.Info) public override positions;
                        /// @inheritdoc IUniswapV3PoolState
                        Oracle.Observation[65535] public override observations;
                        /// @dev Mutually exclusive reentrancy protection into the pool to/from a method. This method also prevents entrance
                        /// to a function before the pool is initialized. The reentrancy guard is required throughout the contract because
                        /// we use balance checks to determine the payment status of interactions such as mint, swap and flash.
                        modifier lock() {
                            require(slot0.unlocked, 'LOK');
                            slot0.unlocked = false;
                            _;
                            slot0.unlocked = true;
                        }
                        /// @dev Prevents calling a function from anyone except the address returned by IUniswapV3Factory#owner()
                        modifier onlyFactoryOwner() {
                            require(msg.sender == IUniswapV3Factory(factory).owner());
                            _;
                        }
                        constructor() {
                            int24 _tickSpacing;
                            (factory, token0, token1, fee, _tickSpacing) = IUniswapV3PoolDeployer(msg.sender).parameters();
                            tickSpacing = _tickSpacing;
                            maxLiquidityPerTick = Tick.tickSpacingToMaxLiquidityPerTick(_tickSpacing);
                        }
                        /// @dev Common checks for valid tick inputs.
                        function checkTicks(int24 tickLower, int24 tickUpper) private pure {
                            require(tickLower < tickUpper, 'TLU');
                            require(tickLower >= TickMath.MIN_TICK, 'TLM');
                            require(tickUpper <= TickMath.MAX_TICK, 'TUM');
                        }
                        /// @dev Returns the block timestamp truncated to 32 bits, i.e. mod 2**32. This method is overridden in tests.
                        function _blockTimestamp() internal view virtual returns (uint32) {
                            return uint32(block.timestamp); // truncation is desired
                        }
                        /// @dev Get the pool's balance of token0
                        /// @dev This function is gas optimized to avoid a redundant extcodesize check in addition to the returndatasize
                        /// check
                        function balance0() private view returns (uint256) {
                            (bool success, bytes memory data) =
                                token0.staticcall(abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this)));
                            require(success && data.length >= 32);
                            return abi.decode(data, (uint256));
                        }
                        /// @dev Get the pool's balance of token1
                        /// @dev This function is gas optimized to avoid a redundant extcodesize check in addition to the returndatasize
                        /// check
                        function balance1() private view returns (uint256) {
                            (bool success, bytes memory data) =
                                token1.staticcall(abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this)));
                            require(success && data.length >= 32);
                            return abi.decode(data, (uint256));
                        }
                        /// @inheritdoc IUniswapV3PoolDerivedState
                        function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
                            external
                            view
                            override
                            noDelegateCall
                            returns (
                                int56 tickCumulativeInside,
                                uint160 secondsPerLiquidityInsideX128,
                                uint32 secondsInside
                            )
                        {
                            checkTicks(tickLower, tickUpper);
                            int56 tickCumulativeLower;
                            int56 tickCumulativeUpper;
                            uint160 secondsPerLiquidityOutsideLowerX128;
                            uint160 secondsPerLiquidityOutsideUpperX128;
                            uint32 secondsOutsideLower;
                            uint32 secondsOutsideUpper;
                            {
                                Tick.Info storage lower = ticks[tickLower];
                                Tick.Info storage upper = ticks[tickUpper];
                                bool initializedLower;
                                (tickCumulativeLower, secondsPerLiquidityOutsideLowerX128, secondsOutsideLower, initializedLower) = (
                                    lower.tickCumulativeOutside,
                                    lower.secondsPerLiquidityOutsideX128,
                                    lower.secondsOutside,
                                    lower.initialized
                                );
                                require(initializedLower);
                                bool initializedUpper;
                                (tickCumulativeUpper, secondsPerLiquidityOutsideUpperX128, secondsOutsideUpper, initializedUpper) = (
                                    upper.tickCumulativeOutside,
                                    upper.secondsPerLiquidityOutsideX128,
                                    upper.secondsOutside,
                                    upper.initialized
                                );
                                require(initializedUpper);
                            }
                            Slot0 memory _slot0 = slot0;
                            if (_slot0.tick < tickLower) {
                                return (
                                    tickCumulativeLower - tickCumulativeUpper,
                                    secondsPerLiquidityOutsideLowerX128 - secondsPerLiquidityOutsideUpperX128,
                                    secondsOutsideLower - secondsOutsideUpper
                                );
                            } else if (_slot0.tick < tickUpper) {
                                uint32 time = _blockTimestamp();
                                (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) =
                                    observations.observeSingle(
                                        time,
                                        0,
                                        _slot0.tick,
                                        _slot0.observationIndex,
                                        liquidity,
                                        _slot0.observationCardinality
                                    );
                                return (
                                    tickCumulative - tickCumulativeLower - tickCumulativeUpper,
                                    secondsPerLiquidityCumulativeX128 -
                                        secondsPerLiquidityOutsideLowerX128 -
                                        secondsPerLiquidityOutsideUpperX128,
                                    time - secondsOutsideLower - secondsOutsideUpper
                                );
                            } else {
                                return (
                                    tickCumulativeUpper - tickCumulativeLower,
                                    secondsPerLiquidityOutsideUpperX128 - secondsPerLiquidityOutsideLowerX128,
                                    secondsOutsideUpper - secondsOutsideLower
                                );
                            }
                        }
                        /// @inheritdoc IUniswapV3PoolDerivedState
                        function observe(uint32[] calldata secondsAgos)
                            external
                            view
                            override
                            noDelegateCall
                            returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s)
                        {
                            return
                                observations.observe(
                                    _blockTimestamp(),
                                    secondsAgos,
                                    slot0.tick,
                                    slot0.observationIndex,
                                    liquidity,
                                    slot0.observationCardinality
                                );
                        }
                        /// @inheritdoc IUniswapV3PoolActions
                        function increaseObservationCardinalityNext(uint16 observationCardinalityNext)
                            external
                            override
                            lock
                            noDelegateCall
                        {
                            uint16 observationCardinalityNextOld = slot0.observationCardinalityNext; // for the event
                            uint16 observationCardinalityNextNew =
                                observations.grow(observationCardinalityNextOld, observationCardinalityNext);
                            slot0.observationCardinalityNext = observationCardinalityNextNew;
                            if (observationCardinalityNextOld != observationCardinalityNextNew)
                                emit IncreaseObservationCardinalityNext(observationCardinalityNextOld, observationCardinalityNextNew);
                        }
                        /// @inheritdoc IUniswapV3PoolActions
                        /// @dev not locked because it initializes unlocked
                        function initialize(uint160 sqrtPriceX96) external override {
                            require(slot0.sqrtPriceX96 == 0, 'AI');
                            int24 tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96);
                            (uint16 cardinality, uint16 cardinalityNext) = observations.initialize(_blockTimestamp());
                            slot0 = Slot0({
                                sqrtPriceX96: sqrtPriceX96,
                                tick: tick,
                                observationIndex: 0,
                                observationCardinality: cardinality,
                                observationCardinalityNext: cardinalityNext,
                                feeProtocol: 0,
                                unlocked: true
                            });
                            emit Initialize(sqrtPriceX96, tick);
                        }
                        struct ModifyPositionParams {
                            // the address that owns the position
                            address owner;
                            // the lower and upper tick of the position
                            int24 tickLower;
                            int24 tickUpper;
                            // any change in liquidity
                            int128 liquidityDelta;
                        }
                        /// @dev Effect some changes to a position
                        /// @param params the position details and the change to the position's liquidity to effect
                        /// @return position a storage pointer referencing the position with the given owner and tick range
                        /// @return amount0 the amount of token0 owed to the pool, negative if the pool should pay the recipient
                        /// @return amount1 the amount of token1 owed to the pool, negative if the pool should pay the recipient
                        function _modifyPosition(ModifyPositionParams memory params)
                            private
                            noDelegateCall
                            returns (
                                Position.Info storage position,
                                int256 amount0,
                                int256 amount1
                            )
                        {
                            checkTicks(params.tickLower, params.tickUpper);
                            Slot0 memory _slot0 = slot0; // SLOAD for gas optimization
                            position = _updatePosition(
                                params.owner,
                                params.tickLower,
                                params.tickUpper,
                                params.liquidityDelta,
                                _slot0.tick
                            );
                            if (params.liquidityDelta != 0) {
                                if (_slot0.tick < params.tickLower) {
                                    // current tick is below the passed range; liquidity can only become in range by crossing from left to
                                    // right, when we'll need _more_ token0 (it's becoming more valuable) so user must provide it
                                    amount0 = SqrtPriceMath.getAmount0Delta(
                                        TickMath.getSqrtRatioAtTick(params.tickLower),
                                        TickMath.getSqrtRatioAtTick(params.tickUpper),
                                        params.liquidityDelta
                                    );
                                } else if (_slot0.tick < params.tickUpper) {
                                    // current tick is inside the passed range
                                    uint128 liquidityBefore = liquidity; // SLOAD for gas optimization
                                    // write an oracle entry
                                    (slot0.observationIndex, slot0.observationCardinality) = observations.write(
                                        _slot0.observationIndex,
                                        _blockTimestamp(),
                                        _slot0.tick,
                                        liquidityBefore,
                                        _slot0.observationCardinality,
                                        _slot0.observationCardinalityNext
                                    );
                                    amount0 = SqrtPriceMath.getAmount0Delta(
                                        _slot0.sqrtPriceX96,
                                        TickMath.getSqrtRatioAtTick(params.tickUpper),
                                        params.liquidityDelta
                                    );
                                    amount1 = SqrtPriceMath.getAmount1Delta(
                                        TickMath.getSqrtRatioAtTick(params.tickLower),
                                        _slot0.sqrtPriceX96,
                                        params.liquidityDelta
                                    );
                                    liquidity = LiquidityMath.addDelta(liquidityBefore, params.liquidityDelta);
                                } else {
                                    // current tick is above the passed range; liquidity can only become in range by crossing from right to
                                    // left, when we'll need _more_ token1 (it's becoming more valuable) so user must provide it
                                    amount1 = SqrtPriceMath.getAmount1Delta(
                                        TickMath.getSqrtRatioAtTick(params.tickLower),
                                        TickMath.getSqrtRatioAtTick(params.tickUpper),
                                        params.liquidityDelta
                                    );
                                }
                            }
                        }
                        /// @dev Gets and updates a position with the given liquidity delta
                        /// @param owner the owner of the position
                        /// @param tickLower the lower tick of the position's tick range
                        /// @param tickUpper the upper tick of the position's tick range
                        /// @param tick the current tick, passed to avoid sloads
                        function _updatePosition(
                            address owner,
                            int24 tickLower,
                            int24 tickUpper,
                            int128 liquidityDelta,
                            int24 tick
                        ) private returns (Position.Info storage position) {
                            position = positions.get(owner, tickLower, tickUpper);
                            uint256 _feeGrowthGlobal0X128 = feeGrowthGlobal0X128; // SLOAD for gas optimization
                            uint256 _feeGrowthGlobal1X128 = feeGrowthGlobal1X128; // SLOAD for gas optimization
                            // if we need to update the ticks, do it
                            bool flippedLower;
                            bool flippedUpper;
                            if (liquidityDelta != 0) {
                                uint32 time = _blockTimestamp();
                                (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) =
                                    observations.observeSingle(
                                        time,
                                        0,
                                        slot0.tick,
                                        slot0.observationIndex,
                                        liquidity,
                                        slot0.observationCardinality
                                    );
                                flippedLower = ticks.update(
                                    tickLower,
                                    tick,
                                    liquidityDelta,
                                    _feeGrowthGlobal0X128,
                                    _feeGrowthGlobal1X128,
                                    secondsPerLiquidityCumulativeX128,
                                    tickCumulative,
                                    time,
                                    false,
                                    maxLiquidityPerTick
                                );
                                flippedUpper = ticks.update(
                                    tickUpper,
                                    tick,
                                    liquidityDelta,
                                    _feeGrowthGlobal0X128,
                                    _feeGrowthGlobal1X128,
                                    secondsPerLiquidityCumulativeX128,
                                    tickCumulative,
                                    time,
                                    true,
                                    maxLiquidityPerTick
                                );
                                if (flippedLower) {
                                    tickBitmap.flipTick(tickLower, tickSpacing);
                                }
                                if (flippedUpper) {
                                    tickBitmap.flipTick(tickUpper, tickSpacing);
                                }
                            }
                            (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) =
                                ticks.getFeeGrowthInside(tickLower, tickUpper, tick, _feeGrowthGlobal0X128, _feeGrowthGlobal1X128);
                            position.update(liquidityDelta, feeGrowthInside0X128, feeGrowthInside1X128);
                            // clear any tick data that is no longer needed
                            if (liquidityDelta < 0) {
                                if (flippedLower) {
                                    ticks.clear(tickLower);
                                }
                                if (flippedUpper) {
                                    ticks.clear(tickUpper);
                                }
                            }
                        }
                        /// @inheritdoc IUniswapV3PoolActions
                        /// @dev noDelegateCall is applied indirectly via _modifyPosition
                        function mint(
                            address recipient,
                            int24 tickLower,
                            int24 tickUpper,
                            uint128 amount,
                            bytes calldata data
                        ) external override lock returns (uint256 amount0, uint256 amount1) {
                            require(amount > 0);
                            (, int256 amount0Int, int256 amount1Int) =
                                _modifyPosition(
                                    ModifyPositionParams({
                                        owner: recipient,
                                        tickLower: tickLower,
                                        tickUpper: tickUpper,
                                        liquidityDelta: int256(amount).toInt128()
                                    })
                                );
                            amount0 = uint256(amount0Int);
                            amount1 = uint256(amount1Int);
                            uint256 balance0Before;
                            uint256 balance1Before;
                            if (amount0 > 0) balance0Before = balance0();
                            if (amount1 > 0) balance1Before = balance1();
                            IUniswapV3MintCallback(msg.sender).uniswapV3MintCallback(amount0, amount1, data);
                            if (amount0 > 0) require(balance0Before.add(amount0) <= balance0(), 'M0');
                            if (amount1 > 0) require(balance1Before.add(amount1) <= balance1(), 'M1');
                            emit Mint(msg.sender, recipient, tickLower, tickUpper, amount, amount0, amount1);
                        }
                        /// @inheritdoc IUniswapV3PoolActions
                        function collect(
                            address recipient,
                            int24 tickLower,
                            int24 tickUpper,
                            uint128 amount0Requested,
                            uint128 amount1Requested
                        ) external override lock returns (uint128 amount0, uint128 amount1) {
                            // we don't need to checkTicks here, because invalid positions will never have non-zero tokensOwed{0,1}
                            Position.Info storage position = positions.get(msg.sender, tickLower, tickUpper);
                            amount0 = amount0Requested > position.tokensOwed0 ? position.tokensOwed0 : amount0Requested;
                            amount1 = amount1Requested > position.tokensOwed1 ? position.tokensOwed1 : amount1Requested;
                            if (amount0 > 0) {
                                position.tokensOwed0 -= amount0;
                                TransferHelper.safeTransfer(token0, recipient, amount0);
                            }
                            if (amount1 > 0) {
                                position.tokensOwed1 -= amount1;
                                TransferHelper.safeTransfer(token1, recipient, amount1);
                            }
                            emit Collect(msg.sender, recipient, tickLower, tickUpper, amount0, amount1);
                        }
                        /// @inheritdoc IUniswapV3PoolActions
                        /// @dev noDelegateCall is applied indirectly via _modifyPosition
                        function burn(
                            int24 tickLower,
                            int24 tickUpper,
                            uint128 amount
                        ) external override lock returns (uint256 amount0, uint256 amount1) {
                            (Position.Info storage position, int256 amount0Int, int256 amount1Int) =
                                _modifyPosition(
                                    ModifyPositionParams({
                                        owner: msg.sender,
                                        tickLower: tickLower,
                                        tickUpper: tickUpper,
                                        liquidityDelta: -int256(amount).toInt128()
                                    })
                                );
                            amount0 = uint256(-amount0Int);
                            amount1 = uint256(-amount1Int);
                            if (amount0 > 0 || amount1 > 0) {
                                (position.tokensOwed0, position.tokensOwed1) = (
                                    position.tokensOwed0 + uint128(amount0),
                                    position.tokensOwed1 + uint128(amount1)
                                );
                            }
                            emit Burn(msg.sender, tickLower, tickUpper, amount, amount0, amount1);
                        }
                        struct SwapCache {
                            // the protocol fee for the input token
                            uint8 feeProtocol;
                            // liquidity at the beginning of the swap
                            uint128 liquidityStart;
                            // the timestamp of the current block
                            uint32 blockTimestamp;
                            // the current value of the tick accumulator, computed only if we cross an initialized tick
                            int56 tickCumulative;
                            // the current value of seconds per liquidity accumulator, computed only if we cross an initialized tick
                            uint160 secondsPerLiquidityCumulativeX128;
                            // whether we've computed and cached the above two accumulators
                            bool computedLatestObservation;
                        }
                        // the top level state of the swap, the results of which are recorded in storage at the end
                        struct SwapState {
                            // the amount remaining to be swapped in/out of the input/output asset
                            int256 amountSpecifiedRemaining;
                            // the amount already swapped out/in of the output/input asset
                            int256 amountCalculated;
                            // current sqrt(price)
                            uint160 sqrtPriceX96;
                            // the tick associated with the current price
                            int24 tick;
                            // the global fee growth of the input token
                            uint256 feeGrowthGlobalX128;
                            // amount of input token paid as protocol fee
                            uint128 protocolFee;
                            // the current liquidity in range
                            uint128 liquidity;
                        }
                        struct StepComputations {
                            // the price at the beginning of the step
                            uint160 sqrtPriceStartX96;
                            // the next tick to swap to from the current tick in the swap direction
                            int24 tickNext;
                            // whether tickNext is initialized or not
                            bool initialized;
                            // sqrt(price) for the next tick (1/0)
                            uint160 sqrtPriceNextX96;
                            // how much is being swapped in in this step
                            uint256 amountIn;
                            // how much is being swapped out
                            uint256 amountOut;
                            // how much fee is being paid in
                            uint256 feeAmount;
                        }
                        /// @inheritdoc IUniswapV3PoolActions
                        function swap(
                            address recipient,
                            bool zeroForOne,
                            int256 amountSpecified,
                            uint160 sqrtPriceLimitX96,
                            bytes calldata data
                        ) external override noDelegateCall returns (int256 amount0, int256 amount1) {
                            require(amountSpecified != 0, 'AS');
                            Slot0 memory slot0Start = slot0;
                            require(slot0Start.unlocked, 'LOK');
                            require(
                                zeroForOne
                                    ? sqrtPriceLimitX96 < slot0Start.sqrtPriceX96 && sqrtPriceLimitX96 > TickMath.MIN_SQRT_RATIO
                                    : sqrtPriceLimitX96 > slot0Start.sqrtPriceX96 && sqrtPriceLimitX96 < TickMath.MAX_SQRT_RATIO,
                                'SPL'
                            );
                            slot0.unlocked = false;
                            SwapCache memory cache =
                                SwapCache({
                                    liquidityStart: liquidity,
                                    blockTimestamp: _blockTimestamp(),
                                    feeProtocol: zeroForOne ? (slot0Start.feeProtocol % 16) : (slot0Start.feeProtocol >> 4),
                                    secondsPerLiquidityCumulativeX128: 0,
                                    tickCumulative: 0,
                                    computedLatestObservation: false
                                });
                            bool exactInput = amountSpecified > 0;
                            SwapState memory state =
                                SwapState({
                                    amountSpecifiedRemaining: amountSpecified,
                                    amountCalculated: 0,
                                    sqrtPriceX96: slot0Start.sqrtPriceX96,
                                    tick: slot0Start.tick,
                                    feeGrowthGlobalX128: zeroForOne ? feeGrowthGlobal0X128 : feeGrowthGlobal1X128,
                                    protocolFee: 0,
                                    liquidity: cache.liquidityStart
                                });
                            // continue swapping as long as we haven't used the entire input/output and haven't reached the price limit
                            while (state.amountSpecifiedRemaining != 0 && state.sqrtPriceX96 != sqrtPriceLimitX96) {
                                StepComputations memory step;
                                step.sqrtPriceStartX96 = state.sqrtPriceX96;
                                (step.tickNext, step.initialized) = tickBitmap.nextInitializedTickWithinOneWord(
                                    state.tick,
                                    tickSpacing,
                                    zeroForOne
                                );
                                // ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds
                                if (step.tickNext < TickMath.MIN_TICK) {
                                    step.tickNext = TickMath.MIN_TICK;
                                } else if (step.tickNext > TickMath.MAX_TICK) {
                                    step.tickNext = TickMath.MAX_TICK;
                                }
                                // get the price for the next tick
                                step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);
                                // compute values to swap to the target tick, price limit, or point where input/output amount is exhausted
                                (state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath.computeSwapStep(
                                    state.sqrtPriceX96,
                                    (zeroForOne ? step.sqrtPriceNextX96 < sqrtPriceLimitX96 : step.sqrtPriceNextX96 > sqrtPriceLimitX96)
                                        ? sqrtPriceLimitX96
                                        : step.sqrtPriceNextX96,
                                    state.liquidity,
                                    state.amountSpecifiedRemaining,
                                    fee
                                );
                                if (exactInput) {
                                    state.amountSpecifiedRemaining -= (step.amountIn + step.feeAmount).toInt256();
                                    state.amountCalculated = state.amountCalculated.sub(step.amountOut.toInt256());
                                } else {
                                    state.amountSpecifiedRemaining += step.amountOut.toInt256();
                                    state.amountCalculated = state.amountCalculated.add((step.amountIn + step.feeAmount).toInt256());
                                }
                                // if the protocol fee is on, calculate how much is owed, decrement feeAmount, and increment protocolFee
                                if (cache.feeProtocol > 0) {
                                    uint256 delta = step.feeAmount / cache.feeProtocol;
                                    step.feeAmount -= delta;
                                    state.protocolFee += uint128(delta);
                                }
                                // update global fee tracker
                                if (state.liquidity > 0)
                                    state.feeGrowthGlobalX128 += FullMath.mulDiv(step.feeAmount, FixedPoint128.Q128, state.liquidity);
                                // shift tick if we reached the next price
                                if (state.sqrtPriceX96 == step.sqrtPriceNextX96) {
                                    // if the tick is initialized, run the tick transition
                                    if (step.initialized) {
                                        // check for the placeholder value, which we replace with the actual value the first time the swap
                                        // crosses an initialized tick
                                        if (!cache.computedLatestObservation) {
                                            (cache.tickCumulative, cache.secondsPerLiquidityCumulativeX128) = observations.observeSingle(
                                                cache.blockTimestamp,
                                                0,
                                                slot0Start.tick,
                                                slot0Start.observationIndex,
                                                cache.liquidityStart,
                                                slot0Start.observationCardinality
                                            );
                                            cache.computedLatestObservation = true;
                                        }
                                        int128 liquidityNet =
                                            ticks.cross(
                                                step.tickNext,
                                                (zeroForOne ? state.feeGrowthGlobalX128 : feeGrowthGlobal0X128),
                                                (zeroForOne ? feeGrowthGlobal1X128 : state.feeGrowthGlobalX128),
                                                cache.secondsPerLiquidityCumulativeX128,
                                                cache.tickCumulative,
                                                cache.blockTimestamp
                                            );
                                        // if we're moving leftward, we interpret liquidityNet as the opposite sign
                                        // safe because liquidityNet cannot be type(int128).min
                                        if (zeroForOne) liquidityNet = -liquidityNet;
                                        state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);
                                    }
                                    state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;
                                } else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) {
                                    // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved
                                    state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);
                                }
                            }
                            // update tick and write an oracle entry if the tick change
                            if (state.tick != slot0Start.tick) {
                                (uint16 observationIndex, uint16 observationCardinality) =
                                    observations.write(
                                        slot0Start.observationIndex,
                                        cache.blockTimestamp,
                                        slot0Start.tick,
                                        cache.liquidityStart,
                                        slot0Start.observationCardinality,
                                        slot0Start.observationCardinalityNext
                                    );
                                (slot0.sqrtPriceX96, slot0.tick, slot0.observationIndex, slot0.observationCardinality) = (
                                    state.sqrtPriceX96,
                                    state.tick,
                                    observationIndex,
                                    observationCardinality
                                );
                            } else {
                                // otherwise just update the price
                                slot0.sqrtPriceX96 = state.sqrtPriceX96;
                            }
                            // update liquidity if it changed
                            if (cache.liquidityStart != state.liquidity) liquidity = state.liquidity;
                            // update fee growth global and, if necessary, protocol fees
                            // overflow is acceptable, protocol has to withdraw before it hits type(uint128).max fees
                            if (zeroForOne) {
                                feeGrowthGlobal0X128 = state.feeGrowthGlobalX128;
                                if (state.protocolFee > 0) protocolFees.token0 += state.protocolFee;
                            } else {
                                feeGrowthGlobal1X128 = state.feeGrowthGlobalX128;
                                if (state.protocolFee > 0) protocolFees.token1 += state.protocolFee;
                            }
                            (amount0, amount1) = zeroForOne == exactInput
                                ? (amountSpecified - state.amountSpecifiedRemaining, state.amountCalculated)
                                : (state.amountCalculated, amountSpecified - state.amountSpecifiedRemaining);
                            // do the transfers and collect payment
                            if (zeroForOne) {
                                if (amount1 < 0) TransferHelper.safeTransfer(token1, recipient, uint256(-amount1));
                                uint256 balance0Before = balance0();
                                IUniswapV3SwapCallback(msg.sender).uniswapV3SwapCallback(amount0, amount1, data);
                                require(balance0Before.add(uint256(amount0)) <= balance0(), 'IIA');
                            } else {
                                if (amount0 < 0) TransferHelper.safeTransfer(token0, recipient, uint256(-amount0));
                                uint256 balance1Before = balance1();
                                IUniswapV3SwapCallback(msg.sender).uniswapV3SwapCallback(amount0, amount1, data);
                                require(balance1Before.add(uint256(amount1)) <= balance1(), 'IIA');
                            }
                            emit Swap(msg.sender, recipient, amount0, amount1, state.sqrtPriceX96, state.liquidity, state.tick);
                            slot0.unlocked = true;
                        }
                        /// @inheritdoc IUniswapV3PoolActions
                        function flash(
                            address recipient,
                            uint256 amount0,
                            uint256 amount1,
                            bytes calldata data
                        ) external override lock noDelegateCall {
                            uint128 _liquidity = liquidity;
                            require(_liquidity > 0, 'L');
                            uint256 fee0 = FullMath.mulDivRoundingUp(amount0, fee, 1e6);
                            uint256 fee1 = FullMath.mulDivRoundingUp(amount1, fee, 1e6);
                            uint256 balance0Before = balance0();
                            uint256 balance1Before = balance1();
                            if (amount0 > 0) TransferHelper.safeTransfer(token0, recipient, amount0);
                            if (amount1 > 0) TransferHelper.safeTransfer(token1, recipient, amount1);
                            IUniswapV3FlashCallback(msg.sender).uniswapV3FlashCallback(fee0, fee1, data);
                            uint256 balance0After = balance0();
                            uint256 balance1After = balance1();
                            require(balance0Before.add(fee0) <= balance0After, 'F0');
                            require(balance1Before.add(fee1) <= balance1After, 'F1');
                            // sub is safe because we know balanceAfter is gt balanceBefore by at least fee
                            uint256 paid0 = balance0After - balance0Before;
                            uint256 paid1 = balance1After - balance1Before;
                            if (paid0 > 0) {
                                uint8 feeProtocol0 = slot0.feeProtocol % 16;
                                uint256 fees0 = feeProtocol0 == 0 ? 0 : paid0 / feeProtocol0;
                                if (uint128(fees0) > 0) protocolFees.token0 += uint128(fees0);
                                feeGrowthGlobal0X128 += FullMath.mulDiv(paid0 - fees0, FixedPoint128.Q128, _liquidity);
                            }
                            if (paid1 > 0) {
                                uint8 feeProtocol1 = slot0.feeProtocol >> 4;
                                uint256 fees1 = feeProtocol1 == 0 ? 0 : paid1 / feeProtocol1;
                                if (uint128(fees1) > 0) protocolFees.token1 += uint128(fees1);
                                feeGrowthGlobal1X128 += FullMath.mulDiv(paid1 - fees1, FixedPoint128.Q128, _liquidity);
                            }
                            emit Flash(msg.sender, recipient, amount0, amount1, paid0, paid1);
                        }
                        /// @inheritdoc IUniswapV3PoolOwnerActions
                        function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external override lock onlyFactoryOwner {
                            require(
                                (feeProtocol0 == 0 || (feeProtocol0 >= 4 && feeProtocol0 <= 10)) &&
                                    (feeProtocol1 == 0 || (feeProtocol1 >= 4 && feeProtocol1 <= 10))
                            );
                            uint8 feeProtocolOld = slot0.feeProtocol;
                            slot0.feeProtocol = feeProtocol0 + (feeProtocol1 << 4);
                            emit SetFeeProtocol(feeProtocolOld % 16, feeProtocolOld >> 4, feeProtocol0, feeProtocol1);
                        }
                        /// @inheritdoc IUniswapV3PoolOwnerActions
                        function collectProtocol(
                            address recipient,
                            uint128 amount0Requested,
                            uint128 amount1Requested
                        ) external override lock onlyFactoryOwner returns (uint128 amount0, uint128 amount1) {
                            amount0 = amount0Requested > protocolFees.token0 ? protocolFees.token0 : amount0Requested;
                            amount1 = amount1Requested > protocolFees.token1 ? protocolFees.token1 : amount1Requested;
                            if (amount0 > 0) {
                                if (amount0 == protocolFees.token0) amount0--; // ensure that the slot is not cleared, for gas savings
                                protocolFees.token0 -= amount0;
                                TransferHelper.safeTransfer(token0, recipient, amount0);
                            }
                            if (amount1 > 0) {
                                if (amount1 == protocolFees.token1) amount1--; // ensure that the slot is not cleared, for gas savings
                                protocolFees.token1 -= amount1;
                                TransferHelper.safeTransfer(token1, recipient, amount1);
                            }
                            emit CollectProtocol(msg.sender, recipient, amount0, amount1);
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title An interface for a contract that is capable of deploying Uniswap V3 Pools
                    /// @notice A contract that constructs a pool must implement this to pass arguments to the pool
                    /// @dev This is used to avoid having constructor arguments in the pool contract, which results in the init code hash
                    /// of the pool being constant allowing the CREATE2 address of the pool to be cheaply computed on-chain
                    interface IUniswapV3PoolDeployer {
                        /// @notice Get the parameters to be used in constructing the pool, set transiently during pool creation.
                        /// @dev Called by the pool constructor to fetch the parameters of the pool
                        /// Returns factory The factory address
                        /// Returns token0 The first token of the pool by address sort order
                        /// Returns token1 The second token of the pool by address sort order
                        /// Returns fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
                        /// Returns tickSpacing The minimum number of ticks between initialized ticks
                        function parameters()
                            external
                            view
                            returns (
                                address factory,
                                address token0,
                                address token1,
                                uint24 fee,
                                int24 tickSpacing
                            );
                    }
                    // 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
                    {
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.7.0;
                    /// @title Optimized overflow and underflow safe math operations
                    /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost
                    library LowGasSafeMath {
                        /// @notice Returns x + y, reverts if sum overflows uint256
                        /// @param x The augend
                        /// @param y The addend
                        /// @return z The sum of x and y
                        function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            require((z = x + y) >= x);
                        }
                        /// @notice Returns x - y, reverts if underflows
                        /// @param x The minuend
                        /// @param y The subtrahend
                        /// @return z The difference of x and y
                        function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            require((z = x - y) <= x);
                        }
                        /// @notice Returns x * y, reverts if overflows
                        /// @param x The multiplicand
                        /// @param y The multiplier
                        /// @return z The product of x and y
                        function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            require(x == 0 || (z = x * y) / x == y);
                        }
                        /// @notice Returns x + y, reverts if overflows or underflows
                        /// @param x The augend
                        /// @param y The addend
                        /// @return z The sum of x and y
                        function add(int256 x, int256 y) internal pure returns (int256 z) {
                            require((z = x + y) >= x == (y >= 0));
                        }
                        /// @notice Returns x - y, reverts if overflows or underflows
                        /// @param x The minuend
                        /// @param y The subtrahend
                        /// @return z The difference of x and y
                        function sub(int256 x, int256 y) internal pure returns (int256 z) {
                            require((z = x - y) <= x == (y >= 0));
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title Safe casting methods
                    /// @notice Contains methods for safely casting between types
                    library SafeCast {
                        /// @notice Cast a uint256 to a uint160, revert on overflow
                        /// @param y The uint256 to be downcasted
                        /// @return z The downcasted integer, now type uint160
                        function toUint160(uint256 y) internal pure returns (uint160 z) {
                            require((z = uint160(y)) == y);
                        }
                        /// @notice Cast a int256 to a int128, revert on overflow or underflow
                        /// @param y The int256 to be downcasted
                        /// @return z The downcasted integer, now type int128
                        function toInt128(int256 y) internal pure returns (int128 z) {
                            require((z = int128(y)) == y);
                        }
                        /// @notice Cast a uint256 to a int256, revert on overflow
                        /// @param y The uint256 to be casted
                        /// @return z The casted integer, now type int256
                        function toInt256(uint256 y) internal pure returns (int256 z) {
                            require(y < 2**255);
                            z = int256(y);
                        }
                    }
                    // SPDX-License-Identifier: BUSL-1.1
                    pragma solidity >=0.5.0;
                    import './LowGasSafeMath.sol';
                    import './SafeCast.sol';
                    import './TickMath.sol';
                    import './LiquidityMath.sol';
                    /// @title Tick
                    /// @notice Contains functions for managing tick processes and relevant calculations
                    library Tick {
                        using LowGasSafeMath for int256;
                        using SafeCast for int256;
                        // info stored for each initialized individual tick
                        struct Info {
                            // the total position liquidity that references this tick
                            uint128 liquidityGross;
                            // amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left),
                            int128 liquidityNet;
                            // fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
                            // only has relative meaning, not absolute — the value depends on when the tick is initialized
                            uint256 feeGrowthOutside0X128;
                            uint256 feeGrowthOutside1X128;
                            // the cumulative tick value on the other side of the tick
                            int56 tickCumulativeOutside;
                            // the seconds per unit of liquidity on the _other_ side of this tick (relative to the current tick)
                            // only has relative meaning, not absolute — the value depends on when the tick is initialized
                            uint160 secondsPerLiquidityOutsideX128;
                            // the seconds spent on the other side of the tick (relative to the current tick)
                            // only has relative meaning, not absolute — the value depends on when the tick is initialized
                            uint32 secondsOutside;
                            // true iff the tick is initialized, i.e. the value is exactly equivalent to the expression liquidityGross != 0
                            // these 8 bits are set to prevent fresh sstores when crossing newly initialized ticks
                            bool initialized;
                        }
                        /// @notice Derives max liquidity per tick from given tick spacing
                        /// @dev Executed within the pool constructor
                        /// @param tickSpacing The amount of required tick separation, realized in multiples of `tickSpacing`
                        ///     e.g., a tickSpacing of 3 requires ticks to be initialized every 3rd tick i.e., ..., -6, -3, 0, 3, 6, ...
                        /// @return The max liquidity per tick
                        function tickSpacingToMaxLiquidityPerTick(int24 tickSpacing) internal pure returns (uint128) {
                            int24 minTick = (TickMath.MIN_TICK / tickSpacing) * tickSpacing;
                            int24 maxTick = (TickMath.MAX_TICK / tickSpacing) * tickSpacing;
                            uint24 numTicks = uint24((maxTick - minTick) / tickSpacing) + 1;
                            return type(uint128).max / numTicks;
                        }
                        /// @notice Retrieves fee growth data
                        /// @param self The mapping containing all tick information for initialized ticks
                        /// @param tickLower The lower tick boundary of the position
                        /// @param tickUpper The upper tick boundary of the position
                        /// @param tickCurrent The current tick
                        /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0
                        /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1
                        /// @return feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries
                        /// @return feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries
                        function getFeeGrowthInside(
                            mapping(int24 => Tick.Info) storage self,
                            int24 tickLower,
                            int24 tickUpper,
                            int24 tickCurrent,
                            uint256 feeGrowthGlobal0X128,
                            uint256 feeGrowthGlobal1X128
                        ) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) {
                            Info storage lower = self[tickLower];
                            Info storage upper = self[tickUpper];
                            // calculate fee growth below
                            uint256 feeGrowthBelow0X128;
                            uint256 feeGrowthBelow1X128;
                            if (tickCurrent >= tickLower) {
                                feeGrowthBelow0X128 = lower.feeGrowthOutside0X128;
                                feeGrowthBelow1X128 = lower.feeGrowthOutside1X128;
                            } else {
                                feeGrowthBelow0X128 = feeGrowthGlobal0X128 - lower.feeGrowthOutside0X128;
                                feeGrowthBelow1X128 = feeGrowthGlobal1X128 - lower.feeGrowthOutside1X128;
                            }
                            // calculate fee growth above
                            uint256 feeGrowthAbove0X128;
                            uint256 feeGrowthAbove1X128;
                            if (tickCurrent < tickUpper) {
                                feeGrowthAbove0X128 = upper.feeGrowthOutside0X128;
                                feeGrowthAbove1X128 = upper.feeGrowthOutside1X128;
                            } else {
                                feeGrowthAbove0X128 = feeGrowthGlobal0X128 - upper.feeGrowthOutside0X128;
                                feeGrowthAbove1X128 = feeGrowthGlobal1X128 - upper.feeGrowthOutside1X128;
                            }
                            feeGrowthInside0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128;
                            feeGrowthInside1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128;
                        }
                        /// @notice Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa
                        /// @param self The mapping containing all tick information for initialized ticks
                        /// @param tick The tick that will be updated
                        /// @param tickCurrent The current tick
                        /// @param liquidityDelta A new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left)
                        /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0
                        /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1
                        /// @param secondsPerLiquidityCumulativeX128 The all-time seconds per max(1, liquidity) of the pool
                        /// @param time The current block timestamp cast to a uint32
                        /// @param upper true for updating a position's upper tick, or false for updating a position's lower tick
                        /// @param maxLiquidity The maximum liquidity allocation for a single tick
                        /// @return flipped Whether the tick was flipped from initialized to uninitialized, or vice versa
                        function update(
                            mapping(int24 => Tick.Info) storage self,
                            int24 tick,
                            int24 tickCurrent,
                            int128 liquidityDelta,
                            uint256 feeGrowthGlobal0X128,
                            uint256 feeGrowthGlobal1X128,
                            uint160 secondsPerLiquidityCumulativeX128,
                            int56 tickCumulative,
                            uint32 time,
                            bool upper,
                            uint128 maxLiquidity
                        ) internal returns (bool flipped) {
                            Tick.Info storage info = self[tick];
                            uint128 liquidityGrossBefore = info.liquidityGross;
                            uint128 liquidityGrossAfter = LiquidityMath.addDelta(liquidityGrossBefore, liquidityDelta);
                            require(liquidityGrossAfter <= maxLiquidity, 'LO');
                            flipped = (liquidityGrossAfter == 0) != (liquidityGrossBefore == 0);
                            if (liquidityGrossBefore == 0) {
                                // by convention, we assume that all growth before a tick was initialized happened _below_ the tick
                                if (tick <= tickCurrent) {
                                    info.feeGrowthOutside0X128 = feeGrowthGlobal0X128;
                                    info.feeGrowthOutside1X128 = feeGrowthGlobal1X128;
                                    info.secondsPerLiquidityOutsideX128 = secondsPerLiquidityCumulativeX128;
                                    info.tickCumulativeOutside = tickCumulative;
                                    info.secondsOutside = time;
                                }
                                info.initialized = true;
                            }
                            info.liquidityGross = liquidityGrossAfter;
                            // when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed)
                            info.liquidityNet = upper
                                ? int256(info.liquidityNet).sub(liquidityDelta).toInt128()
                                : int256(info.liquidityNet).add(liquidityDelta).toInt128();
                        }
                        /// @notice Clears tick data
                        /// @param self The mapping containing all initialized tick information for initialized ticks
                        /// @param tick The tick that will be cleared
                        function clear(mapping(int24 => Tick.Info) storage self, int24 tick) internal {
                            delete self[tick];
                        }
                        /// @notice Transitions to next tick as needed by price movement
                        /// @param self The mapping containing all tick information for initialized ticks
                        /// @param tick The destination tick of the transition
                        /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0
                        /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1
                        /// @param secondsPerLiquidityCumulativeX128 The current seconds per liquidity
                        /// @param time The current block.timestamp
                        /// @return liquidityNet The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left)
                        function cross(
                            mapping(int24 => Tick.Info) storage self,
                            int24 tick,
                            uint256 feeGrowthGlobal0X128,
                            uint256 feeGrowthGlobal1X128,
                            uint160 secondsPerLiquidityCumulativeX128,
                            int56 tickCumulative,
                            uint32 time
                        ) internal returns (int128 liquidityNet) {
                            Tick.Info storage info = self[tick];
                            info.feeGrowthOutside0X128 = feeGrowthGlobal0X128 - info.feeGrowthOutside0X128;
                            info.feeGrowthOutside1X128 = feeGrowthGlobal1X128 - info.feeGrowthOutside1X128;
                            info.secondsPerLiquidityOutsideX128 = secondsPerLiquidityCumulativeX128 - info.secondsPerLiquidityOutsideX128;
                            info.tickCumulativeOutside = tickCumulative - info.tickCumulativeOutside;
                            info.secondsOutside = time - info.secondsOutside;
                            liquidityNet = info.liquidityNet;
                        }
                    }
                    // SPDX-License-Identifier: BUSL-1.1
                    pragma solidity >=0.5.0;
                    import './BitMath.sol';
                    /// @title Packed tick initialized state library
                    /// @notice Stores a packed mapping of tick index to its initialized state
                    /// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.
                    library TickBitmap {
                        /// @notice Computes the position in the mapping where the initialized bit for a tick lives
                        /// @param tick The tick for which to compute the position
                        /// @return wordPos The key in the mapping containing the word in which the bit is stored
                        /// @return bitPos The bit position in the word where the flag is stored
                        function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) {
                            wordPos = int16(tick >> 8);
                            bitPos = uint8(tick % 256);
                        }
                        /// @notice Flips the initialized state for a given tick from false to true, or vice versa
                        /// @param self The mapping in which to flip the tick
                        /// @param tick The tick to flip
                        /// @param tickSpacing The spacing between usable ticks
                        function flipTick(
                            mapping(int16 => uint256) storage self,
                            int24 tick,
                            int24 tickSpacing
                        ) internal {
                            require(tick % tickSpacing == 0); // ensure that the tick is spaced
                            (int16 wordPos, uint8 bitPos) = position(tick / tickSpacing);
                            uint256 mask = 1 << bitPos;
                            self[wordPos] ^= mask;
                        }
                        /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either
                        /// to the left (less than or equal to) or right (greater than) of the given tick
                        /// @param self The mapping in which to compute the next initialized tick
                        /// @param tick The starting tick
                        /// @param tickSpacing The spacing between usable ticks
                        /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)
                        /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick
                        /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks
                        function nextInitializedTickWithinOneWord(
                            mapping(int16 => uint256) storage self,
                            int24 tick,
                            int24 tickSpacing,
                            bool lte
                        ) internal view returns (int24 next, bool initialized) {
                            int24 compressed = tick / tickSpacing;
                            if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity
                            if (lte) {
                                (int16 wordPos, uint8 bitPos) = position(compressed);
                                // all the 1s at or to the right of the current bitPos
                                uint256 mask = (1 << bitPos) - 1 + (1 << bitPos);
                                uint256 masked = self[wordPos] & mask;
                                // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word
                                initialized = masked != 0;
                                // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
                                next = initialized
                                    ? (compressed - int24(bitPos - BitMath.mostSignificantBit(masked))) * tickSpacing
                                    : (compressed - int24(bitPos)) * tickSpacing;
                            } else {
                                // start from the word of the next tick, since the current tick state doesn't matter
                                (int16 wordPos, uint8 bitPos) = position(compressed + 1);
                                // all the 1s at or to the left of the bitPos
                                uint256 mask = ~((1 << bitPos) - 1);
                                uint256 masked = self[wordPos] & mask;
                                // if there are no initialized ticks to the left of the current tick, return leftmost in the word
                                initialized = masked != 0;
                                // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
                                next = initialized
                                    ? (compressed + 1 + int24(BitMath.leastSignificantBit(masked) - bitPos)) * tickSpacing
                                    : (compressed + 1 + int24(type(uint8).max - bitPos)) * tickSpacing;
                            }
                        }
                    }
                    // SPDX-License-Identifier: BUSL-1.1
                    pragma solidity >=0.5.0;
                    import './FullMath.sol';
                    import './FixedPoint128.sol';
                    import './LiquidityMath.sol';
                    /// @title Position
                    /// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary
                    /// @dev Positions store additional state for tracking fees owed to the position
                    library Position {
                        // info stored for each user's position
                        struct Info {
                            // the amount of liquidity owned by this position
                            uint128 liquidity;
                            // fee growth per unit of liquidity as of the last update to liquidity or fees owed
                            uint256 feeGrowthInside0LastX128;
                            uint256 feeGrowthInside1LastX128;
                            // the fees owed to the position owner in token0/token1
                            uint128 tokensOwed0;
                            uint128 tokensOwed1;
                        }
                        /// @notice Returns the Info struct of a position, given an owner and position boundaries
                        /// @param self The mapping containing all user positions
                        /// @param owner The address of the position owner
                        /// @param tickLower The lower tick boundary of the position
                        /// @param tickUpper The upper tick boundary of the position
                        /// @return position The position info struct of the given owners' position
                        function get(
                            mapping(bytes32 => Info) storage self,
                            address owner,
                            int24 tickLower,
                            int24 tickUpper
                        ) internal view returns (Position.Info storage position) {
                            position = self[keccak256(abi.encodePacked(owner, tickLower, tickUpper))];
                        }
                        /// @notice Credits accumulated fees to a user's position
                        /// @param self The individual position to update
                        /// @param liquidityDelta The change in pool liquidity as a result of the position update
                        /// @param feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries
                        /// @param feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries
                        function update(
                            Info storage self,
                            int128 liquidityDelta,
                            uint256 feeGrowthInside0X128,
                            uint256 feeGrowthInside1X128
                        ) internal {
                            Info memory _self = self;
                            uint128 liquidityNext;
                            if (liquidityDelta == 0) {
                                require(_self.liquidity > 0, 'NP'); // disallow pokes for 0 liquidity positions
                                liquidityNext = _self.liquidity;
                            } else {
                                liquidityNext = LiquidityMath.addDelta(_self.liquidity, liquidityDelta);
                            }
                            // calculate accumulated fees
                            uint128 tokensOwed0 =
                                uint128(
                                    FullMath.mulDiv(
                                        feeGrowthInside0X128 - _self.feeGrowthInside0LastX128,
                                        _self.liquidity,
                                        FixedPoint128.Q128
                                    )
                                );
                            uint128 tokensOwed1 =
                                uint128(
                                    FullMath.mulDiv(
                                        feeGrowthInside1X128 - _self.feeGrowthInside1LastX128,
                                        _self.liquidity,
                                        FixedPoint128.Q128
                                    )
                                );
                            // update the position
                            if (liquidityDelta != 0) self.liquidity = liquidityNext;
                            self.feeGrowthInside0LastX128 = feeGrowthInside0X128;
                            self.feeGrowthInside1LastX128 = feeGrowthInside1X128;
                            if (tokensOwed0 > 0 || tokensOwed1 > 0) {
                                // overflow is acceptable, have to withdraw before you hit type(uint128).max fees
                                self.tokensOwed0 += tokensOwed0;
                                self.tokensOwed1 += tokensOwed1;
                            }
                        }
                    }
                    // SPDX-License-Identifier: BUSL-1.1
                    pragma solidity >=0.5.0;
                    /// @title Oracle
                    /// @notice Provides price and liquidity data useful for a wide variety of system designs
                    /// @dev Instances of stored oracle data, "observations", are collected in the oracle array
                    /// Every pool is initialized with an oracle array length of 1. Anyone can pay the SSTOREs to increase the
                    /// maximum length of the oracle array. New slots will be added when the array is fully populated.
                    /// Observations are overwritten when the full length of the oracle array is populated.
                    /// The most recent observation is available, independent of the length of the oracle array, by passing 0 to observe()
                    library Oracle {
                        struct Observation {
                            // the block timestamp of the observation
                            uint32 blockTimestamp;
                            // the tick accumulator, i.e. tick * time elapsed since the pool was first initialized
                            int56 tickCumulative;
                            // the seconds per liquidity, i.e. seconds elapsed / max(1, liquidity) since the pool was first initialized
                            uint160 secondsPerLiquidityCumulativeX128;
                            // whether or not the observation is initialized
                            bool initialized;
                        }
                        /// @notice Transforms a previous observation into a new observation, given the passage of time and the current tick and liquidity values
                        /// @dev blockTimestamp _must_ be chronologically equal to or greater than last.blockTimestamp, safe for 0 or 1 overflows
                        /// @param last The specified observation to be transformed
                        /// @param blockTimestamp The timestamp of the new observation
                        /// @param tick The active tick at the time of the new observation
                        /// @param liquidity The total in-range liquidity at the time of the new observation
                        /// @return Observation The newly populated observation
                        function transform(
                            Observation memory last,
                            uint32 blockTimestamp,
                            int24 tick,
                            uint128 liquidity
                        ) private pure returns (Observation memory) {
                            uint32 delta = blockTimestamp - last.blockTimestamp;
                            return
                                Observation({
                                    blockTimestamp: blockTimestamp,
                                    tickCumulative: last.tickCumulative + int56(tick) * delta,
                                    secondsPerLiquidityCumulativeX128: last.secondsPerLiquidityCumulativeX128 +
                                        ((uint160(delta) << 128) / (liquidity > 0 ? liquidity : 1)),
                                    initialized: true
                                });
                        }
                        /// @notice Initialize the oracle array by writing the first slot. Called once for the lifecycle of the observations array
                        /// @param self The stored oracle array
                        /// @param time The time of the oracle initialization, via block.timestamp truncated to uint32
                        /// @return cardinality The number of populated elements in the oracle array
                        /// @return cardinalityNext The new length of the oracle array, independent of population
                        function initialize(Observation[65535] storage self, uint32 time)
                            internal
                            returns (uint16 cardinality, uint16 cardinalityNext)
                        {
                            self[0] = Observation({
                                blockTimestamp: time,
                                tickCumulative: 0,
                                secondsPerLiquidityCumulativeX128: 0,
                                initialized: true
                            });
                            return (1, 1);
                        }
                        /// @notice Writes an oracle observation to the array
                        /// @dev Writable at most once per block. Index represents the most recently written element. cardinality and index must be tracked externally.
                        /// If the index is at the end of the allowable array length (according to cardinality), and the next cardinality
                        /// is greater than the current one, cardinality may be increased. This restriction is created to preserve ordering.
                        /// @param self The stored oracle array
                        /// @param index The index of the observation that was most recently written to the observations array
                        /// @param blockTimestamp The timestamp of the new observation
                        /// @param tick The active tick at the time of the new observation
                        /// @param liquidity The total in-range liquidity at the time of the new observation
                        /// @param cardinality The number of populated elements in the oracle array
                        /// @param cardinalityNext The new length of the oracle array, independent of population
                        /// @return indexUpdated The new index of the most recently written element in the oracle array
                        /// @return cardinalityUpdated The new cardinality of the oracle array
                        function write(
                            Observation[65535] storage self,
                            uint16 index,
                            uint32 blockTimestamp,
                            int24 tick,
                            uint128 liquidity,
                            uint16 cardinality,
                            uint16 cardinalityNext
                        ) internal returns (uint16 indexUpdated, uint16 cardinalityUpdated) {
                            Observation memory last = self[index];
                            // early return if we've already written an observation this block
                            if (last.blockTimestamp == blockTimestamp) return (index, cardinality);
                            // if the conditions are right, we can bump the cardinality
                            if (cardinalityNext > cardinality && index == (cardinality - 1)) {
                                cardinalityUpdated = cardinalityNext;
                            } else {
                                cardinalityUpdated = cardinality;
                            }
                            indexUpdated = (index + 1) % cardinalityUpdated;
                            self[indexUpdated] = transform(last, blockTimestamp, tick, liquidity);
                        }
                        /// @notice Prepares the oracle array to store up to `next` observations
                        /// @param self The stored oracle array
                        /// @param current The current next cardinality of the oracle array
                        /// @param next The proposed next cardinality which will be populated in the oracle array
                        /// @return next The next cardinality which will be populated in the oracle array
                        function grow(
                            Observation[65535] storage self,
                            uint16 current,
                            uint16 next
                        ) internal returns (uint16) {
                            require(current > 0, 'I');
                            // no-op if the passed next value isn't greater than the current next value
                            if (next <= current) return current;
                            // store in each slot to prevent fresh SSTOREs in swaps
                            // this data will not be used because the initialized boolean is still false
                            for (uint16 i = current; i < next; i++) self[i].blockTimestamp = 1;
                            return next;
                        }
                        /// @notice comparator for 32-bit timestamps
                        /// @dev safe for 0 or 1 overflows, a and b _must_ be chronologically before or equal to time
                        /// @param time A timestamp truncated to 32 bits
                        /// @param a A comparison timestamp from which to determine the relative position of `time`
                        /// @param b From which to determine the relative position of `time`
                        /// @return bool Whether `a` is chronologically <= `b`
                        function lte(
                            uint32 time,
                            uint32 a,
                            uint32 b
                        ) private pure returns (bool) {
                            // if there hasn't been overflow, no need to adjust
                            if (a <= time && b <= time) return a <= b;
                            uint256 aAdjusted = a > time ? a : a + 2**32;
                            uint256 bAdjusted = b > time ? b : b + 2**32;
                            return aAdjusted <= bAdjusted;
                        }
                        /// @notice Fetches the observations beforeOrAt and atOrAfter a target, i.e. where [beforeOrAt, atOrAfter] is satisfied.
                        /// The result may be the same observation, or adjacent observations.
                        /// @dev The answer must be contained in the array, used when the target is located within the stored observation
                        /// boundaries: older than the most recent observation and younger, or the same age as, the oldest observation
                        /// @param self The stored oracle array
                        /// @param time The current block.timestamp
                        /// @param target The timestamp at which the reserved observation should be for
                        /// @param index The index of the observation that was most recently written to the observations array
                        /// @param cardinality The number of populated elements in the oracle array
                        /// @return beforeOrAt The observation recorded before, or at, the target
                        /// @return atOrAfter The observation recorded at, or after, the target
                        function binarySearch(
                            Observation[65535] storage self,
                            uint32 time,
                            uint32 target,
                            uint16 index,
                            uint16 cardinality
                        ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
                            uint256 l = (index + 1) % cardinality; // oldest observation
                            uint256 r = l + cardinality - 1; // newest observation
                            uint256 i;
                            while (true) {
                                i = (l + r) / 2;
                                beforeOrAt = self[i % cardinality];
                                // we've landed on an uninitialized tick, keep searching higher (more recently)
                                if (!beforeOrAt.initialized) {
                                    l = i + 1;
                                    continue;
                                }
                                atOrAfter = self[(i + 1) % cardinality];
                                bool targetAtOrAfter = lte(time, beforeOrAt.blockTimestamp, target);
                                // check if we've found the answer!
                                if (targetAtOrAfter && lte(time, target, atOrAfter.blockTimestamp)) break;
                                if (!targetAtOrAfter) r = i - 1;
                                else l = i + 1;
                            }
                        }
                        /// @notice Fetches the observations beforeOrAt and atOrAfter a given target, i.e. where [beforeOrAt, atOrAfter] is satisfied
                        /// @dev Assumes there is at least 1 initialized observation.
                        /// Used by observeSingle() to compute the counterfactual accumulator values as of a given block timestamp.
                        /// @param self The stored oracle array
                        /// @param time The current block.timestamp
                        /// @param target The timestamp at which the reserved observation should be for
                        /// @param tick The active tick at the time of the returned or simulated observation
                        /// @param index The index of the observation that was most recently written to the observations array
                        /// @param liquidity The total pool liquidity at the time of the call
                        /// @param cardinality The number of populated elements in the oracle array
                        /// @return beforeOrAt The observation which occurred at, or before, the given timestamp
                        /// @return atOrAfter The observation which occurred at, or after, the given timestamp
                        function getSurroundingObservations(
                            Observation[65535] storage self,
                            uint32 time,
                            uint32 target,
                            int24 tick,
                            uint16 index,
                            uint128 liquidity,
                            uint16 cardinality
                        ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
                            // optimistically set before to the newest observation
                            beforeOrAt = self[index];
                            // if the target is chronologically at or after the newest observation, we can early return
                            if (lte(time, beforeOrAt.blockTimestamp, target)) {
                                if (beforeOrAt.blockTimestamp == target) {
                                    // if newest observation equals target, we're in the same block, so we can ignore atOrAfter
                                    return (beforeOrAt, atOrAfter);
                                } else {
                                    // otherwise, we need to transform
                                    return (beforeOrAt, transform(beforeOrAt, target, tick, liquidity));
                                }
                            }
                            // now, set before to the oldest observation
                            beforeOrAt = self[(index + 1) % cardinality];
                            if (!beforeOrAt.initialized) beforeOrAt = self[0];
                            // ensure that the target is chronologically at or after the oldest observation
                            require(lte(time, beforeOrAt.blockTimestamp, target), 'OLD');
                            // if we've reached this point, we have to binary search
                            return binarySearch(self, time, target, index, cardinality);
                        }
                        /// @dev Reverts if an observation at or before the desired observation timestamp does not exist.
                        /// 0 may be passed as `secondsAgo' to return the current cumulative values.
                        /// If called with a timestamp falling between two observations, returns the counterfactual accumulator values
                        /// at exactly the timestamp between the two observations.
                        /// @param self The stored oracle array
                        /// @param time The current block timestamp
                        /// @param secondsAgo The amount of time to look back, in seconds, at which point to return an observation
                        /// @param tick The current tick
                        /// @param index The index of the observation that was most recently written to the observations array
                        /// @param liquidity The current in-range pool liquidity
                        /// @param cardinality The number of populated elements in the oracle array
                        /// @return tickCumulative The tick * time elapsed since the pool was first initialized, as of `secondsAgo`
                        /// @return secondsPerLiquidityCumulativeX128 The time elapsed / max(1, liquidity) since the pool was first initialized, as of `secondsAgo`
                        function observeSingle(
                            Observation[65535] storage self,
                            uint32 time,
                            uint32 secondsAgo,
                            int24 tick,
                            uint16 index,
                            uint128 liquidity,
                            uint16 cardinality
                        ) internal view returns (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) {
                            if (secondsAgo == 0) {
                                Observation memory last = self[index];
                                if (last.blockTimestamp != time) last = transform(last, time, tick, liquidity);
                                return (last.tickCumulative, last.secondsPerLiquidityCumulativeX128);
                            }
                            uint32 target = time - secondsAgo;
                            (Observation memory beforeOrAt, Observation memory atOrAfter) =
                                getSurroundingObservations(self, time, target, tick, index, liquidity, cardinality);
                            if (target == beforeOrAt.blockTimestamp) {
                                // we're at the left boundary
                                return (beforeOrAt.tickCumulative, beforeOrAt.secondsPerLiquidityCumulativeX128);
                            } else if (target == atOrAfter.blockTimestamp) {
                                // we're at the right boundary
                                return (atOrAfter.tickCumulative, atOrAfter.secondsPerLiquidityCumulativeX128);
                            } else {
                                // we're in the middle
                                uint32 observationTimeDelta = atOrAfter.blockTimestamp - beforeOrAt.blockTimestamp;
                                uint32 targetDelta = target - beforeOrAt.blockTimestamp;
                                return (
                                    beforeOrAt.tickCumulative +
                                        ((atOrAfter.tickCumulative - beforeOrAt.tickCumulative) / observationTimeDelta) *
                                        targetDelta,
                                    beforeOrAt.secondsPerLiquidityCumulativeX128 +
                                        uint160(
                                            (uint256(
                                                atOrAfter.secondsPerLiquidityCumulativeX128 - beforeOrAt.secondsPerLiquidityCumulativeX128
                                            ) * targetDelta) / observationTimeDelta
                                        )
                                );
                            }
                        }
                        /// @notice Returns the accumulator values as of each time seconds ago from the given time in the array of `secondsAgos`
                        /// @dev Reverts if `secondsAgos` > oldest observation
                        /// @param self The stored oracle array
                        /// @param time The current block.timestamp
                        /// @param secondsAgos Each amount of time to look back, in seconds, at which point to return an observation
                        /// @param tick The current tick
                        /// @param index The index of the observation that was most recently written to the observations array
                        /// @param liquidity The current in-range pool liquidity
                        /// @param cardinality The number of populated elements in the oracle array
                        /// @return tickCumulatives The tick * time elapsed since the pool was first initialized, as of each `secondsAgo`
                        /// @return secondsPerLiquidityCumulativeX128s The cumulative seconds / max(1, liquidity) since the pool was first initialized, as of each `secondsAgo`
                        function observe(
                            Observation[65535] storage self,
                            uint32 time,
                            uint32[] memory secondsAgos,
                            int24 tick,
                            uint16 index,
                            uint128 liquidity,
                            uint16 cardinality
                        ) internal view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) {
                            require(cardinality > 0, 'I');
                            tickCumulatives = new int56[](secondsAgos.length);
                            secondsPerLiquidityCumulativeX128s = new uint160[](secondsAgos.length);
                            for (uint256 i = 0; i < secondsAgos.length; i++) {
                                (tickCumulatives[i], secondsPerLiquidityCumulativeX128s[i]) = observeSingle(
                                    self,
                                    time,
                                    secondsAgos[i],
                                    tick,
                                    index,
                                    liquidity,
                                    cardinality
                                );
                            }
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity >=0.4.0;
                    /// @title Contains 512-bit math functions
                    /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
                    /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
                    library FullMath {
                        /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
                        /// @param a The multiplicand
                        /// @param b The multiplier
                        /// @param denominator The divisor
                        /// @return result The 256-bit result
                        /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
                        function mulDiv(
                            uint256 a,
                            uint256 b,
                            uint256 denominator
                        ) internal pure returns (uint256 result) {
                            // 512-bit multiply [prod1 prod0] = a * b
                            // Compute the product mod 2**256 and mod 2**256 - 1
                            // then 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; // Least significant 256 bits of the product
                            uint256 prod1; // Most significant 256 bits of the product
                            assembly {
                                let mm := mulmod(a, b, not(0))
                                prod0 := mul(a, b)
                                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                            }
                            // Handle non-overflow cases, 256 by 256 division
                            if (prod1 == 0) {
                                require(denominator > 0);
                                assembly {
                                    result := div(prod0, denominator)
                                }
                                return result;
                            }
                            // Make sure the result is less than 2**256.
                            // Also prevents denominator == 0
                            require(denominator > prod1);
                            ///////////////////////////////////////////////
                            // 512 by 256 division.
                            ///////////////////////////////////////////////
                            // Make division exact by subtracting the remainder from [prod1 prod0]
                            // Compute remainder using mulmod
                            uint256 remainder;
                            assembly {
                                remainder := mulmod(a, b, denominator)
                            }
                            // Subtract 256 bit number from 512 bit number
                            assembly {
                                prod1 := sub(prod1, gt(remainder, prod0))
                                prod0 := sub(prod0, remainder)
                            }
                            // Factor powers of two out of denominator
                            // Compute largest power of two divisor of denominator.
                            // Always >= 1.
                            uint256 twos = -denominator & denominator;
                            // Divide denominator by power of two
                            assembly {
                                denominator := div(denominator, twos)
                            }
                            // Divide [prod1 prod0] by the factors of two
                            assembly {
                                prod0 := div(prod0, twos)
                            }
                            // Shift in bits from prod1 into prod0. For this we need
                            // to flip `twos` such that it is 2**256 / twos.
                            // If twos is zero, then it becomes one
                            assembly {
                                twos := add(div(sub(0, twos), twos), 1)
                            }
                            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
                            // correct for four bits. That is, denominator * inv = 1 mod 2**4
                            uint256 inv = (3 * denominator) ^ 2;
                            // Now use 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.
                            inv *= 2 - denominator * inv; // inverse mod 2**8
                            inv *= 2 - denominator * inv; // inverse mod 2**16
                            inv *= 2 - denominator * inv; // inverse mod 2**32
                            inv *= 2 - denominator * inv; // inverse mod 2**64
                            inv *= 2 - denominator * inv; // inverse mod 2**128
                            inv *= 2 - denominator * inv; // 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 precoditions 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 * inv;
                            return result;
                        }
                        /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
                        /// @param a The multiplicand
                        /// @param b The multiplier
                        /// @param denominator The divisor
                        /// @return result The 256-bit result
                        function mulDivRoundingUp(
                            uint256 a,
                            uint256 b,
                            uint256 denominator
                        ) internal pure returns (uint256 result) {
                            result = mulDiv(a, b, denominator);
                            if (mulmod(a, b, denominator) > 0) {
                                require(result < type(uint256).max);
                                result++;
                            }
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.4.0;
                    /// @title FixedPoint128
                    /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
                    library FixedPoint128 {
                        uint256 internal constant Q128 = 0x100000000000000000000000000000000;
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.6.0;
                    import '../interfaces/IERC20Minimal.sol';
                    /// @title TransferHelper
                    /// @notice Contains helper methods for interacting with ERC20 tokens that do not consistently return true/false
                    library TransferHelper {
                        /// @notice Transfers tokens from msg.sender to a recipient
                        /// @dev Calls transfer on token contract, errors with TF if transfer fails
                        /// @param token The contract address of the token which will be transferred
                        /// @param to The recipient of the transfer
                        /// @param value The value of the transfer
                        function safeTransfer(
                            address token,
                            address to,
                            uint256 value
                        ) internal {
                            (bool success, bytes memory data) =
                                token.call(abi.encodeWithSelector(IERC20Minimal.transfer.selector, to, value));
                            require(success && (data.length == 0 || abi.decode(data, (bool))), 'TF');
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.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 {
                        /// @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) {
                            uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
                            require(absTick <= uint256(MAX_TICK), '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) {
                            // second inequality must be < because the price can never reach the price at the max tick
                            require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, '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;
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title Math library for liquidity
                    library LiquidityMath {
                        /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
                        /// @param x The liquidity before change
                        /// @param y The delta by which liquidity should be changed
                        /// @return z The liquidity delta
                        function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
                            if (y < 0) {
                                require((z = x - uint128(-y)) < x, 'LS');
                            } else {
                                require((z = x + uint128(y)) >= x, 'LA');
                            }
                        }
                    }
                    // SPDX-License-Identifier: BUSL-1.1
                    pragma solidity >=0.5.0;
                    import './LowGasSafeMath.sol';
                    import './SafeCast.sol';
                    import './FullMath.sol';
                    import './UnsafeMath.sol';
                    import './FixedPoint96.sol';
                    /// @title Functions based on Q64.96 sqrt price and liquidity
                    /// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
                    library SqrtPriceMath {
                        using LowGasSafeMath for uint256;
                        using SafeCast for uint256;
                        /// @notice Gets the next sqrt price given a delta of token0
                        /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least
                        /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the
                        /// price less in order to not send too much output.
                        /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),
                        /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).
                        /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta
                        /// @param liquidity The amount of usable liquidity
                        /// @param amount How much of token0 to add or remove from virtual reserves
                        /// @param add Whether to add or remove the amount of token0
                        /// @return The price after adding or removing amount, depending on add
                        function getNextSqrtPriceFromAmount0RoundingUp(
                            uint160 sqrtPX96,
                            uint128 liquidity,
                            uint256 amount,
                            bool add
                        ) internal pure returns (uint160) {
                            // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price
                            if (amount == 0) return sqrtPX96;
                            uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
                            if (add) {
                                uint256 product;
                                if ((product = amount * sqrtPX96) / amount == sqrtPX96) {
                                    uint256 denominator = numerator1 + product;
                                    if (denominator >= numerator1)
                                        // always fits in 160 bits
                                        return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));
                                }
                                return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount)));
                            } else {
                                uint256 product;
                                // if the product overflows, we know the denominator underflows
                                // in addition, we must check that the denominator does not underflow
                                require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);
                                uint256 denominator = numerator1 - product;
                                return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
                            }
                        }
                        /// @notice Gets the next sqrt price given a delta of token1
                        /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least
                        /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the
                        /// price less in order to not send too much output.
                        /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity
                        /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta
                        /// @param liquidity The amount of usable liquidity
                        /// @param amount How much of token1 to add, or remove, from virtual reserves
                        /// @param add Whether to add, or remove, the amount of token1
                        /// @return The price after adding or removing `amount`
                        function getNextSqrtPriceFromAmount1RoundingDown(
                            uint160 sqrtPX96,
                            uint128 liquidity,
                            uint256 amount,
                            bool add
                        ) internal pure returns (uint160) {
                            // if we're adding (subtracting), rounding down requires rounding the quotient down (up)
                            // in both cases, avoid a mulDiv for most inputs
                            if (add) {
                                uint256 quotient =
                                    (
                                        amount <= type(uint160).max
                                            ? (amount << FixedPoint96.RESOLUTION) / liquidity
                                            : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)
                                    );
                                return uint256(sqrtPX96).add(quotient).toUint160();
                            } else {
                                uint256 quotient =
                                    (
                                        amount <= type(uint160).max
                                            ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)
                                            : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)
                                    );
                                require(sqrtPX96 > quotient);
                                // always fits 160 bits
                                return uint160(sqrtPX96 - quotient);
                            }
                        }
                        /// @notice Gets the next sqrt price given an input amount of token0 or token1
                        /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds
                        /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount
                        /// @param liquidity The amount of usable liquidity
                        /// @param amountIn How much of token0, or token1, is being swapped in
                        /// @param zeroForOne Whether the amount in is token0 or token1
                        /// @return sqrtQX96 The price after adding the input amount to token0 or token1
                        function getNextSqrtPriceFromInput(
                            uint160 sqrtPX96,
                            uint128 liquidity,
                            uint256 amountIn,
                            bool zeroForOne
                        ) internal pure returns (uint160 sqrtQX96) {
                            require(sqrtPX96 > 0);
                            require(liquidity > 0);
                            // round to make sure that we don't pass the target price
                            return
                                zeroForOne
                                    ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)
                                    : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
                        }
                        /// @notice Gets the next sqrt price given an output amount of token0 or token1
                        /// @dev Throws if price or liquidity are 0 or the next price is out of bounds
                        /// @param sqrtPX96 The starting price before accounting for the output amount
                        /// @param liquidity The amount of usable liquidity
                        /// @param amountOut How much of token0, or token1, is being swapped out
                        /// @param zeroForOne Whether the amount out is token0 or token1
                        /// @return sqrtQX96 The price after removing the output amount of token0 or token1
                        function getNextSqrtPriceFromOutput(
                            uint160 sqrtPX96,
                            uint128 liquidity,
                            uint256 amountOut,
                            bool zeroForOne
                        ) internal pure returns (uint160 sqrtQX96) {
                            require(sqrtPX96 > 0);
                            require(liquidity > 0);
                            // round to make sure that we pass the target price
                            return
                                zeroForOne
                                    ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)
                                    : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
                        }
                        /// @notice Gets the amount0 delta between two prices
                        /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),
                        /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
                        /// @param sqrtRatioAX96 A sqrt price
                        /// @param sqrtRatioBX96 Another sqrt price
                        /// @param liquidity The amount of usable liquidity
                        /// @param roundUp Whether to round the amount up or down
                        /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices
                        function getAmount0Delta(
                            uint160 sqrtRatioAX96,
                            uint160 sqrtRatioBX96,
                            uint128 liquidity,
                            bool roundUp
                        ) internal pure returns (uint256 amount0) {
                            if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
                            uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
                            uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;
                            require(sqrtRatioAX96 > 0);
                            return
                                roundUp
                                    ? UnsafeMath.divRoundingUp(
                                        FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),
                                        sqrtRatioAX96
                                    )
                                    : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;
                        }
                        /// @notice Gets the amount1 delta between two prices
                        /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
                        /// @param sqrtRatioAX96 A sqrt price
                        /// @param sqrtRatioBX96 Another sqrt price
                        /// @param liquidity The amount of usable liquidity
                        /// @param roundUp Whether to round the amount up, or down
                        /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices
                        function getAmount1Delta(
                            uint160 sqrtRatioAX96,
                            uint160 sqrtRatioBX96,
                            uint128 liquidity,
                            bool roundUp
                        ) internal pure returns (uint256 amount1) {
                            if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
                            return
                                roundUp
                                    ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)
                                    : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
                        }
                        /// @notice Helper that gets signed token0 delta
                        /// @param sqrtRatioAX96 A sqrt price
                        /// @param sqrtRatioBX96 Another sqrt price
                        /// @param liquidity The change in liquidity for which to compute the amount0 delta
                        /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices
                        function getAmount0Delta(
                            uint160 sqrtRatioAX96,
                            uint160 sqrtRatioBX96,
                            int128 liquidity
                        ) internal pure returns (int256 amount0) {
                            return
                                liquidity < 0
                                    ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
                                    : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
                        }
                        /// @notice Helper that gets signed token1 delta
                        /// @param sqrtRatioAX96 A sqrt price
                        /// @param sqrtRatioBX96 Another sqrt price
                        /// @param liquidity The change in liquidity for which to compute the amount1 delta
                        /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices
                        function getAmount1Delta(
                            uint160 sqrtRatioAX96,
                            uint160 sqrtRatioBX96,
                            int128 liquidity
                        ) internal pure returns (int256 amount1) {
                            return
                                liquidity < 0
                                    ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
                                    : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
                        }
                    }
                    // SPDX-License-Identifier: BUSL-1.1
                    pragma solidity >=0.5.0;
                    import './FullMath.sol';
                    import './SqrtPriceMath.sol';
                    /// @title Computes the result of a swap within ticks
                    /// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.
                    library SwapMath {
                        /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap
                        /// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive
                        /// @param sqrtRatioCurrentX96 The current sqrt price of the pool
                        /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred
                        /// @param liquidity The usable liquidity
                        /// @param amountRemaining How much input or output amount is remaining to be swapped in/out
                        /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip
                        /// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target
                        /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap
                        /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap
                        /// @return feeAmount The amount of input that will be taken as a fee
                        function computeSwapStep(
                            uint160 sqrtRatioCurrentX96,
                            uint160 sqrtRatioTargetX96,
                            uint128 liquidity,
                            int256 amountRemaining,
                            uint24 feePips
                        )
                            internal
                            pure
                            returns (
                                uint160 sqrtRatioNextX96,
                                uint256 amountIn,
                                uint256 amountOut,
                                uint256 feeAmount
                            )
                        {
                            bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96;
                            bool exactIn = amountRemaining >= 0;
                            if (exactIn) {
                                uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(amountRemaining), 1e6 - feePips, 1e6);
                                amountIn = zeroForOne
                                    ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true)
                                    : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);
                                if (amountRemainingLessFee >= amountIn) sqrtRatioNextX96 = sqrtRatioTargetX96;
                                else
                                    sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(
                                        sqrtRatioCurrentX96,
                                        liquidity,
                                        amountRemainingLessFee,
                                        zeroForOne
                                    );
                            } else {
                                amountOut = zeroForOne
                                    ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false)
                                    : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);
                                if (uint256(-amountRemaining) >= amountOut) sqrtRatioNextX96 = sqrtRatioTargetX96;
                                else
                                    sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(
                                        sqrtRatioCurrentX96,
                                        liquidity,
                                        uint256(-amountRemaining),
                                        zeroForOne
                                    );
                            }
                            bool max = sqrtRatioTargetX96 == sqrtRatioNextX96;
                            // get the input/output amounts
                            if (zeroForOne) {
                                amountIn = max && exactIn
                                    ? amountIn
                                    : SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true);
                                amountOut = max && !exactIn
                                    ? amountOut
                                    : SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false);
                            } else {
                                amountIn = max && exactIn
                                    ? amountIn
                                    : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true);
                                amountOut = max && !exactIn
                                    ? amountOut
                                    : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false);
                            }
                            // cap the output amount to not exceed the remaining output amount
                            if (!exactIn && amountOut > uint256(-amountRemaining)) {
                                amountOut = uint256(-amountRemaining);
                            }
                            if (exactIn && sqrtRatioNextX96 != sqrtRatioTargetX96) {
                                // we didn't reach the target, so take the remainder of the maximum input as fee
                                feeAmount = uint256(amountRemaining) - amountIn;
                            } else {
                                feeAmount = FullMath.mulDivRoundingUp(amountIn, feePips, 1e6 - feePips);
                            }
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title Minimal ERC20 interface for Uniswap
                    /// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
                    interface IERC20Minimal {
                        /// @notice Returns the balance of a token
                        /// @param account The account for which to look up the number of tokens it has, i.e. its balance
                        /// @return The number of tokens held by the account
                        function balanceOf(address account) external view returns (uint256);
                        /// @notice Transfers the amount of token from the `msg.sender` to the recipient
                        /// @param recipient The account that will receive the amount transferred
                        /// @param amount The number of tokens to send from the sender to the recipient
                        /// @return Returns true for a successful transfer, false for an unsuccessful transfer
                        function transfer(address recipient, uint256 amount) external returns (bool);
                        /// @notice Returns the current allowance given to a spender by an owner
                        /// @param owner The account of the token owner
                        /// @param spender The account of the token spender
                        /// @return The current allowance granted by `owner` to `spender`
                        function allowance(address owner, address spender) external view returns (uint256);
                        /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
                        /// @param spender The account which will be allowed to spend a given amount of the owners tokens
                        /// @param amount The amount of tokens allowed to be used by `spender`
                        /// @return Returns true for a successful approval, false for unsuccessful
                        function approve(address spender, uint256 amount) external returns (bool);
                        /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
                        /// @param sender The account from which the transfer will be initiated
                        /// @param recipient The recipient of the transfer
                        /// @param amount The amount of the transfer
                        /// @return Returns true for a successful transfer, false for unsuccessful
                        function transferFrom(
                            address sender,
                            address recipient,
                            uint256 amount
                        ) external returns (bool);
                        /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
                        /// @param from The account from which the tokens were sent, i.e. the balance decreased
                        /// @param to The account to which the tokens were sent, i.e. the balance increased
                        /// @param value The amount of tokens that were transferred
                        event Transfer(address indexed from, address indexed to, uint256 value);
                        /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
                        /// @param owner The account that approved spending of its tokens
                        /// @param spender The account for which the spending allowance was modified
                        /// @param value The new allowance from the owner to the spender
                        event Approval(address indexed owner, address indexed spender, uint256 value);
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title Callback for IUniswapV3PoolActions#mint
                    /// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface
                    interface IUniswapV3MintCallback {
                        /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
                        /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
                        /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
                        /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
                        /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
                        /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
                        function uniswapV3MintCallback(
                            uint256 amount0Owed,
                            uint256 amount1Owed,
                            bytes calldata data
                        ) external;
                    }
                    // 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;
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title Callback for IUniswapV3PoolActions#flash
                    /// @notice Any contract that calls IUniswapV3PoolActions#flash must implement this interface
                    interface IUniswapV3FlashCallback {
                        /// @notice Called to `msg.sender` after transferring to the recipient from IUniswapV3Pool#flash.
                        /// @dev In the implementation you must repay the pool the tokens sent by flash plus the computed fee amounts.
                        /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
                        /// @param fee0 The fee amount in token0 due to the pool by the end of the flash
                        /// @param fee1 The fee amount in token1 due to the pool by the end of the flash
                        /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#flash call
                        function uniswapV3FlashCallback(
                            uint256 fee0,
                            uint256 fee1,
                            bytes calldata data
                        ) external;
                    }
                    // 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);
                    }
                    // 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
                            );
                    }
                    // 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
                            );
                    }
                    // 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;
                    }
                    // 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);
                    }
                    // 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);
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title BitMath
                    /// @dev This library provides functionality for computing bit properties of an unsigned integer
                    library BitMath {
                        /// @notice Returns the index of the most significant bit of the number,
                        ///     where the least significant bit is at index 0 and the most significant bit is at index 255
                        /// @dev The function satisfies the property:
                        ///     x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)
                        /// @param x the value for which to compute the most significant bit, must be greater than 0
                        /// @return r the index of the most significant bit
                        function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
                            require(x > 0);
                            if (x >= 0x100000000000000000000000000000000) {
                                x >>= 128;
                                r += 128;
                            }
                            if (x >= 0x10000000000000000) {
                                x >>= 64;
                                r += 64;
                            }
                            if (x >= 0x100000000) {
                                x >>= 32;
                                r += 32;
                            }
                            if (x >= 0x10000) {
                                x >>= 16;
                                r += 16;
                            }
                            if (x >= 0x100) {
                                x >>= 8;
                                r += 8;
                            }
                            if (x >= 0x10) {
                                x >>= 4;
                                r += 4;
                            }
                            if (x >= 0x4) {
                                x >>= 2;
                                r += 2;
                            }
                            if (x >= 0x2) r += 1;
                        }
                        /// @notice Returns the index of the least significant bit of the number,
                        ///     where the least significant bit is at index 0 and the most significant bit is at index 255
                        /// @dev The function satisfies the property:
                        ///     (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)
                        /// @param x the value for which to compute the least significant bit, must be greater than 0
                        /// @return r the index of the least significant bit
                        function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
                            require(x > 0);
                            r = 255;
                            if (x & type(uint128).max > 0) {
                                r -= 128;
                            } else {
                                x >>= 128;
                            }
                            if (x & type(uint64).max > 0) {
                                r -= 64;
                            } else {
                                x >>= 64;
                            }
                            if (x & type(uint32).max > 0) {
                                r -= 32;
                            } else {
                                x >>= 32;
                            }
                            if (x & type(uint16).max > 0) {
                                r -= 16;
                            } else {
                                x >>= 16;
                            }
                            if (x & type(uint8).max > 0) {
                                r -= 8;
                            } else {
                                x >>= 8;
                            }
                            if (x & 0xf > 0) {
                                r -= 4;
                            } else {
                                x >>= 4;
                            }
                            if (x & 0x3 > 0) {
                                r -= 2;
                            } else {
                                x >>= 2;
                            }
                            if (x & 0x1 > 0) r -= 1;
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title Math functions that do not check inputs or outputs
                    /// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
                    library UnsafeMath {
                        /// @notice Returns ceil(x / y)
                        /// @dev division by 0 has unspecified behavior, and must be checked externally
                        /// @param x The dividend
                        /// @param y The divisor
                        /// @return z The quotient, ceil(x / y)
                        function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            assembly {
                                z := add(div(x, y), gt(mod(x, y), 0))
                            }
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.4.0;
                    /// @title FixedPoint96
                    /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
                    /// @dev Used in SqrtPriceMath.sol
                    library FixedPoint96 {
                        uint8 internal constant RESOLUTION = 96;
                        uint256 internal constant Q96 = 0x1000000000000000000000000;
                    }
                    

                    File 3 of 6: UniswapV3Pool
                    // SPDX-License-Identifier: BUSL-1.1
                    pragma solidity =0.7.6;
                    import './interfaces/IUniswapV3Pool.sol';
                    import './NoDelegateCall.sol';
                    import './libraries/LowGasSafeMath.sol';
                    import './libraries/SafeCast.sol';
                    import './libraries/Tick.sol';
                    import './libraries/TickBitmap.sol';
                    import './libraries/Position.sol';
                    import './libraries/Oracle.sol';
                    import './libraries/FullMath.sol';
                    import './libraries/FixedPoint128.sol';
                    import './libraries/TransferHelper.sol';
                    import './libraries/TickMath.sol';
                    import './libraries/LiquidityMath.sol';
                    import './libraries/SqrtPriceMath.sol';
                    import './libraries/SwapMath.sol';
                    import './interfaces/IUniswapV3PoolDeployer.sol';
                    import './interfaces/IUniswapV3Factory.sol';
                    import './interfaces/IERC20Minimal.sol';
                    import './interfaces/callback/IUniswapV3MintCallback.sol';
                    import './interfaces/callback/IUniswapV3SwapCallback.sol';
                    import './interfaces/callback/IUniswapV3FlashCallback.sol';
                    contract UniswapV3Pool is IUniswapV3Pool, NoDelegateCall {
                        using LowGasSafeMath for uint256;
                        using LowGasSafeMath for int256;
                        using SafeCast for uint256;
                        using SafeCast for int256;
                        using Tick for mapping(int24 => Tick.Info);
                        using TickBitmap for mapping(int16 => uint256);
                        using Position for mapping(bytes32 => Position.Info);
                        using Position for Position.Info;
                        using Oracle for Oracle.Observation[65535];
                        /// @inheritdoc IUniswapV3PoolImmutables
                        address public immutable override factory;
                        /// @inheritdoc IUniswapV3PoolImmutables
                        address public immutable override token0;
                        /// @inheritdoc IUniswapV3PoolImmutables
                        address public immutable override token1;
                        /// @inheritdoc IUniswapV3PoolImmutables
                        uint24 public immutable override fee;
                        /// @inheritdoc IUniswapV3PoolImmutables
                        int24 public immutable override tickSpacing;
                        /// @inheritdoc IUniswapV3PoolImmutables
                        uint128 public immutable override maxLiquidityPerTick;
                        struct Slot0 {
                            // the current price
                            uint160 sqrtPriceX96;
                            // the current tick
                            int24 tick;
                            // the most-recently updated index of the observations array
                            uint16 observationIndex;
                            // the current maximum number of observations that are being stored
                            uint16 observationCardinality;
                            // the next maximum number of observations to store, triggered in observations.write
                            uint16 observationCardinalityNext;
                            // the current protocol fee as a percentage of the swap fee taken on withdrawal
                            // represented as an integer denominator (1/x)%
                            uint8 feeProtocol;
                            // whether the pool is locked
                            bool unlocked;
                        }
                        /// @inheritdoc IUniswapV3PoolState
                        Slot0 public override slot0;
                        /// @inheritdoc IUniswapV3PoolState
                        uint256 public override feeGrowthGlobal0X128;
                        /// @inheritdoc IUniswapV3PoolState
                        uint256 public override feeGrowthGlobal1X128;
                        // accumulated protocol fees in token0/token1 units
                        struct ProtocolFees {
                            uint128 token0;
                            uint128 token1;
                        }
                        /// @inheritdoc IUniswapV3PoolState
                        ProtocolFees public override protocolFees;
                        /// @inheritdoc IUniswapV3PoolState
                        uint128 public override liquidity;
                        /// @inheritdoc IUniswapV3PoolState
                        mapping(int24 => Tick.Info) public override ticks;
                        /// @inheritdoc IUniswapV3PoolState
                        mapping(int16 => uint256) public override tickBitmap;
                        /// @inheritdoc IUniswapV3PoolState
                        mapping(bytes32 => Position.Info) public override positions;
                        /// @inheritdoc IUniswapV3PoolState
                        Oracle.Observation[65535] public override observations;
                        /// @dev Mutually exclusive reentrancy protection into the pool to/from a method. This method also prevents entrance
                        /// to a function before the pool is initialized. The reentrancy guard is required throughout the contract because
                        /// we use balance checks to determine the payment status of interactions such as mint, swap and flash.
                        modifier lock() {
                            require(slot0.unlocked, 'LOK');
                            slot0.unlocked = false;
                            _;
                            slot0.unlocked = true;
                        }
                        /// @dev Prevents calling a function from anyone except the address returned by IUniswapV3Factory#owner()
                        modifier onlyFactoryOwner() {
                            require(msg.sender == IUniswapV3Factory(factory).owner());
                            _;
                        }
                        constructor() {
                            int24 _tickSpacing;
                            (factory, token0, token1, fee, _tickSpacing) = IUniswapV3PoolDeployer(msg.sender).parameters();
                            tickSpacing = _tickSpacing;
                            maxLiquidityPerTick = Tick.tickSpacingToMaxLiquidityPerTick(_tickSpacing);
                        }
                        /// @dev Common checks for valid tick inputs.
                        function checkTicks(int24 tickLower, int24 tickUpper) private pure {
                            require(tickLower < tickUpper, 'TLU');
                            require(tickLower >= TickMath.MIN_TICK, 'TLM');
                            require(tickUpper <= TickMath.MAX_TICK, 'TUM');
                        }
                        /// @dev Returns the block timestamp truncated to 32 bits, i.e. mod 2**32. This method is overridden in tests.
                        function _blockTimestamp() internal view virtual returns (uint32) {
                            return uint32(block.timestamp); // truncation is desired
                        }
                        /// @dev Get the pool's balance of token0
                        /// @dev This function is gas optimized to avoid a redundant extcodesize check in addition to the returndatasize
                        /// check
                        function balance0() private view returns (uint256) {
                            (bool success, bytes memory data) =
                                token0.staticcall(abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this)));
                            require(success && data.length >= 32);
                            return abi.decode(data, (uint256));
                        }
                        /// @dev Get the pool's balance of token1
                        /// @dev This function is gas optimized to avoid a redundant extcodesize check in addition to the returndatasize
                        /// check
                        function balance1() private view returns (uint256) {
                            (bool success, bytes memory data) =
                                token1.staticcall(abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this)));
                            require(success && data.length >= 32);
                            return abi.decode(data, (uint256));
                        }
                        /// @inheritdoc IUniswapV3PoolDerivedState
                        function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
                            external
                            view
                            override
                            noDelegateCall
                            returns (
                                int56 tickCumulativeInside,
                                uint160 secondsPerLiquidityInsideX128,
                                uint32 secondsInside
                            )
                        {
                            checkTicks(tickLower, tickUpper);
                            int56 tickCumulativeLower;
                            int56 tickCumulativeUpper;
                            uint160 secondsPerLiquidityOutsideLowerX128;
                            uint160 secondsPerLiquidityOutsideUpperX128;
                            uint32 secondsOutsideLower;
                            uint32 secondsOutsideUpper;
                            {
                                Tick.Info storage lower = ticks[tickLower];
                                Tick.Info storage upper = ticks[tickUpper];
                                bool initializedLower;
                                (tickCumulativeLower, secondsPerLiquidityOutsideLowerX128, secondsOutsideLower, initializedLower) = (
                                    lower.tickCumulativeOutside,
                                    lower.secondsPerLiquidityOutsideX128,
                                    lower.secondsOutside,
                                    lower.initialized
                                );
                                require(initializedLower);
                                bool initializedUpper;
                                (tickCumulativeUpper, secondsPerLiquidityOutsideUpperX128, secondsOutsideUpper, initializedUpper) = (
                                    upper.tickCumulativeOutside,
                                    upper.secondsPerLiquidityOutsideX128,
                                    upper.secondsOutside,
                                    upper.initialized
                                );
                                require(initializedUpper);
                            }
                            Slot0 memory _slot0 = slot0;
                            if (_slot0.tick < tickLower) {
                                return (
                                    tickCumulativeLower - tickCumulativeUpper,
                                    secondsPerLiquidityOutsideLowerX128 - secondsPerLiquidityOutsideUpperX128,
                                    secondsOutsideLower - secondsOutsideUpper
                                );
                            } else if (_slot0.tick < tickUpper) {
                                uint32 time = _blockTimestamp();
                                (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) =
                                    observations.observeSingle(
                                        time,
                                        0,
                                        _slot0.tick,
                                        _slot0.observationIndex,
                                        liquidity,
                                        _slot0.observationCardinality
                                    );
                                return (
                                    tickCumulative - tickCumulativeLower - tickCumulativeUpper,
                                    secondsPerLiquidityCumulativeX128 -
                                        secondsPerLiquidityOutsideLowerX128 -
                                        secondsPerLiquidityOutsideUpperX128,
                                    time - secondsOutsideLower - secondsOutsideUpper
                                );
                            } else {
                                return (
                                    tickCumulativeUpper - tickCumulativeLower,
                                    secondsPerLiquidityOutsideUpperX128 - secondsPerLiquidityOutsideLowerX128,
                                    secondsOutsideUpper - secondsOutsideLower
                                );
                            }
                        }
                        /// @inheritdoc IUniswapV3PoolDerivedState
                        function observe(uint32[] calldata secondsAgos)
                            external
                            view
                            override
                            noDelegateCall
                            returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s)
                        {
                            return
                                observations.observe(
                                    _blockTimestamp(),
                                    secondsAgos,
                                    slot0.tick,
                                    slot0.observationIndex,
                                    liquidity,
                                    slot0.observationCardinality
                                );
                        }
                        /// @inheritdoc IUniswapV3PoolActions
                        function increaseObservationCardinalityNext(uint16 observationCardinalityNext)
                            external
                            override
                            lock
                            noDelegateCall
                        {
                            uint16 observationCardinalityNextOld = slot0.observationCardinalityNext; // for the event
                            uint16 observationCardinalityNextNew =
                                observations.grow(observationCardinalityNextOld, observationCardinalityNext);
                            slot0.observationCardinalityNext = observationCardinalityNextNew;
                            if (observationCardinalityNextOld != observationCardinalityNextNew)
                                emit IncreaseObservationCardinalityNext(observationCardinalityNextOld, observationCardinalityNextNew);
                        }
                        /// @inheritdoc IUniswapV3PoolActions
                        /// @dev not locked because it initializes unlocked
                        function initialize(uint160 sqrtPriceX96) external override {
                            require(slot0.sqrtPriceX96 == 0, 'AI');
                            int24 tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96);
                            (uint16 cardinality, uint16 cardinalityNext) = observations.initialize(_blockTimestamp());
                            slot0 = Slot0({
                                sqrtPriceX96: sqrtPriceX96,
                                tick: tick,
                                observationIndex: 0,
                                observationCardinality: cardinality,
                                observationCardinalityNext: cardinalityNext,
                                feeProtocol: 0,
                                unlocked: true
                            });
                            emit Initialize(sqrtPriceX96, tick);
                        }
                        struct ModifyPositionParams {
                            // the address that owns the position
                            address owner;
                            // the lower and upper tick of the position
                            int24 tickLower;
                            int24 tickUpper;
                            // any change in liquidity
                            int128 liquidityDelta;
                        }
                        /// @dev Effect some changes to a position
                        /// @param params the position details and the change to the position's liquidity to effect
                        /// @return position a storage pointer referencing the position with the given owner and tick range
                        /// @return amount0 the amount of token0 owed to the pool, negative if the pool should pay the recipient
                        /// @return amount1 the amount of token1 owed to the pool, negative if the pool should pay the recipient
                        function _modifyPosition(ModifyPositionParams memory params)
                            private
                            noDelegateCall
                            returns (
                                Position.Info storage position,
                                int256 amount0,
                                int256 amount1
                            )
                        {
                            checkTicks(params.tickLower, params.tickUpper);
                            Slot0 memory _slot0 = slot0; // SLOAD for gas optimization
                            position = _updatePosition(
                                params.owner,
                                params.tickLower,
                                params.tickUpper,
                                params.liquidityDelta,
                                _slot0.tick
                            );
                            if (params.liquidityDelta != 0) {
                                if (_slot0.tick < params.tickLower) {
                                    // current tick is below the passed range; liquidity can only become in range by crossing from left to
                                    // right, when we'll need _more_ token0 (it's becoming more valuable) so user must provide it
                                    amount0 = SqrtPriceMath.getAmount0Delta(
                                        TickMath.getSqrtRatioAtTick(params.tickLower),
                                        TickMath.getSqrtRatioAtTick(params.tickUpper),
                                        params.liquidityDelta
                                    );
                                } else if (_slot0.tick < params.tickUpper) {
                                    // current tick is inside the passed range
                                    uint128 liquidityBefore = liquidity; // SLOAD for gas optimization
                                    // write an oracle entry
                                    (slot0.observationIndex, slot0.observationCardinality) = observations.write(
                                        _slot0.observationIndex,
                                        _blockTimestamp(),
                                        _slot0.tick,
                                        liquidityBefore,
                                        _slot0.observationCardinality,
                                        _slot0.observationCardinalityNext
                                    );
                                    amount0 = SqrtPriceMath.getAmount0Delta(
                                        _slot0.sqrtPriceX96,
                                        TickMath.getSqrtRatioAtTick(params.tickUpper),
                                        params.liquidityDelta
                                    );
                                    amount1 = SqrtPriceMath.getAmount1Delta(
                                        TickMath.getSqrtRatioAtTick(params.tickLower),
                                        _slot0.sqrtPriceX96,
                                        params.liquidityDelta
                                    );
                                    liquidity = LiquidityMath.addDelta(liquidityBefore, params.liquidityDelta);
                                } else {
                                    // current tick is above the passed range; liquidity can only become in range by crossing from right to
                                    // left, when we'll need _more_ token1 (it's becoming more valuable) so user must provide it
                                    amount1 = SqrtPriceMath.getAmount1Delta(
                                        TickMath.getSqrtRatioAtTick(params.tickLower),
                                        TickMath.getSqrtRatioAtTick(params.tickUpper),
                                        params.liquidityDelta
                                    );
                                }
                            }
                        }
                        /// @dev Gets and updates a position with the given liquidity delta
                        /// @param owner the owner of the position
                        /// @param tickLower the lower tick of the position's tick range
                        /// @param tickUpper the upper tick of the position's tick range
                        /// @param tick the current tick, passed to avoid sloads
                        function _updatePosition(
                            address owner,
                            int24 tickLower,
                            int24 tickUpper,
                            int128 liquidityDelta,
                            int24 tick
                        ) private returns (Position.Info storage position) {
                            position = positions.get(owner, tickLower, tickUpper);
                            uint256 _feeGrowthGlobal0X128 = feeGrowthGlobal0X128; // SLOAD for gas optimization
                            uint256 _feeGrowthGlobal1X128 = feeGrowthGlobal1X128; // SLOAD for gas optimization
                            // if we need to update the ticks, do it
                            bool flippedLower;
                            bool flippedUpper;
                            if (liquidityDelta != 0) {
                                uint32 time = _blockTimestamp();
                                (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) =
                                    observations.observeSingle(
                                        time,
                                        0,
                                        slot0.tick,
                                        slot0.observationIndex,
                                        liquidity,
                                        slot0.observationCardinality
                                    );
                                flippedLower = ticks.update(
                                    tickLower,
                                    tick,
                                    liquidityDelta,
                                    _feeGrowthGlobal0X128,
                                    _feeGrowthGlobal1X128,
                                    secondsPerLiquidityCumulativeX128,
                                    tickCumulative,
                                    time,
                                    false,
                                    maxLiquidityPerTick
                                );
                                flippedUpper = ticks.update(
                                    tickUpper,
                                    tick,
                                    liquidityDelta,
                                    _feeGrowthGlobal0X128,
                                    _feeGrowthGlobal1X128,
                                    secondsPerLiquidityCumulativeX128,
                                    tickCumulative,
                                    time,
                                    true,
                                    maxLiquidityPerTick
                                );
                                if (flippedLower) {
                                    tickBitmap.flipTick(tickLower, tickSpacing);
                                }
                                if (flippedUpper) {
                                    tickBitmap.flipTick(tickUpper, tickSpacing);
                                }
                            }
                            (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) =
                                ticks.getFeeGrowthInside(tickLower, tickUpper, tick, _feeGrowthGlobal0X128, _feeGrowthGlobal1X128);
                            position.update(liquidityDelta, feeGrowthInside0X128, feeGrowthInside1X128);
                            // clear any tick data that is no longer needed
                            if (liquidityDelta < 0) {
                                if (flippedLower) {
                                    ticks.clear(tickLower);
                                }
                                if (flippedUpper) {
                                    ticks.clear(tickUpper);
                                }
                            }
                        }
                        /// @inheritdoc IUniswapV3PoolActions
                        /// @dev noDelegateCall is applied indirectly via _modifyPosition
                        function mint(
                            address recipient,
                            int24 tickLower,
                            int24 tickUpper,
                            uint128 amount,
                            bytes calldata data
                        ) external override lock returns (uint256 amount0, uint256 amount1) {
                            require(amount > 0);
                            (, int256 amount0Int, int256 amount1Int) =
                                _modifyPosition(
                                    ModifyPositionParams({
                                        owner: recipient,
                                        tickLower: tickLower,
                                        tickUpper: tickUpper,
                                        liquidityDelta: int256(amount).toInt128()
                                    })
                                );
                            amount0 = uint256(amount0Int);
                            amount1 = uint256(amount1Int);
                            uint256 balance0Before;
                            uint256 balance1Before;
                            if (amount0 > 0) balance0Before = balance0();
                            if (amount1 > 0) balance1Before = balance1();
                            IUniswapV3MintCallback(msg.sender).uniswapV3MintCallback(amount0, amount1, data);
                            if (amount0 > 0) require(balance0Before.add(amount0) <= balance0(), 'M0');
                            if (amount1 > 0) require(balance1Before.add(amount1) <= balance1(), 'M1');
                            emit Mint(msg.sender, recipient, tickLower, tickUpper, amount, amount0, amount1);
                        }
                        /// @inheritdoc IUniswapV3PoolActions
                        function collect(
                            address recipient,
                            int24 tickLower,
                            int24 tickUpper,
                            uint128 amount0Requested,
                            uint128 amount1Requested
                        ) external override lock returns (uint128 amount0, uint128 amount1) {
                            // we don't need to checkTicks here, because invalid positions will never have non-zero tokensOwed{0,1}
                            Position.Info storage position = positions.get(msg.sender, tickLower, tickUpper);
                            amount0 = amount0Requested > position.tokensOwed0 ? position.tokensOwed0 : amount0Requested;
                            amount1 = amount1Requested > position.tokensOwed1 ? position.tokensOwed1 : amount1Requested;
                            if (amount0 > 0) {
                                position.tokensOwed0 -= amount0;
                                TransferHelper.safeTransfer(token0, recipient, amount0);
                            }
                            if (amount1 > 0) {
                                position.tokensOwed1 -= amount1;
                                TransferHelper.safeTransfer(token1, recipient, amount1);
                            }
                            emit Collect(msg.sender, recipient, tickLower, tickUpper, amount0, amount1);
                        }
                        /// @inheritdoc IUniswapV3PoolActions
                        /// @dev noDelegateCall is applied indirectly via _modifyPosition
                        function burn(
                            int24 tickLower,
                            int24 tickUpper,
                            uint128 amount
                        ) external override lock returns (uint256 amount0, uint256 amount1) {
                            (Position.Info storage position, int256 amount0Int, int256 amount1Int) =
                                _modifyPosition(
                                    ModifyPositionParams({
                                        owner: msg.sender,
                                        tickLower: tickLower,
                                        tickUpper: tickUpper,
                                        liquidityDelta: -int256(amount).toInt128()
                                    })
                                );
                            amount0 = uint256(-amount0Int);
                            amount1 = uint256(-amount1Int);
                            if (amount0 > 0 || amount1 > 0) {
                                (position.tokensOwed0, position.tokensOwed1) = (
                                    position.tokensOwed0 + uint128(amount0),
                                    position.tokensOwed1 + uint128(amount1)
                                );
                            }
                            emit Burn(msg.sender, tickLower, tickUpper, amount, amount0, amount1);
                        }
                        struct SwapCache {
                            // the protocol fee for the input token
                            uint8 feeProtocol;
                            // liquidity at the beginning of the swap
                            uint128 liquidityStart;
                            // the timestamp of the current block
                            uint32 blockTimestamp;
                            // the current value of the tick accumulator, computed only if we cross an initialized tick
                            int56 tickCumulative;
                            // the current value of seconds per liquidity accumulator, computed only if we cross an initialized tick
                            uint160 secondsPerLiquidityCumulativeX128;
                            // whether we've computed and cached the above two accumulators
                            bool computedLatestObservation;
                        }
                        // the top level state of the swap, the results of which are recorded in storage at the end
                        struct SwapState {
                            // the amount remaining to be swapped in/out of the input/output asset
                            int256 amountSpecifiedRemaining;
                            // the amount already swapped out/in of the output/input asset
                            int256 amountCalculated;
                            // current sqrt(price)
                            uint160 sqrtPriceX96;
                            // the tick associated with the current price
                            int24 tick;
                            // the global fee growth of the input token
                            uint256 feeGrowthGlobalX128;
                            // amount of input token paid as protocol fee
                            uint128 protocolFee;
                            // the current liquidity in range
                            uint128 liquidity;
                        }
                        struct StepComputations {
                            // the price at the beginning of the step
                            uint160 sqrtPriceStartX96;
                            // the next tick to swap to from the current tick in the swap direction
                            int24 tickNext;
                            // whether tickNext is initialized or not
                            bool initialized;
                            // sqrt(price) for the next tick (1/0)
                            uint160 sqrtPriceNextX96;
                            // how much is being swapped in in this step
                            uint256 amountIn;
                            // how much is being swapped out
                            uint256 amountOut;
                            // how much fee is being paid in
                            uint256 feeAmount;
                        }
                        /// @inheritdoc IUniswapV3PoolActions
                        function swap(
                            address recipient,
                            bool zeroForOne,
                            int256 amountSpecified,
                            uint160 sqrtPriceLimitX96,
                            bytes calldata data
                        ) external override noDelegateCall returns (int256 amount0, int256 amount1) {
                            require(amountSpecified != 0, 'AS');
                            Slot0 memory slot0Start = slot0;
                            require(slot0Start.unlocked, 'LOK');
                            require(
                                zeroForOne
                                    ? sqrtPriceLimitX96 < slot0Start.sqrtPriceX96 && sqrtPriceLimitX96 > TickMath.MIN_SQRT_RATIO
                                    : sqrtPriceLimitX96 > slot0Start.sqrtPriceX96 && sqrtPriceLimitX96 < TickMath.MAX_SQRT_RATIO,
                                'SPL'
                            );
                            slot0.unlocked = false;
                            SwapCache memory cache =
                                SwapCache({
                                    liquidityStart: liquidity,
                                    blockTimestamp: _blockTimestamp(),
                                    feeProtocol: zeroForOne ? (slot0Start.feeProtocol % 16) : (slot0Start.feeProtocol >> 4),
                                    secondsPerLiquidityCumulativeX128: 0,
                                    tickCumulative: 0,
                                    computedLatestObservation: false
                                });
                            bool exactInput = amountSpecified > 0;
                            SwapState memory state =
                                SwapState({
                                    amountSpecifiedRemaining: amountSpecified,
                                    amountCalculated: 0,
                                    sqrtPriceX96: slot0Start.sqrtPriceX96,
                                    tick: slot0Start.tick,
                                    feeGrowthGlobalX128: zeroForOne ? feeGrowthGlobal0X128 : feeGrowthGlobal1X128,
                                    protocolFee: 0,
                                    liquidity: cache.liquidityStart
                                });
                            // continue swapping as long as we haven't used the entire input/output and haven't reached the price limit
                            while (state.amountSpecifiedRemaining != 0 && state.sqrtPriceX96 != sqrtPriceLimitX96) {
                                StepComputations memory step;
                                step.sqrtPriceStartX96 = state.sqrtPriceX96;
                                (step.tickNext, step.initialized) = tickBitmap.nextInitializedTickWithinOneWord(
                                    state.tick,
                                    tickSpacing,
                                    zeroForOne
                                );
                                // ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds
                                if (step.tickNext < TickMath.MIN_TICK) {
                                    step.tickNext = TickMath.MIN_TICK;
                                } else if (step.tickNext > TickMath.MAX_TICK) {
                                    step.tickNext = TickMath.MAX_TICK;
                                }
                                // get the price for the next tick
                                step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);
                                // compute values to swap to the target tick, price limit, or point where input/output amount is exhausted
                                (state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath.computeSwapStep(
                                    state.sqrtPriceX96,
                                    (zeroForOne ? step.sqrtPriceNextX96 < sqrtPriceLimitX96 : step.sqrtPriceNextX96 > sqrtPriceLimitX96)
                                        ? sqrtPriceLimitX96
                                        : step.sqrtPriceNextX96,
                                    state.liquidity,
                                    state.amountSpecifiedRemaining,
                                    fee
                                );
                                if (exactInput) {
                                    state.amountSpecifiedRemaining -= (step.amountIn + step.feeAmount).toInt256();
                                    state.amountCalculated = state.amountCalculated.sub(step.amountOut.toInt256());
                                } else {
                                    state.amountSpecifiedRemaining += step.amountOut.toInt256();
                                    state.amountCalculated = state.amountCalculated.add((step.amountIn + step.feeAmount).toInt256());
                                }
                                // if the protocol fee is on, calculate how much is owed, decrement feeAmount, and increment protocolFee
                                if (cache.feeProtocol > 0) {
                                    uint256 delta = step.feeAmount / cache.feeProtocol;
                                    step.feeAmount -= delta;
                                    state.protocolFee += uint128(delta);
                                }
                                // update global fee tracker
                                if (state.liquidity > 0)
                                    state.feeGrowthGlobalX128 += FullMath.mulDiv(step.feeAmount, FixedPoint128.Q128, state.liquidity);
                                // shift tick if we reached the next price
                                if (state.sqrtPriceX96 == step.sqrtPriceNextX96) {
                                    // if the tick is initialized, run the tick transition
                                    if (step.initialized) {
                                        // check for the placeholder value, which we replace with the actual value the first time the swap
                                        // crosses an initialized tick
                                        if (!cache.computedLatestObservation) {
                                            (cache.tickCumulative, cache.secondsPerLiquidityCumulativeX128) = observations.observeSingle(
                                                cache.blockTimestamp,
                                                0,
                                                slot0Start.tick,
                                                slot0Start.observationIndex,
                                                cache.liquidityStart,
                                                slot0Start.observationCardinality
                                            );
                                            cache.computedLatestObservation = true;
                                        }
                                        int128 liquidityNet =
                                            ticks.cross(
                                                step.tickNext,
                                                (zeroForOne ? state.feeGrowthGlobalX128 : feeGrowthGlobal0X128),
                                                (zeroForOne ? feeGrowthGlobal1X128 : state.feeGrowthGlobalX128),
                                                cache.secondsPerLiquidityCumulativeX128,
                                                cache.tickCumulative,
                                                cache.blockTimestamp
                                            );
                                        // if we're moving leftward, we interpret liquidityNet as the opposite sign
                                        // safe because liquidityNet cannot be type(int128).min
                                        if (zeroForOne) liquidityNet = -liquidityNet;
                                        state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);
                                    }
                                    state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;
                                } else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) {
                                    // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved
                                    state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);
                                }
                            }
                            // update tick and write an oracle entry if the tick change
                            if (state.tick != slot0Start.tick) {
                                (uint16 observationIndex, uint16 observationCardinality) =
                                    observations.write(
                                        slot0Start.observationIndex,
                                        cache.blockTimestamp,
                                        slot0Start.tick,
                                        cache.liquidityStart,
                                        slot0Start.observationCardinality,
                                        slot0Start.observationCardinalityNext
                                    );
                                (slot0.sqrtPriceX96, slot0.tick, slot0.observationIndex, slot0.observationCardinality) = (
                                    state.sqrtPriceX96,
                                    state.tick,
                                    observationIndex,
                                    observationCardinality
                                );
                            } else {
                                // otherwise just update the price
                                slot0.sqrtPriceX96 = state.sqrtPriceX96;
                            }
                            // update liquidity if it changed
                            if (cache.liquidityStart != state.liquidity) liquidity = state.liquidity;
                            // update fee growth global and, if necessary, protocol fees
                            // overflow is acceptable, protocol has to withdraw before it hits type(uint128).max fees
                            if (zeroForOne) {
                                feeGrowthGlobal0X128 = state.feeGrowthGlobalX128;
                                if (state.protocolFee > 0) protocolFees.token0 += state.protocolFee;
                            } else {
                                feeGrowthGlobal1X128 = state.feeGrowthGlobalX128;
                                if (state.protocolFee > 0) protocolFees.token1 += state.protocolFee;
                            }
                            (amount0, amount1) = zeroForOne == exactInput
                                ? (amountSpecified - state.amountSpecifiedRemaining, state.amountCalculated)
                                : (state.amountCalculated, amountSpecified - state.amountSpecifiedRemaining);
                            // do the transfers and collect payment
                            if (zeroForOne) {
                                if (amount1 < 0) TransferHelper.safeTransfer(token1, recipient, uint256(-amount1));
                                uint256 balance0Before = balance0();
                                IUniswapV3SwapCallback(msg.sender).uniswapV3SwapCallback(amount0, amount1, data);
                                require(balance0Before.add(uint256(amount0)) <= balance0(), 'IIA');
                            } else {
                                if (amount0 < 0) TransferHelper.safeTransfer(token0, recipient, uint256(-amount0));
                                uint256 balance1Before = balance1();
                                IUniswapV3SwapCallback(msg.sender).uniswapV3SwapCallback(amount0, amount1, data);
                                require(balance1Before.add(uint256(amount1)) <= balance1(), 'IIA');
                            }
                            emit Swap(msg.sender, recipient, amount0, amount1, state.sqrtPriceX96, state.liquidity, state.tick);
                            slot0.unlocked = true;
                        }
                        /// @inheritdoc IUniswapV3PoolActions
                        function flash(
                            address recipient,
                            uint256 amount0,
                            uint256 amount1,
                            bytes calldata data
                        ) external override lock noDelegateCall {
                            uint128 _liquidity = liquidity;
                            require(_liquidity > 0, 'L');
                            uint256 fee0 = FullMath.mulDivRoundingUp(amount0, fee, 1e6);
                            uint256 fee1 = FullMath.mulDivRoundingUp(amount1, fee, 1e6);
                            uint256 balance0Before = balance0();
                            uint256 balance1Before = balance1();
                            if (amount0 > 0) TransferHelper.safeTransfer(token0, recipient, amount0);
                            if (amount1 > 0) TransferHelper.safeTransfer(token1, recipient, amount1);
                            IUniswapV3FlashCallback(msg.sender).uniswapV3FlashCallback(fee0, fee1, data);
                            uint256 balance0After = balance0();
                            uint256 balance1After = balance1();
                            require(balance0Before.add(fee0) <= balance0After, 'F0');
                            require(balance1Before.add(fee1) <= balance1After, 'F1');
                            // sub is safe because we know balanceAfter is gt balanceBefore by at least fee
                            uint256 paid0 = balance0After - balance0Before;
                            uint256 paid1 = balance1After - balance1Before;
                            if (paid0 > 0) {
                                uint8 feeProtocol0 = slot0.feeProtocol % 16;
                                uint256 fees0 = feeProtocol0 == 0 ? 0 : paid0 / feeProtocol0;
                                if (uint128(fees0) > 0) protocolFees.token0 += uint128(fees0);
                                feeGrowthGlobal0X128 += FullMath.mulDiv(paid0 - fees0, FixedPoint128.Q128, _liquidity);
                            }
                            if (paid1 > 0) {
                                uint8 feeProtocol1 = slot0.feeProtocol >> 4;
                                uint256 fees1 = feeProtocol1 == 0 ? 0 : paid1 / feeProtocol1;
                                if (uint128(fees1) > 0) protocolFees.token1 += uint128(fees1);
                                feeGrowthGlobal1X128 += FullMath.mulDiv(paid1 - fees1, FixedPoint128.Q128, _liquidity);
                            }
                            emit Flash(msg.sender, recipient, amount0, amount1, paid0, paid1);
                        }
                        /// @inheritdoc IUniswapV3PoolOwnerActions
                        function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external override lock onlyFactoryOwner {
                            require(
                                (feeProtocol0 == 0 || (feeProtocol0 >= 4 && feeProtocol0 <= 10)) &&
                                    (feeProtocol1 == 0 || (feeProtocol1 >= 4 && feeProtocol1 <= 10))
                            );
                            uint8 feeProtocolOld = slot0.feeProtocol;
                            slot0.feeProtocol = feeProtocol0 + (feeProtocol1 << 4);
                            emit SetFeeProtocol(feeProtocolOld % 16, feeProtocolOld >> 4, feeProtocol0, feeProtocol1);
                        }
                        /// @inheritdoc IUniswapV3PoolOwnerActions
                        function collectProtocol(
                            address recipient,
                            uint128 amount0Requested,
                            uint128 amount1Requested
                        ) external override lock onlyFactoryOwner returns (uint128 amount0, uint128 amount1) {
                            amount0 = amount0Requested > protocolFees.token0 ? protocolFees.token0 : amount0Requested;
                            amount1 = amount1Requested > protocolFees.token1 ? protocolFees.token1 : amount1Requested;
                            if (amount0 > 0) {
                                if (amount0 == protocolFees.token0) amount0--; // ensure that the slot is not cleared, for gas savings
                                protocolFees.token0 -= amount0;
                                TransferHelper.safeTransfer(token0, recipient, amount0);
                            }
                            if (amount1 > 0) {
                                if (amount1 == protocolFees.token1) amount1--; // ensure that the slot is not cleared, for gas savings
                                protocolFees.token1 -= amount1;
                                TransferHelper.safeTransfer(token1, recipient, amount1);
                            }
                            emit CollectProtocol(msg.sender, recipient, amount0, amount1);
                        }
                    }
                    // 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
                    {
                    }
                    // SPDX-License-Identifier: BUSL-1.1
                    pragma solidity =0.7.6;
                    /// @title Prevents delegatecall to a contract
                    /// @notice Base contract that provides a modifier for preventing delegatecall to methods in a child contract
                    abstract contract NoDelegateCall {
                        /// @dev The original address of this contract
                        address private immutable original;
                        constructor() {
                            // Immutables are computed in the init code of the contract, and then inlined into the deployed bytecode.
                            // In other words, this variable won't change when it's checked at runtime.
                            original = address(this);
                        }
                        /// @dev Private method is used instead of inlining into modifier because modifiers are copied into each method,
                        ///     and the use of immutable means the address bytes are copied in every place the modifier is used.
                        function checkNotDelegateCall() private view {
                            require(address(this) == original);
                        }
                        /// @notice Prevents delegatecall into the modified method
                        modifier noDelegateCall() {
                            checkNotDelegateCall();
                            _;
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.7.0;
                    /// @title Optimized overflow and underflow safe math operations
                    /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost
                    library LowGasSafeMath {
                        /// @notice Returns x + y, reverts if sum overflows uint256
                        /// @param x The augend
                        /// @param y The addend
                        /// @return z The sum of x and y
                        function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            require((z = x + y) >= x);
                        }
                        /// @notice Returns x - y, reverts if underflows
                        /// @param x The minuend
                        /// @param y The subtrahend
                        /// @return z The difference of x and y
                        function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            require((z = x - y) <= x);
                        }
                        /// @notice Returns x * y, reverts if overflows
                        /// @param x The multiplicand
                        /// @param y The multiplier
                        /// @return z The product of x and y
                        function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            require(x == 0 || (z = x * y) / x == y);
                        }
                        /// @notice Returns x + y, reverts if overflows or underflows
                        /// @param x The augend
                        /// @param y The addend
                        /// @return z The sum of x and y
                        function add(int256 x, int256 y) internal pure returns (int256 z) {
                            require((z = x + y) >= x == (y >= 0));
                        }
                        /// @notice Returns x - y, reverts if overflows or underflows
                        /// @param x The minuend
                        /// @param y The subtrahend
                        /// @return z The difference of x and y
                        function sub(int256 x, int256 y) internal pure returns (int256 z) {
                            require((z = x - y) <= x == (y >= 0));
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title Safe casting methods
                    /// @notice Contains methods for safely casting between types
                    library SafeCast {
                        /// @notice Cast a uint256 to a uint160, revert on overflow
                        /// @param y The uint256 to be downcasted
                        /// @return z The downcasted integer, now type uint160
                        function toUint160(uint256 y) internal pure returns (uint160 z) {
                            require((z = uint160(y)) == y);
                        }
                        /// @notice Cast a int256 to a int128, revert on overflow or underflow
                        /// @param y The int256 to be downcasted
                        /// @return z The downcasted integer, now type int128
                        function toInt128(int256 y) internal pure returns (int128 z) {
                            require((z = int128(y)) == y);
                        }
                        /// @notice Cast a uint256 to a int256, revert on overflow
                        /// @param y The uint256 to be casted
                        /// @return z The casted integer, now type int256
                        function toInt256(uint256 y) internal pure returns (int256 z) {
                            require(y < 2**255);
                            z = int256(y);
                        }
                    }
                    // SPDX-License-Identifier: BUSL-1.1
                    pragma solidity >=0.5.0;
                    import './LowGasSafeMath.sol';
                    import './SafeCast.sol';
                    import './TickMath.sol';
                    import './LiquidityMath.sol';
                    /// @title Tick
                    /// @notice Contains functions for managing tick processes and relevant calculations
                    library Tick {
                        using LowGasSafeMath for int256;
                        using SafeCast for int256;
                        // info stored for each initialized individual tick
                        struct Info {
                            // the total position liquidity that references this tick
                            uint128 liquidityGross;
                            // amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left),
                            int128 liquidityNet;
                            // fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
                            // only has relative meaning, not absolute — the value depends on when the tick is initialized
                            uint256 feeGrowthOutside0X128;
                            uint256 feeGrowthOutside1X128;
                            // the cumulative tick value on the other side of the tick
                            int56 tickCumulativeOutside;
                            // the seconds per unit of liquidity on the _other_ side of this tick (relative to the current tick)
                            // only has relative meaning, not absolute — the value depends on when the tick is initialized
                            uint160 secondsPerLiquidityOutsideX128;
                            // the seconds spent on the other side of the tick (relative to the current tick)
                            // only has relative meaning, not absolute — the value depends on when the tick is initialized
                            uint32 secondsOutside;
                            // true iff the tick is initialized, i.e. the value is exactly equivalent to the expression liquidityGross != 0
                            // these 8 bits are set to prevent fresh sstores when crossing newly initialized ticks
                            bool initialized;
                        }
                        /// @notice Derives max liquidity per tick from given tick spacing
                        /// @dev Executed within the pool constructor
                        /// @param tickSpacing The amount of required tick separation, realized in multiples of `tickSpacing`
                        ///     e.g., a tickSpacing of 3 requires ticks to be initialized every 3rd tick i.e., ..., -6, -3, 0, 3, 6, ...
                        /// @return The max liquidity per tick
                        function tickSpacingToMaxLiquidityPerTick(int24 tickSpacing) internal pure returns (uint128) {
                            int24 minTick = (TickMath.MIN_TICK / tickSpacing) * tickSpacing;
                            int24 maxTick = (TickMath.MAX_TICK / tickSpacing) * tickSpacing;
                            uint24 numTicks = uint24((maxTick - minTick) / tickSpacing) + 1;
                            return type(uint128).max / numTicks;
                        }
                        /// @notice Retrieves fee growth data
                        /// @param self The mapping containing all tick information for initialized ticks
                        /// @param tickLower The lower tick boundary of the position
                        /// @param tickUpper The upper tick boundary of the position
                        /// @param tickCurrent The current tick
                        /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0
                        /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1
                        /// @return feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries
                        /// @return feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries
                        function getFeeGrowthInside(
                            mapping(int24 => Tick.Info) storage self,
                            int24 tickLower,
                            int24 tickUpper,
                            int24 tickCurrent,
                            uint256 feeGrowthGlobal0X128,
                            uint256 feeGrowthGlobal1X128
                        ) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) {
                            Info storage lower = self[tickLower];
                            Info storage upper = self[tickUpper];
                            // calculate fee growth below
                            uint256 feeGrowthBelow0X128;
                            uint256 feeGrowthBelow1X128;
                            if (tickCurrent >= tickLower) {
                                feeGrowthBelow0X128 = lower.feeGrowthOutside0X128;
                                feeGrowthBelow1X128 = lower.feeGrowthOutside1X128;
                            } else {
                                feeGrowthBelow0X128 = feeGrowthGlobal0X128 - lower.feeGrowthOutside0X128;
                                feeGrowthBelow1X128 = feeGrowthGlobal1X128 - lower.feeGrowthOutside1X128;
                            }
                            // calculate fee growth above
                            uint256 feeGrowthAbove0X128;
                            uint256 feeGrowthAbove1X128;
                            if (tickCurrent < tickUpper) {
                                feeGrowthAbove0X128 = upper.feeGrowthOutside0X128;
                                feeGrowthAbove1X128 = upper.feeGrowthOutside1X128;
                            } else {
                                feeGrowthAbove0X128 = feeGrowthGlobal0X128 - upper.feeGrowthOutside0X128;
                                feeGrowthAbove1X128 = feeGrowthGlobal1X128 - upper.feeGrowthOutside1X128;
                            }
                            feeGrowthInside0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128;
                            feeGrowthInside1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128;
                        }
                        /// @notice Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa
                        /// @param self The mapping containing all tick information for initialized ticks
                        /// @param tick The tick that will be updated
                        /// @param tickCurrent The current tick
                        /// @param liquidityDelta A new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left)
                        /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0
                        /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1
                        /// @param secondsPerLiquidityCumulativeX128 The all-time seconds per max(1, liquidity) of the pool
                        /// @param time The current block timestamp cast to a uint32
                        /// @param upper true for updating a position's upper tick, or false for updating a position's lower tick
                        /// @param maxLiquidity The maximum liquidity allocation for a single tick
                        /// @return flipped Whether the tick was flipped from initialized to uninitialized, or vice versa
                        function update(
                            mapping(int24 => Tick.Info) storage self,
                            int24 tick,
                            int24 tickCurrent,
                            int128 liquidityDelta,
                            uint256 feeGrowthGlobal0X128,
                            uint256 feeGrowthGlobal1X128,
                            uint160 secondsPerLiquidityCumulativeX128,
                            int56 tickCumulative,
                            uint32 time,
                            bool upper,
                            uint128 maxLiquidity
                        ) internal returns (bool flipped) {
                            Tick.Info storage info = self[tick];
                            uint128 liquidityGrossBefore = info.liquidityGross;
                            uint128 liquidityGrossAfter = LiquidityMath.addDelta(liquidityGrossBefore, liquidityDelta);
                            require(liquidityGrossAfter <= maxLiquidity, 'LO');
                            flipped = (liquidityGrossAfter == 0) != (liquidityGrossBefore == 0);
                            if (liquidityGrossBefore == 0) {
                                // by convention, we assume that all growth before a tick was initialized happened _below_ the tick
                                if (tick <= tickCurrent) {
                                    info.feeGrowthOutside0X128 = feeGrowthGlobal0X128;
                                    info.feeGrowthOutside1X128 = feeGrowthGlobal1X128;
                                    info.secondsPerLiquidityOutsideX128 = secondsPerLiquidityCumulativeX128;
                                    info.tickCumulativeOutside = tickCumulative;
                                    info.secondsOutside = time;
                                }
                                info.initialized = true;
                            }
                            info.liquidityGross = liquidityGrossAfter;
                            // when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed)
                            info.liquidityNet = upper
                                ? int256(info.liquidityNet).sub(liquidityDelta).toInt128()
                                : int256(info.liquidityNet).add(liquidityDelta).toInt128();
                        }
                        /// @notice Clears tick data
                        /// @param self The mapping containing all initialized tick information for initialized ticks
                        /// @param tick The tick that will be cleared
                        function clear(mapping(int24 => Tick.Info) storage self, int24 tick) internal {
                            delete self[tick];
                        }
                        /// @notice Transitions to next tick as needed by price movement
                        /// @param self The mapping containing all tick information for initialized ticks
                        /// @param tick The destination tick of the transition
                        /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0
                        /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1
                        /// @param secondsPerLiquidityCumulativeX128 The current seconds per liquidity
                        /// @param time The current block.timestamp
                        /// @return liquidityNet The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left)
                        function cross(
                            mapping(int24 => Tick.Info) storage self,
                            int24 tick,
                            uint256 feeGrowthGlobal0X128,
                            uint256 feeGrowthGlobal1X128,
                            uint160 secondsPerLiquidityCumulativeX128,
                            int56 tickCumulative,
                            uint32 time
                        ) internal returns (int128 liquidityNet) {
                            Tick.Info storage info = self[tick];
                            info.feeGrowthOutside0X128 = feeGrowthGlobal0X128 - info.feeGrowthOutside0X128;
                            info.feeGrowthOutside1X128 = feeGrowthGlobal1X128 - info.feeGrowthOutside1X128;
                            info.secondsPerLiquidityOutsideX128 = secondsPerLiquidityCumulativeX128 - info.secondsPerLiquidityOutsideX128;
                            info.tickCumulativeOutside = tickCumulative - info.tickCumulativeOutside;
                            info.secondsOutside = time - info.secondsOutside;
                            liquidityNet = info.liquidityNet;
                        }
                    }
                    // SPDX-License-Identifier: BUSL-1.1
                    pragma solidity >=0.5.0;
                    import './BitMath.sol';
                    /// @title Packed tick initialized state library
                    /// @notice Stores a packed mapping of tick index to its initialized state
                    /// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.
                    library TickBitmap {
                        /// @notice Computes the position in the mapping where the initialized bit for a tick lives
                        /// @param tick The tick for which to compute the position
                        /// @return wordPos The key in the mapping containing the word in which the bit is stored
                        /// @return bitPos The bit position in the word where the flag is stored
                        function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) {
                            wordPos = int16(tick >> 8);
                            bitPos = uint8(tick % 256);
                        }
                        /// @notice Flips the initialized state for a given tick from false to true, or vice versa
                        /// @param self The mapping in which to flip the tick
                        /// @param tick The tick to flip
                        /// @param tickSpacing The spacing between usable ticks
                        function flipTick(
                            mapping(int16 => uint256) storage self,
                            int24 tick,
                            int24 tickSpacing
                        ) internal {
                            require(tick % tickSpacing == 0); // ensure that the tick is spaced
                            (int16 wordPos, uint8 bitPos) = position(tick / tickSpacing);
                            uint256 mask = 1 << bitPos;
                            self[wordPos] ^= mask;
                        }
                        /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either
                        /// to the left (less than or equal to) or right (greater than) of the given tick
                        /// @param self The mapping in which to compute the next initialized tick
                        /// @param tick The starting tick
                        /// @param tickSpacing The spacing between usable ticks
                        /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)
                        /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick
                        /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks
                        function nextInitializedTickWithinOneWord(
                            mapping(int16 => uint256) storage self,
                            int24 tick,
                            int24 tickSpacing,
                            bool lte
                        ) internal view returns (int24 next, bool initialized) {
                            int24 compressed = tick / tickSpacing;
                            if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity
                            if (lte) {
                                (int16 wordPos, uint8 bitPos) = position(compressed);
                                // all the 1s at or to the right of the current bitPos
                                uint256 mask = (1 << bitPos) - 1 + (1 << bitPos);
                                uint256 masked = self[wordPos] & mask;
                                // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word
                                initialized = masked != 0;
                                // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
                                next = initialized
                                    ? (compressed - int24(bitPos - BitMath.mostSignificantBit(masked))) * tickSpacing
                                    : (compressed - int24(bitPos)) * tickSpacing;
                            } else {
                                // start from the word of the next tick, since the current tick state doesn't matter
                                (int16 wordPos, uint8 bitPos) = position(compressed + 1);
                                // all the 1s at or to the left of the bitPos
                                uint256 mask = ~((1 << bitPos) - 1);
                                uint256 masked = self[wordPos] & mask;
                                // if there are no initialized ticks to the left of the current tick, return leftmost in the word
                                initialized = masked != 0;
                                // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
                                next = initialized
                                    ? (compressed + 1 + int24(BitMath.leastSignificantBit(masked) - bitPos)) * tickSpacing
                                    : (compressed + 1 + int24(type(uint8).max - bitPos)) * tickSpacing;
                            }
                        }
                    }
                    // SPDX-License-Identifier: BUSL-1.1
                    pragma solidity >=0.5.0;
                    import './FullMath.sol';
                    import './FixedPoint128.sol';
                    import './LiquidityMath.sol';
                    /// @title Position
                    /// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary
                    /// @dev Positions store additional state for tracking fees owed to the position
                    library Position {
                        // info stored for each user's position
                        struct Info {
                            // the amount of liquidity owned by this position
                            uint128 liquidity;
                            // fee growth per unit of liquidity as of the last update to liquidity or fees owed
                            uint256 feeGrowthInside0LastX128;
                            uint256 feeGrowthInside1LastX128;
                            // the fees owed to the position owner in token0/token1
                            uint128 tokensOwed0;
                            uint128 tokensOwed1;
                        }
                        /// @notice Returns the Info struct of a position, given an owner and position boundaries
                        /// @param self The mapping containing all user positions
                        /// @param owner The address of the position owner
                        /// @param tickLower The lower tick boundary of the position
                        /// @param tickUpper The upper tick boundary of the position
                        /// @return position The position info struct of the given owners' position
                        function get(
                            mapping(bytes32 => Info) storage self,
                            address owner,
                            int24 tickLower,
                            int24 tickUpper
                        ) internal view returns (Position.Info storage position) {
                            position = self[keccak256(abi.encodePacked(owner, tickLower, tickUpper))];
                        }
                        /// @notice Credits accumulated fees to a user's position
                        /// @param self The individual position to update
                        /// @param liquidityDelta The change in pool liquidity as a result of the position update
                        /// @param feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries
                        /// @param feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries
                        function update(
                            Info storage self,
                            int128 liquidityDelta,
                            uint256 feeGrowthInside0X128,
                            uint256 feeGrowthInside1X128
                        ) internal {
                            Info memory _self = self;
                            uint128 liquidityNext;
                            if (liquidityDelta == 0) {
                                require(_self.liquidity > 0, 'NP'); // disallow pokes for 0 liquidity positions
                                liquidityNext = _self.liquidity;
                            } else {
                                liquidityNext = LiquidityMath.addDelta(_self.liquidity, liquidityDelta);
                            }
                            // calculate accumulated fees
                            uint128 tokensOwed0 =
                                uint128(
                                    FullMath.mulDiv(
                                        feeGrowthInside0X128 - _self.feeGrowthInside0LastX128,
                                        _self.liquidity,
                                        FixedPoint128.Q128
                                    )
                                );
                            uint128 tokensOwed1 =
                                uint128(
                                    FullMath.mulDiv(
                                        feeGrowthInside1X128 - _self.feeGrowthInside1LastX128,
                                        _self.liquidity,
                                        FixedPoint128.Q128
                                    )
                                );
                            // update the position
                            if (liquidityDelta != 0) self.liquidity = liquidityNext;
                            self.feeGrowthInside0LastX128 = feeGrowthInside0X128;
                            self.feeGrowthInside1LastX128 = feeGrowthInside1X128;
                            if (tokensOwed0 > 0 || tokensOwed1 > 0) {
                                // overflow is acceptable, have to withdraw before you hit type(uint128).max fees
                                self.tokensOwed0 += tokensOwed0;
                                self.tokensOwed1 += tokensOwed1;
                            }
                        }
                    }
                    // SPDX-License-Identifier: BUSL-1.1
                    pragma solidity >=0.5.0;
                    /// @title Oracle
                    /// @notice Provides price and liquidity data useful for a wide variety of system designs
                    /// @dev Instances of stored oracle data, "observations", are collected in the oracle array
                    /// Every pool is initialized with an oracle array length of 1. Anyone can pay the SSTOREs to increase the
                    /// maximum length of the oracle array. New slots will be added when the array is fully populated.
                    /// Observations are overwritten when the full length of the oracle array is populated.
                    /// The most recent observation is available, independent of the length of the oracle array, by passing 0 to observe()
                    library Oracle {
                        struct Observation {
                            // the block timestamp of the observation
                            uint32 blockTimestamp;
                            // the tick accumulator, i.e. tick * time elapsed since the pool was first initialized
                            int56 tickCumulative;
                            // the seconds per liquidity, i.e. seconds elapsed / max(1, liquidity) since the pool was first initialized
                            uint160 secondsPerLiquidityCumulativeX128;
                            // whether or not the observation is initialized
                            bool initialized;
                        }
                        /// @notice Transforms a previous observation into a new observation, given the passage of time and the current tick and liquidity values
                        /// @dev blockTimestamp _must_ be chronologically equal to or greater than last.blockTimestamp, safe for 0 or 1 overflows
                        /// @param last The specified observation to be transformed
                        /// @param blockTimestamp The timestamp of the new observation
                        /// @param tick The active tick at the time of the new observation
                        /// @param liquidity The total in-range liquidity at the time of the new observation
                        /// @return Observation The newly populated observation
                        function transform(
                            Observation memory last,
                            uint32 blockTimestamp,
                            int24 tick,
                            uint128 liquidity
                        ) private pure returns (Observation memory) {
                            uint32 delta = blockTimestamp - last.blockTimestamp;
                            return
                                Observation({
                                    blockTimestamp: blockTimestamp,
                                    tickCumulative: last.tickCumulative + int56(tick) * delta,
                                    secondsPerLiquidityCumulativeX128: last.secondsPerLiquidityCumulativeX128 +
                                        ((uint160(delta) << 128) / (liquidity > 0 ? liquidity : 1)),
                                    initialized: true
                                });
                        }
                        /// @notice Initialize the oracle array by writing the first slot. Called once for the lifecycle of the observations array
                        /// @param self The stored oracle array
                        /// @param time The time of the oracle initialization, via block.timestamp truncated to uint32
                        /// @return cardinality The number of populated elements in the oracle array
                        /// @return cardinalityNext The new length of the oracle array, independent of population
                        function initialize(Observation[65535] storage self, uint32 time)
                            internal
                            returns (uint16 cardinality, uint16 cardinalityNext)
                        {
                            self[0] = Observation({
                                blockTimestamp: time,
                                tickCumulative: 0,
                                secondsPerLiquidityCumulativeX128: 0,
                                initialized: true
                            });
                            return (1, 1);
                        }
                        /// @notice Writes an oracle observation to the array
                        /// @dev Writable at most once per block. Index represents the most recently written element. cardinality and index must be tracked externally.
                        /// If the index is at the end of the allowable array length (according to cardinality), and the next cardinality
                        /// is greater than the current one, cardinality may be increased. This restriction is created to preserve ordering.
                        /// @param self The stored oracle array
                        /// @param index The index of the observation that was most recently written to the observations array
                        /// @param blockTimestamp The timestamp of the new observation
                        /// @param tick The active tick at the time of the new observation
                        /// @param liquidity The total in-range liquidity at the time of the new observation
                        /// @param cardinality The number of populated elements in the oracle array
                        /// @param cardinalityNext The new length of the oracle array, independent of population
                        /// @return indexUpdated The new index of the most recently written element in the oracle array
                        /// @return cardinalityUpdated The new cardinality of the oracle array
                        function write(
                            Observation[65535] storage self,
                            uint16 index,
                            uint32 blockTimestamp,
                            int24 tick,
                            uint128 liquidity,
                            uint16 cardinality,
                            uint16 cardinalityNext
                        ) internal returns (uint16 indexUpdated, uint16 cardinalityUpdated) {
                            Observation memory last = self[index];
                            // early return if we've already written an observation this block
                            if (last.blockTimestamp == blockTimestamp) return (index, cardinality);
                            // if the conditions are right, we can bump the cardinality
                            if (cardinalityNext > cardinality && index == (cardinality - 1)) {
                                cardinalityUpdated = cardinalityNext;
                            } else {
                                cardinalityUpdated = cardinality;
                            }
                            indexUpdated = (index + 1) % cardinalityUpdated;
                            self[indexUpdated] = transform(last, blockTimestamp, tick, liquidity);
                        }
                        /// @notice Prepares the oracle array to store up to `next` observations
                        /// @param self The stored oracle array
                        /// @param current The current next cardinality of the oracle array
                        /// @param next The proposed next cardinality which will be populated in the oracle array
                        /// @return next The next cardinality which will be populated in the oracle array
                        function grow(
                            Observation[65535] storage self,
                            uint16 current,
                            uint16 next
                        ) internal returns (uint16) {
                            require(current > 0, 'I');
                            // no-op if the passed next value isn't greater than the current next value
                            if (next <= current) return current;
                            // store in each slot to prevent fresh SSTOREs in swaps
                            // this data will not be used because the initialized boolean is still false
                            for (uint16 i = current; i < next; i++) self[i].blockTimestamp = 1;
                            return next;
                        }
                        /// @notice comparator for 32-bit timestamps
                        /// @dev safe for 0 or 1 overflows, a and b _must_ be chronologically before or equal to time
                        /// @param time A timestamp truncated to 32 bits
                        /// @param a A comparison timestamp from which to determine the relative position of `time`
                        /// @param b From which to determine the relative position of `time`
                        /// @return bool Whether `a` is chronologically <= `b`
                        function lte(
                            uint32 time,
                            uint32 a,
                            uint32 b
                        ) private pure returns (bool) {
                            // if there hasn't been overflow, no need to adjust
                            if (a <= time && b <= time) return a <= b;
                            uint256 aAdjusted = a > time ? a : a + 2**32;
                            uint256 bAdjusted = b > time ? b : b + 2**32;
                            return aAdjusted <= bAdjusted;
                        }
                        /// @notice Fetches the observations beforeOrAt and atOrAfter a target, i.e. where [beforeOrAt, atOrAfter] is satisfied.
                        /// The result may be the same observation, or adjacent observations.
                        /// @dev The answer must be contained in the array, used when the target is located within the stored observation
                        /// boundaries: older than the most recent observation and younger, or the same age as, the oldest observation
                        /// @param self The stored oracle array
                        /// @param time The current block.timestamp
                        /// @param target The timestamp at which the reserved observation should be for
                        /// @param index The index of the observation that was most recently written to the observations array
                        /// @param cardinality The number of populated elements in the oracle array
                        /// @return beforeOrAt The observation recorded before, or at, the target
                        /// @return atOrAfter The observation recorded at, or after, the target
                        function binarySearch(
                            Observation[65535] storage self,
                            uint32 time,
                            uint32 target,
                            uint16 index,
                            uint16 cardinality
                        ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
                            uint256 l = (index + 1) % cardinality; // oldest observation
                            uint256 r = l + cardinality - 1; // newest observation
                            uint256 i;
                            while (true) {
                                i = (l + r) / 2;
                                beforeOrAt = self[i % cardinality];
                                // we've landed on an uninitialized tick, keep searching higher (more recently)
                                if (!beforeOrAt.initialized) {
                                    l = i + 1;
                                    continue;
                                }
                                atOrAfter = self[(i + 1) % cardinality];
                                bool targetAtOrAfter = lte(time, beforeOrAt.blockTimestamp, target);
                                // check if we've found the answer!
                                if (targetAtOrAfter && lte(time, target, atOrAfter.blockTimestamp)) break;
                                if (!targetAtOrAfter) r = i - 1;
                                else l = i + 1;
                            }
                        }
                        /// @notice Fetches the observations beforeOrAt and atOrAfter a given target, i.e. where [beforeOrAt, atOrAfter] is satisfied
                        /// @dev Assumes there is at least 1 initialized observation.
                        /// Used by observeSingle() to compute the counterfactual accumulator values as of a given block timestamp.
                        /// @param self The stored oracle array
                        /// @param time The current block.timestamp
                        /// @param target The timestamp at which the reserved observation should be for
                        /// @param tick The active tick at the time of the returned or simulated observation
                        /// @param index The index of the observation that was most recently written to the observations array
                        /// @param liquidity The total pool liquidity at the time of the call
                        /// @param cardinality The number of populated elements in the oracle array
                        /// @return beforeOrAt The observation which occurred at, or before, the given timestamp
                        /// @return atOrAfter The observation which occurred at, or after, the given timestamp
                        function getSurroundingObservations(
                            Observation[65535] storage self,
                            uint32 time,
                            uint32 target,
                            int24 tick,
                            uint16 index,
                            uint128 liquidity,
                            uint16 cardinality
                        ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
                            // optimistically set before to the newest observation
                            beforeOrAt = self[index];
                            // if the target is chronologically at or after the newest observation, we can early return
                            if (lte(time, beforeOrAt.blockTimestamp, target)) {
                                if (beforeOrAt.blockTimestamp == target) {
                                    // if newest observation equals target, we're in the same block, so we can ignore atOrAfter
                                    return (beforeOrAt, atOrAfter);
                                } else {
                                    // otherwise, we need to transform
                                    return (beforeOrAt, transform(beforeOrAt, target, tick, liquidity));
                                }
                            }
                            // now, set before to the oldest observation
                            beforeOrAt = self[(index + 1) % cardinality];
                            if (!beforeOrAt.initialized) beforeOrAt = self[0];
                            // ensure that the target is chronologically at or after the oldest observation
                            require(lte(time, beforeOrAt.blockTimestamp, target), 'OLD');
                            // if we've reached this point, we have to binary search
                            return binarySearch(self, time, target, index, cardinality);
                        }
                        /// @dev Reverts if an observation at or before the desired observation timestamp does not exist.
                        /// 0 may be passed as `secondsAgo' to return the current cumulative values.
                        /// If called with a timestamp falling between two observations, returns the counterfactual accumulator values
                        /// at exactly the timestamp between the two observations.
                        /// @param self The stored oracle array
                        /// @param time The current block timestamp
                        /// @param secondsAgo The amount of time to look back, in seconds, at which point to return an observation
                        /// @param tick The current tick
                        /// @param index The index of the observation that was most recently written to the observations array
                        /// @param liquidity The current in-range pool liquidity
                        /// @param cardinality The number of populated elements in the oracle array
                        /// @return tickCumulative The tick * time elapsed since the pool was first initialized, as of `secondsAgo`
                        /// @return secondsPerLiquidityCumulativeX128 The time elapsed / max(1, liquidity) since the pool was first initialized, as of `secondsAgo`
                        function observeSingle(
                            Observation[65535] storage self,
                            uint32 time,
                            uint32 secondsAgo,
                            int24 tick,
                            uint16 index,
                            uint128 liquidity,
                            uint16 cardinality
                        ) internal view returns (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) {
                            if (secondsAgo == 0) {
                                Observation memory last = self[index];
                                if (last.blockTimestamp != time) last = transform(last, time, tick, liquidity);
                                return (last.tickCumulative, last.secondsPerLiquidityCumulativeX128);
                            }
                            uint32 target = time - secondsAgo;
                            (Observation memory beforeOrAt, Observation memory atOrAfter) =
                                getSurroundingObservations(self, time, target, tick, index, liquidity, cardinality);
                            if (target == beforeOrAt.blockTimestamp) {
                                // we're at the left boundary
                                return (beforeOrAt.tickCumulative, beforeOrAt.secondsPerLiquidityCumulativeX128);
                            } else if (target == atOrAfter.blockTimestamp) {
                                // we're at the right boundary
                                return (atOrAfter.tickCumulative, atOrAfter.secondsPerLiquidityCumulativeX128);
                            } else {
                                // we're in the middle
                                uint32 observationTimeDelta = atOrAfter.blockTimestamp - beforeOrAt.blockTimestamp;
                                uint32 targetDelta = target - beforeOrAt.blockTimestamp;
                                return (
                                    beforeOrAt.tickCumulative +
                                        ((atOrAfter.tickCumulative - beforeOrAt.tickCumulative) / observationTimeDelta) *
                                        targetDelta,
                                    beforeOrAt.secondsPerLiquidityCumulativeX128 +
                                        uint160(
                                            (uint256(
                                                atOrAfter.secondsPerLiquidityCumulativeX128 - beforeOrAt.secondsPerLiquidityCumulativeX128
                                            ) * targetDelta) / observationTimeDelta
                                        )
                                );
                            }
                        }
                        /// @notice Returns the accumulator values as of each time seconds ago from the given time in the array of `secondsAgos`
                        /// @dev Reverts if `secondsAgos` > oldest observation
                        /// @param self The stored oracle array
                        /// @param time The current block.timestamp
                        /// @param secondsAgos Each amount of time to look back, in seconds, at which point to return an observation
                        /// @param tick The current tick
                        /// @param index The index of the observation that was most recently written to the observations array
                        /// @param liquidity The current in-range pool liquidity
                        /// @param cardinality The number of populated elements in the oracle array
                        /// @return tickCumulatives The tick * time elapsed since the pool was first initialized, as of each `secondsAgo`
                        /// @return secondsPerLiquidityCumulativeX128s The cumulative seconds / max(1, liquidity) since the pool was first initialized, as of each `secondsAgo`
                        function observe(
                            Observation[65535] storage self,
                            uint32 time,
                            uint32[] memory secondsAgos,
                            int24 tick,
                            uint16 index,
                            uint128 liquidity,
                            uint16 cardinality
                        ) internal view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) {
                            require(cardinality > 0, 'I');
                            tickCumulatives = new int56[](secondsAgos.length);
                            secondsPerLiquidityCumulativeX128s = new uint160[](secondsAgos.length);
                            for (uint256 i = 0; i < secondsAgos.length; i++) {
                                (tickCumulatives[i], secondsPerLiquidityCumulativeX128s[i]) = observeSingle(
                                    self,
                                    time,
                                    secondsAgos[i],
                                    tick,
                                    index,
                                    liquidity,
                                    cardinality
                                );
                            }
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity >=0.4.0;
                    /// @title Contains 512-bit math functions
                    /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
                    /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
                    library FullMath {
                        /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
                        /// @param a The multiplicand
                        /// @param b The multiplier
                        /// @param denominator The divisor
                        /// @return result The 256-bit result
                        /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
                        function mulDiv(
                            uint256 a,
                            uint256 b,
                            uint256 denominator
                        ) internal pure returns (uint256 result) {
                            // 512-bit multiply [prod1 prod0] = a * b
                            // Compute the product mod 2**256 and mod 2**256 - 1
                            // then 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; // Least significant 256 bits of the product
                            uint256 prod1; // Most significant 256 bits of the product
                            assembly {
                                let mm := mulmod(a, b, not(0))
                                prod0 := mul(a, b)
                                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                            }
                            // Handle non-overflow cases, 256 by 256 division
                            if (prod1 == 0) {
                                require(denominator > 0);
                                assembly {
                                    result := div(prod0, denominator)
                                }
                                return result;
                            }
                            // Make sure the result is less than 2**256.
                            // Also prevents denominator == 0
                            require(denominator > prod1);
                            ///////////////////////////////////////////////
                            // 512 by 256 division.
                            ///////////////////////////////////////////////
                            // Make division exact by subtracting the remainder from [prod1 prod0]
                            // Compute remainder using mulmod
                            uint256 remainder;
                            assembly {
                                remainder := mulmod(a, b, denominator)
                            }
                            // Subtract 256 bit number from 512 bit number
                            assembly {
                                prod1 := sub(prod1, gt(remainder, prod0))
                                prod0 := sub(prod0, remainder)
                            }
                            // Factor powers of two out of denominator
                            // Compute largest power of two divisor of denominator.
                            // Always >= 1.
                            uint256 twos = -denominator & denominator;
                            // Divide denominator by power of two
                            assembly {
                                denominator := div(denominator, twos)
                            }
                            // Divide [prod1 prod0] by the factors of two
                            assembly {
                                prod0 := div(prod0, twos)
                            }
                            // Shift in bits from prod1 into prod0. For this we need
                            // to flip `twos` such that it is 2**256 / twos.
                            // If twos is zero, then it becomes one
                            assembly {
                                twos := add(div(sub(0, twos), twos), 1)
                            }
                            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
                            // correct for four bits. That is, denominator * inv = 1 mod 2**4
                            uint256 inv = (3 * denominator) ^ 2;
                            // Now use 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.
                            inv *= 2 - denominator * inv; // inverse mod 2**8
                            inv *= 2 - denominator * inv; // inverse mod 2**16
                            inv *= 2 - denominator * inv; // inverse mod 2**32
                            inv *= 2 - denominator * inv; // inverse mod 2**64
                            inv *= 2 - denominator * inv; // inverse mod 2**128
                            inv *= 2 - denominator * inv; // 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 precoditions 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 * inv;
                            return result;
                        }
                        /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
                        /// @param a The multiplicand
                        /// @param b The multiplier
                        /// @param denominator The divisor
                        /// @return result The 256-bit result
                        function mulDivRoundingUp(
                            uint256 a,
                            uint256 b,
                            uint256 denominator
                        ) internal pure returns (uint256 result) {
                            result = mulDiv(a, b, denominator);
                            if (mulmod(a, b, denominator) > 0) {
                                require(result < type(uint256).max);
                                result++;
                            }
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.4.0;
                    /// @title FixedPoint128
                    /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
                    library FixedPoint128 {
                        uint256 internal constant Q128 = 0x100000000000000000000000000000000;
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.6.0;
                    import '../interfaces/IERC20Minimal.sol';
                    /// @title TransferHelper
                    /// @notice Contains helper methods for interacting with ERC20 tokens that do not consistently return true/false
                    library TransferHelper {
                        /// @notice Transfers tokens from msg.sender to a recipient
                        /// @dev Calls transfer on token contract, errors with TF if transfer fails
                        /// @param token The contract address of the token which will be transferred
                        /// @param to The recipient of the transfer
                        /// @param value The value of the transfer
                        function safeTransfer(
                            address token,
                            address to,
                            uint256 value
                        ) internal {
                            (bool success, bytes memory data) =
                                token.call(abi.encodeWithSelector(IERC20Minimal.transfer.selector, to, value));
                            require(success && (data.length == 0 || abi.decode(data, (bool))), 'TF');
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.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 {
                        /// @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) {
                            uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
                            require(absTick <= uint256(MAX_TICK), '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) {
                            // second inequality must be < because the price can never reach the price at the max tick
                            require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, '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;
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title Math library for liquidity
                    library LiquidityMath {
                        /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
                        /// @param x The liquidity before change
                        /// @param y The delta by which liquidity should be changed
                        /// @return z The liquidity delta
                        function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
                            if (y < 0) {
                                require((z = x - uint128(-y)) < x, 'LS');
                            } else {
                                require((z = x + uint128(y)) >= x, 'LA');
                            }
                        }
                    }
                    // SPDX-License-Identifier: BUSL-1.1
                    pragma solidity >=0.5.0;
                    import './LowGasSafeMath.sol';
                    import './SafeCast.sol';
                    import './FullMath.sol';
                    import './UnsafeMath.sol';
                    import './FixedPoint96.sol';
                    /// @title Functions based on Q64.96 sqrt price and liquidity
                    /// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
                    library SqrtPriceMath {
                        using LowGasSafeMath for uint256;
                        using SafeCast for uint256;
                        /// @notice Gets the next sqrt price given a delta of token0
                        /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least
                        /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the
                        /// price less in order to not send too much output.
                        /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),
                        /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).
                        /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta
                        /// @param liquidity The amount of usable liquidity
                        /// @param amount How much of token0 to add or remove from virtual reserves
                        /// @param add Whether to add or remove the amount of token0
                        /// @return The price after adding or removing amount, depending on add
                        function getNextSqrtPriceFromAmount0RoundingUp(
                            uint160 sqrtPX96,
                            uint128 liquidity,
                            uint256 amount,
                            bool add
                        ) internal pure returns (uint160) {
                            // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price
                            if (amount == 0) return sqrtPX96;
                            uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
                            if (add) {
                                uint256 product;
                                if ((product = amount * sqrtPX96) / amount == sqrtPX96) {
                                    uint256 denominator = numerator1 + product;
                                    if (denominator >= numerator1)
                                        // always fits in 160 bits
                                        return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));
                                }
                                return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount)));
                            } else {
                                uint256 product;
                                // if the product overflows, we know the denominator underflows
                                // in addition, we must check that the denominator does not underflow
                                require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);
                                uint256 denominator = numerator1 - product;
                                return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
                            }
                        }
                        /// @notice Gets the next sqrt price given a delta of token1
                        /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least
                        /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the
                        /// price less in order to not send too much output.
                        /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity
                        /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta
                        /// @param liquidity The amount of usable liquidity
                        /// @param amount How much of token1 to add, or remove, from virtual reserves
                        /// @param add Whether to add, or remove, the amount of token1
                        /// @return The price after adding or removing `amount`
                        function getNextSqrtPriceFromAmount1RoundingDown(
                            uint160 sqrtPX96,
                            uint128 liquidity,
                            uint256 amount,
                            bool add
                        ) internal pure returns (uint160) {
                            // if we're adding (subtracting), rounding down requires rounding the quotient down (up)
                            // in both cases, avoid a mulDiv for most inputs
                            if (add) {
                                uint256 quotient =
                                    (
                                        amount <= type(uint160).max
                                            ? (amount << FixedPoint96.RESOLUTION) / liquidity
                                            : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)
                                    );
                                return uint256(sqrtPX96).add(quotient).toUint160();
                            } else {
                                uint256 quotient =
                                    (
                                        amount <= type(uint160).max
                                            ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)
                                            : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)
                                    );
                                require(sqrtPX96 > quotient);
                                // always fits 160 bits
                                return uint160(sqrtPX96 - quotient);
                            }
                        }
                        /// @notice Gets the next sqrt price given an input amount of token0 or token1
                        /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds
                        /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount
                        /// @param liquidity The amount of usable liquidity
                        /// @param amountIn How much of token0, or token1, is being swapped in
                        /// @param zeroForOne Whether the amount in is token0 or token1
                        /// @return sqrtQX96 The price after adding the input amount to token0 or token1
                        function getNextSqrtPriceFromInput(
                            uint160 sqrtPX96,
                            uint128 liquidity,
                            uint256 amountIn,
                            bool zeroForOne
                        ) internal pure returns (uint160 sqrtQX96) {
                            require(sqrtPX96 > 0);
                            require(liquidity > 0);
                            // round to make sure that we don't pass the target price
                            return
                                zeroForOne
                                    ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)
                                    : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
                        }
                        /// @notice Gets the next sqrt price given an output amount of token0 or token1
                        /// @dev Throws if price or liquidity are 0 or the next price is out of bounds
                        /// @param sqrtPX96 The starting price before accounting for the output amount
                        /// @param liquidity The amount of usable liquidity
                        /// @param amountOut How much of token0, or token1, is being swapped out
                        /// @param zeroForOne Whether the amount out is token0 or token1
                        /// @return sqrtQX96 The price after removing the output amount of token0 or token1
                        function getNextSqrtPriceFromOutput(
                            uint160 sqrtPX96,
                            uint128 liquidity,
                            uint256 amountOut,
                            bool zeroForOne
                        ) internal pure returns (uint160 sqrtQX96) {
                            require(sqrtPX96 > 0);
                            require(liquidity > 0);
                            // round to make sure that we pass the target price
                            return
                                zeroForOne
                                    ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)
                                    : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
                        }
                        /// @notice Gets the amount0 delta between two prices
                        /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),
                        /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
                        /// @param sqrtRatioAX96 A sqrt price
                        /// @param sqrtRatioBX96 Another sqrt price
                        /// @param liquidity The amount of usable liquidity
                        /// @param roundUp Whether to round the amount up or down
                        /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices
                        function getAmount0Delta(
                            uint160 sqrtRatioAX96,
                            uint160 sqrtRatioBX96,
                            uint128 liquidity,
                            bool roundUp
                        ) internal pure returns (uint256 amount0) {
                            if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
                            uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
                            uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;
                            require(sqrtRatioAX96 > 0);
                            return
                                roundUp
                                    ? UnsafeMath.divRoundingUp(
                                        FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96),
                                        sqrtRatioAX96
                                    )
                                    : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;
                        }
                        /// @notice Gets the amount1 delta between two prices
                        /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
                        /// @param sqrtRatioAX96 A sqrt price
                        /// @param sqrtRatioBX96 Another sqrt price
                        /// @param liquidity The amount of usable liquidity
                        /// @param roundUp Whether to round the amount up, or down
                        /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices
                        function getAmount1Delta(
                            uint160 sqrtRatioAX96,
                            uint160 sqrtRatioBX96,
                            uint128 liquidity,
                            bool roundUp
                        ) internal pure returns (uint256 amount1) {
                            if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
                            return
                                roundUp
                                    ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)
                                    : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
                        }
                        /// @notice Helper that gets signed token0 delta
                        /// @param sqrtRatioAX96 A sqrt price
                        /// @param sqrtRatioBX96 Another sqrt price
                        /// @param liquidity The change in liquidity for which to compute the amount0 delta
                        /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices
                        function getAmount0Delta(
                            uint160 sqrtRatioAX96,
                            uint160 sqrtRatioBX96,
                            int128 liquidity
                        ) internal pure returns (int256 amount0) {
                            return
                                liquidity < 0
                                    ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
                                    : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
                        }
                        /// @notice Helper that gets signed token1 delta
                        /// @param sqrtRatioAX96 A sqrt price
                        /// @param sqrtRatioBX96 Another sqrt price
                        /// @param liquidity The change in liquidity for which to compute the amount1 delta
                        /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices
                        function getAmount1Delta(
                            uint160 sqrtRatioAX96,
                            uint160 sqrtRatioBX96,
                            int128 liquidity
                        ) internal pure returns (int256 amount1) {
                            return
                                liquidity < 0
                                    ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()
                                    : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();
                        }
                    }
                    // SPDX-License-Identifier: BUSL-1.1
                    pragma solidity >=0.5.0;
                    import './FullMath.sol';
                    import './SqrtPriceMath.sol';
                    /// @title Computes the result of a swap within ticks
                    /// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.
                    library SwapMath {
                        /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap
                        /// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive
                        /// @param sqrtRatioCurrentX96 The current sqrt price of the pool
                        /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred
                        /// @param liquidity The usable liquidity
                        /// @param amountRemaining How much input or output amount is remaining to be swapped in/out
                        /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip
                        /// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target
                        /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap
                        /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap
                        /// @return feeAmount The amount of input that will be taken as a fee
                        function computeSwapStep(
                            uint160 sqrtRatioCurrentX96,
                            uint160 sqrtRatioTargetX96,
                            uint128 liquidity,
                            int256 amountRemaining,
                            uint24 feePips
                        )
                            internal
                            pure
                            returns (
                                uint160 sqrtRatioNextX96,
                                uint256 amountIn,
                                uint256 amountOut,
                                uint256 feeAmount
                            )
                        {
                            bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96;
                            bool exactIn = amountRemaining >= 0;
                            if (exactIn) {
                                uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(amountRemaining), 1e6 - feePips, 1e6);
                                amountIn = zeroForOne
                                    ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true)
                                    : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);
                                if (amountRemainingLessFee >= amountIn) sqrtRatioNextX96 = sqrtRatioTargetX96;
                                else
                                    sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(
                                        sqrtRatioCurrentX96,
                                        liquidity,
                                        amountRemainingLessFee,
                                        zeroForOne
                                    );
                            } else {
                                amountOut = zeroForOne
                                    ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false)
                                    : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);
                                if (uint256(-amountRemaining) >= amountOut) sqrtRatioNextX96 = sqrtRatioTargetX96;
                                else
                                    sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(
                                        sqrtRatioCurrentX96,
                                        liquidity,
                                        uint256(-amountRemaining),
                                        zeroForOne
                                    );
                            }
                            bool max = sqrtRatioTargetX96 == sqrtRatioNextX96;
                            // get the input/output amounts
                            if (zeroForOne) {
                                amountIn = max && exactIn
                                    ? amountIn
                                    : SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true);
                                amountOut = max && !exactIn
                                    ? amountOut
                                    : SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false);
                            } else {
                                amountIn = max && exactIn
                                    ? amountIn
                                    : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true);
                                amountOut = max && !exactIn
                                    ? amountOut
                                    : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false);
                            }
                            // cap the output amount to not exceed the remaining output amount
                            if (!exactIn && amountOut > uint256(-amountRemaining)) {
                                amountOut = uint256(-amountRemaining);
                            }
                            if (exactIn && sqrtRatioNextX96 != sqrtRatioTargetX96) {
                                // we didn't reach the target, so take the remainder of the maximum input as fee
                                feeAmount = uint256(amountRemaining) - amountIn;
                            } else {
                                feeAmount = FullMath.mulDivRoundingUp(amountIn, feePips, 1e6 - feePips);
                            }
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title An interface for a contract that is capable of deploying Uniswap V3 Pools
                    /// @notice A contract that constructs a pool must implement this to pass arguments to the pool
                    /// @dev This is used to avoid having constructor arguments in the pool contract, which results in the init code hash
                    /// of the pool being constant allowing the CREATE2 address of the pool to be cheaply computed on-chain
                    interface IUniswapV3PoolDeployer {
                        /// @notice Get the parameters to be used in constructing the pool, set transiently during pool creation.
                        /// @dev Called by the pool constructor to fetch the parameters of the pool
                        /// Returns factory The factory address
                        /// Returns token0 The first token of the pool by address sort order
                        /// Returns token1 The second token of the pool by address sort order
                        /// Returns fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
                        /// Returns tickSpacing The minimum number of ticks between initialized ticks
                        function parameters()
                            external
                            view
                            returns (
                                address factory,
                                address token0,
                                address token1,
                                uint24 fee,
                                int24 tickSpacing
                            );
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title The interface for the Uniswap V3 Factory
                    /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees
                    interface IUniswapV3Factory {
                        /// @notice Emitted when the owner of the factory is changed
                        /// @param oldOwner The owner before the owner was changed
                        /// @param newOwner The owner after the owner was changed
                        event OwnerChanged(address indexed oldOwner, address indexed newOwner);
                        /// @notice Emitted when a pool is created
                        /// @param token0 The first token of the pool by address sort order
                        /// @param token1 The second token of the pool by address sort order
                        /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
                        /// @param tickSpacing The minimum number of ticks between initialized ticks
                        /// @param pool The address of the created pool
                        event PoolCreated(
                            address indexed token0,
                            address indexed token1,
                            uint24 indexed fee,
                            int24 tickSpacing,
                            address pool
                        );
                        /// @notice Emitted when a new fee amount is enabled for pool creation via the factory
                        /// @param fee The enabled fee, denominated in hundredths of a bip
                        /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee
                        event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);
                        /// @notice Returns the current owner of the factory
                        /// @dev Can be changed by the current owner via setOwner
                        /// @return The address of the factory owner
                        function owner() external view returns (address);
                        /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled
                        /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context
                        /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee
                        /// @return The tick spacing
                        function feeAmountTickSpacing(uint24 fee) external view returns (int24);
                        /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist
                        /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
                        /// @param tokenA The contract address of either token0 or token1
                        /// @param tokenB The contract address of the other token
                        /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
                        /// @return pool The pool address
                        function getPool(
                            address tokenA,
                            address tokenB,
                            uint24 fee
                        ) external view returns (address pool);
                        /// @notice Creates a pool for the given two tokens and fee
                        /// @param tokenA One of the two tokens in the desired pool
                        /// @param tokenB The other of the two tokens in the desired pool
                        /// @param fee The desired fee for the pool
                        /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
                        /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
                        /// are invalid.
                        /// @return pool The address of the newly created pool
                        function createPool(
                            address tokenA,
                            address tokenB,
                            uint24 fee
                        ) external returns (address pool);
                        /// @notice Updates the owner of the factory
                        /// @dev Must be called by the current owner
                        /// @param _owner The new owner of the factory
                        function setOwner(address _owner) external;
                        /// @notice Enables a fee amount with the given tickSpacing
                        /// @dev Fee amounts may never be removed once enabled
                        /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)
                        /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount
                        function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title Minimal ERC20 interface for Uniswap
                    /// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
                    interface IERC20Minimal {
                        /// @notice Returns the balance of a token
                        /// @param account The account for which to look up the number of tokens it has, i.e. its balance
                        /// @return The number of tokens held by the account
                        function balanceOf(address account) external view returns (uint256);
                        /// @notice Transfers the amount of token from the `msg.sender` to the recipient
                        /// @param recipient The account that will receive the amount transferred
                        /// @param amount The number of tokens to send from the sender to the recipient
                        /// @return Returns true for a successful transfer, false for an unsuccessful transfer
                        function transfer(address recipient, uint256 amount) external returns (bool);
                        /// @notice Returns the current allowance given to a spender by an owner
                        /// @param owner The account of the token owner
                        /// @param spender The account of the token spender
                        /// @return The current allowance granted by `owner` to `spender`
                        function allowance(address owner, address spender) external view returns (uint256);
                        /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
                        /// @param spender The account which will be allowed to spend a given amount of the owners tokens
                        /// @param amount The amount of tokens allowed to be used by `spender`
                        /// @return Returns true for a successful approval, false for unsuccessful
                        function approve(address spender, uint256 amount) external returns (bool);
                        /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
                        /// @param sender The account from which the transfer will be initiated
                        /// @param recipient The recipient of the transfer
                        /// @param amount The amount of the transfer
                        /// @return Returns true for a successful transfer, false for unsuccessful
                        function transferFrom(
                            address sender,
                            address recipient,
                            uint256 amount
                        ) external returns (bool);
                        /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
                        /// @param from The account from which the tokens were sent, i.e. the balance decreased
                        /// @param to The account to which the tokens were sent, i.e. the balance increased
                        /// @param value The amount of tokens that were transferred
                        event Transfer(address indexed from, address indexed to, uint256 value);
                        /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
                        /// @param owner The account that approved spending of its tokens
                        /// @param spender The account for which the spending allowance was modified
                        /// @param value The new allowance from the owner to the spender
                        event Approval(address indexed owner, address indexed spender, uint256 value);
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title Callback for IUniswapV3PoolActions#mint
                    /// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface
                    interface IUniswapV3MintCallback {
                        /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
                        /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
                        /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
                        /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
                        /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
                        /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
                        function uniswapV3MintCallback(
                            uint256 amount0Owed,
                            uint256 amount1Owed,
                            bytes calldata data
                        ) external;
                    }
                    // 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;
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title Callback for IUniswapV3PoolActions#flash
                    /// @notice Any contract that calls IUniswapV3PoolActions#flash must implement this interface
                    interface IUniswapV3FlashCallback {
                        /// @notice Called to `msg.sender` after transferring to the recipient from IUniswapV3Pool#flash.
                        /// @dev In the implementation you must repay the pool the tokens sent by flash plus the computed fee amounts.
                        /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
                        /// @param fee0 The fee amount in token0 due to the pool by the end of the flash
                        /// @param fee1 The fee amount in token1 due to the pool by the end of the flash
                        /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#flash call
                        function uniswapV3FlashCallback(
                            uint256 fee0,
                            uint256 fee1,
                            bytes calldata data
                        ) external;
                    }
                    // 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);
                    }
                    // 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
                            );
                    }
                    // 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
                            );
                    }
                    // 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;
                    }
                    // 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);
                    }
                    // 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);
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title BitMath
                    /// @dev This library provides functionality for computing bit properties of an unsigned integer
                    library BitMath {
                        /// @notice Returns the index of the most significant bit of the number,
                        ///     where the least significant bit is at index 0 and the most significant bit is at index 255
                        /// @dev The function satisfies the property:
                        ///     x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)
                        /// @param x the value for which to compute the most significant bit, must be greater than 0
                        /// @return r the index of the most significant bit
                        function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
                            require(x > 0);
                            if (x >= 0x100000000000000000000000000000000) {
                                x >>= 128;
                                r += 128;
                            }
                            if (x >= 0x10000000000000000) {
                                x >>= 64;
                                r += 64;
                            }
                            if (x >= 0x100000000) {
                                x >>= 32;
                                r += 32;
                            }
                            if (x >= 0x10000) {
                                x >>= 16;
                                r += 16;
                            }
                            if (x >= 0x100) {
                                x >>= 8;
                                r += 8;
                            }
                            if (x >= 0x10) {
                                x >>= 4;
                                r += 4;
                            }
                            if (x >= 0x4) {
                                x >>= 2;
                                r += 2;
                            }
                            if (x >= 0x2) r += 1;
                        }
                        /// @notice Returns the index of the least significant bit of the number,
                        ///     where the least significant bit is at index 0 and the most significant bit is at index 255
                        /// @dev The function satisfies the property:
                        ///     (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)
                        /// @param x the value for which to compute the least significant bit, must be greater than 0
                        /// @return r the index of the least significant bit
                        function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
                            require(x > 0);
                            r = 255;
                            if (x & type(uint128).max > 0) {
                                r -= 128;
                            } else {
                                x >>= 128;
                            }
                            if (x & type(uint64).max > 0) {
                                r -= 64;
                            } else {
                                x >>= 64;
                            }
                            if (x & type(uint32).max > 0) {
                                r -= 32;
                            } else {
                                x >>= 32;
                            }
                            if (x & type(uint16).max > 0) {
                                r -= 16;
                            } else {
                                x >>= 16;
                            }
                            if (x & type(uint8).max > 0) {
                                r -= 8;
                            } else {
                                x >>= 8;
                            }
                            if (x & 0xf > 0) {
                                r -= 4;
                            } else {
                                x >>= 4;
                            }
                            if (x & 0x3 > 0) {
                                r -= 2;
                            } else {
                                x >>= 2;
                            }
                            if (x & 0x1 > 0) r -= 1;
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title Math functions that do not check inputs or outputs
                    /// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
                    library UnsafeMath {
                        /// @notice Returns ceil(x / y)
                        /// @dev division by 0 has unspecified behavior, and must be checked externally
                        /// @param x The dividend
                        /// @param y The divisor
                        /// @return z The quotient, ceil(x / y)
                        function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
                            assembly {
                                z := add(div(x, y), gt(mod(x, y), 0))
                            }
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.4.0;
                    /// @title FixedPoint96
                    /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
                    /// @dev Used in SqrtPriceMath.sol
                    library FixedPoint96 {
                        uint8 internal constant RESOLUTION = 96;
                        uint256 internal constant Q96 = 0x1000000000000000000000000;
                    }
                    

                    File 4 of 6: Kerosine
                    // SPDX-License-Identifier: MIT
                    pragma solidity =0.8.17;
                    import {ERC20} from "@solmate/src/tokens/ERC20.sol";
                    contract Kerosine is ERC20("Kerosene", "KEROSENE", 18) {
                      constructor() {
                          _mint(msg.sender, 1_000_000_000 * 10**18); // 1 billion
                      }
                    }
                    // SPDX-License-Identifier: AGPL-3.0-only
                    pragma solidity >=0.8.0;
                    /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
                    /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
                    /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
                    /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
                    abstract contract ERC20 {
                        /*//////////////////////////////////////////////////////////////
                                                     EVENTS
                        //////////////////////////////////////////////////////////////*/
                        event Transfer(address indexed from, address indexed to, uint256 amount);
                        event Approval(address indexed owner, address indexed spender, uint256 amount);
                        /*//////////////////////////////////////////////////////////////
                                                METADATA STORAGE
                        //////////////////////////////////////////////////////////////*/
                        string public name;
                        string public symbol;
                        uint8 public immutable decimals;
                        /*//////////////////////////////////////////////////////////////
                                                  ERC20 STORAGE
                        //////////////////////////////////////////////////////////////*/
                        uint256 public totalSupply;
                        mapping(address => uint256) public balanceOf;
                        mapping(address => mapping(address => uint256)) public allowance;
                        /*//////////////////////////////////////////////////////////////
                                                EIP-2612 STORAGE
                        //////////////////////////////////////////////////////////////*/
                        uint256 internal immutable INITIAL_CHAIN_ID;
                        bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
                        mapping(address => uint256) public nonces;
                        /*//////////////////////////////////////////////////////////////
                                                   CONSTRUCTOR
                        //////////////////////////////////////////////////////////////*/
                        constructor(
                            string memory _name,
                            string memory _symbol,
                            uint8 _decimals
                        ) {
                            name = _name;
                            symbol = _symbol;
                            decimals = _decimals;
                            INITIAL_CHAIN_ID = block.chainid;
                            INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
                        }
                        /*//////////////////////////////////////////////////////////////
                                                   ERC20 LOGIC
                        //////////////////////////////////////////////////////////////*/
                        function approve(address spender, uint256 amount) public virtual returns (bool) {
                            allowance[msg.sender][spender] = amount;
                            emit Approval(msg.sender, spender, amount);
                            return true;
                        }
                        function transfer(address to, uint256 amount) public virtual returns (bool) {
                            balanceOf[msg.sender] -= amount;
                            // Cannot overflow because the sum of all user
                            // balances can't exceed the max uint256 value.
                            unchecked {
                                balanceOf[to] += amount;
                            }
                            emit Transfer(msg.sender, to, amount);
                            return true;
                        }
                        function transferFrom(
                            address from,
                            address to,
                            uint256 amount
                        ) public virtual returns (bool) {
                            uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
                            if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
                            balanceOf[from] -= amount;
                            // Cannot overflow because the sum of all user
                            // balances can't exceed the max uint256 value.
                            unchecked {
                                balanceOf[to] += amount;
                            }
                            emit Transfer(from, to, amount);
                            return true;
                        }
                        /*//////////////////////////////////////////////////////////////
                                                 EIP-2612 LOGIC
                        //////////////////////////////////////////////////////////////*/
                        function permit(
                            address owner,
                            address spender,
                            uint256 value,
                            uint256 deadline,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) public virtual {
                            require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
                            // Unchecked because the only math done is incrementing
                            // the owner's nonce which cannot realistically overflow.
                            unchecked {
                                address recoveredAddress = ecrecover(
                                    keccak256(
                                        abi.encodePacked(
                                            "\\x19\\x01",
                                            DOMAIN_SEPARATOR(),
                                            keccak256(
                                                abi.encode(
                                                    keccak256(
                                                        "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                                    ),
                                                    owner,
                                                    spender,
                                                    value,
                                                    nonces[owner]++,
                                                    deadline
                                                )
                                            )
                                        )
                                    ),
                                    v,
                                    r,
                                    s
                                );
                                require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
                                allowance[recoveredAddress][spender] = value;
                            }
                            emit Approval(owner, spender, value);
                        }
                        function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
                            return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
                        }
                        function computeDomainSeparator() internal view virtual returns (bytes32) {
                            return
                                keccak256(
                                    abi.encode(
                                        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                                        keccak256(bytes(name)),
                                        keccak256("1"),
                                        block.chainid,
                                        address(this)
                                    )
                                );
                        }
                        /*//////////////////////////////////////////////////////////////
                                            INTERNAL MINT/BURN LOGIC
                        //////////////////////////////////////////////////////////////*/
                        function _mint(address to, uint256 amount) internal virtual {
                            totalSupply += amount;
                            // Cannot overflow because the sum of all user
                            // balances can't exceed the max uint256 value.
                            unchecked {
                                balanceOf[to] += amount;
                            }
                            emit Transfer(address(0), to, amount);
                        }
                        function _burn(address from, uint256 amount) internal virtual {
                            balanceOf[from] -= amount;
                            // Cannot underflow because a user's balance
                            // will never be larger than the total supply.
                            unchecked {
                                totalSupply -= amount;
                            }
                            emit Transfer(from, address(0), amount);
                        }
                    }
                    

                    File 5 of 6: NonfungiblePositionManager
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity =0.7.6;
                    pragma abicoder v2;
                    import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
                    import '@uniswap/v3-core/contracts/libraries/FixedPoint128.sol';
                    import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
                    import './interfaces/INonfungiblePositionManager.sol';
                    import './interfaces/INonfungibleTokenPositionDescriptor.sol';
                    import './libraries/PositionKey.sol';
                    import './libraries/PoolAddress.sol';
                    import './base/LiquidityManagement.sol';
                    import './base/PeripheryImmutableState.sol';
                    import './base/Multicall.sol';
                    import './base/ERC721Permit.sol';
                    import './base/PeripheryValidation.sol';
                    import './base/SelfPermit.sol';
                    import './base/PoolInitializer.sol';
                    /// @title NFT positions
                    /// @notice Wraps Uniswap V3 positions in the ERC721 non-fungible token interface
                    contract NonfungiblePositionManager is
                        INonfungiblePositionManager,
                        Multicall,
                        ERC721Permit,
                        PeripheryImmutableState,
                        PoolInitializer,
                        LiquidityManagement,
                        PeripheryValidation,
                        SelfPermit
                    {
                        // details about the uniswap position
                        struct Position {
                            // the nonce for permits
                            uint96 nonce;
                            // the address that is approved for spending this token
                            address operator;
                            // the ID of the pool with which this token is connected
                            uint80 poolId;
                            // the tick range of the position
                            int24 tickLower;
                            int24 tickUpper;
                            // the liquidity of the position
                            uint128 liquidity;
                            // the fee growth of the aggregate position as of the last action on the individual position
                            uint256 feeGrowthInside0LastX128;
                            uint256 feeGrowthInside1LastX128;
                            // how many uncollected tokens are owed to the position, as of the last computation
                            uint128 tokensOwed0;
                            uint128 tokensOwed1;
                        }
                        /// @dev IDs of pools assigned by this contract
                        mapping(address => uint80) private _poolIds;
                        /// @dev Pool keys by pool ID, to save on SSTOREs for position data
                        mapping(uint80 => PoolAddress.PoolKey) private _poolIdToPoolKey;
                        /// @dev The token ID position data
                        mapping(uint256 => Position) private _positions;
                        /// @dev The ID of the next token that will be minted. Skips 0
                        uint176 private _nextId = 1;
                        /// @dev The ID of the next pool that is used for the first time. Skips 0
                        uint80 private _nextPoolId = 1;
                        /// @dev The address of the token descriptor contract, which handles generating token URIs for position tokens
                        address private immutable _tokenDescriptor;
                        constructor(
                            address _factory,
                            address _WETH9,
                            address _tokenDescriptor_
                        ) ERC721Permit('Uniswap V3 Positions NFT-V1', 'UNI-V3-POS', '1') PeripheryImmutableState(_factory, _WETH9) {
                            _tokenDescriptor = _tokenDescriptor_;
                        }
                        /// @inheritdoc INonfungiblePositionManager
                        function positions(uint256 tokenId)
                            external
                            view
                            override
                            returns (
                                uint96 nonce,
                                address operator,
                                address token0,
                                address token1,
                                uint24 fee,
                                int24 tickLower,
                                int24 tickUpper,
                                uint128 liquidity,
                                uint256 feeGrowthInside0LastX128,
                                uint256 feeGrowthInside1LastX128,
                                uint128 tokensOwed0,
                                uint128 tokensOwed1
                            )
                        {
                            Position memory position = _positions[tokenId];
                            require(position.poolId != 0, 'Invalid token ID');
                            PoolAddress.PoolKey memory poolKey = _poolIdToPoolKey[position.poolId];
                            return (
                                position.nonce,
                                position.operator,
                                poolKey.token0,
                                poolKey.token1,
                                poolKey.fee,
                                position.tickLower,
                                position.tickUpper,
                                position.liquidity,
                                position.feeGrowthInside0LastX128,
                                position.feeGrowthInside1LastX128,
                                position.tokensOwed0,
                                position.tokensOwed1
                            );
                        }
                        /// @dev Caches a pool key
                        function cachePoolKey(address pool, PoolAddress.PoolKey memory poolKey) private returns (uint80 poolId) {
                            poolId = _poolIds[pool];
                            if (poolId == 0) {
                                _poolIds[pool] = (poolId = _nextPoolId++);
                                _poolIdToPoolKey[poolId] = poolKey;
                            }
                        }
                        /// @inheritdoc INonfungiblePositionManager
                        function mint(MintParams calldata params)
                            external
                            payable
                            override
                            checkDeadline(params.deadline)
                            returns (
                                uint256 tokenId,
                                uint128 liquidity,
                                uint256 amount0,
                                uint256 amount1
                            )
                        {
                            IUniswapV3Pool pool;
                            (liquidity, amount0, amount1, pool) = addLiquidity(
                                AddLiquidityParams({
                                    token0: params.token0,
                                    token1: params.token1,
                                    fee: params.fee,
                                    recipient: address(this),
                                    tickLower: params.tickLower,
                                    tickUpper: params.tickUpper,
                                    amount0Desired: params.amount0Desired,
                                    amount1Desired: params.amount1Desired,
                                    amount0Min: params.amount0Min,
                                    amount1Min: params.amount1Min
                                })
                            );
                            _mint(params.recipient, (tokenId = _nextId++));
                            bytes32 positionKey = PositionKey.compute(address(this), params.tickLower, params.tickUpper);
                            (, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, , ) = pool.positions(positionKey);
                            // idempotent set
                            uint80 poolId =
                                cachePoolKey(
                                    address(pool),
                                    PoolAddress.PoolKey({token0: params.token0, token1: params.token1, fee: params.fee})
                                );
                            _positions[tokenId] = Position({
                                nonce: 0,
                                operator: address(0),
                                poolId: poolId,
                                tickLower: params.tickLower,
                                tickUpper: params.tickUpper,
                                liquidity: liquidity,
                                feeGrowthInside0LastX128: feeGrowthInside0LastX128,
                                feeGrowthInside1LastX128: feeGrowthInside1LastX128,
                                tokensOwed0: 0,
                                tokensOwed1: 0
                            });
                            emit IncreaseLiquidity(tokenId, liquidity, amount0, amount1);
                        }
                        modifier isAuthorizedForToken(uint256 tokenId) {
                            require(_isApprovedOrOwner(msg.sender, tokenId), 'Not approved');
                            _;
                        }
                        function tokenURI(uint256 tokenId) public view override(ERC721, IERC721Metadata) returns (string memory) {
                            require(_exists(tokenId));
                            return INonfungibleTokenPositionDescriptor(_tokenDescriptor).tokenURI(this, tokenId);
                        }
                        // save bytecode by removing implementation of unused method
                        function baseURI() public pure override returns (string memory) {}
                        /// @inheritdoc INonfungiblePositionManager
                        function increaseLiquidity(IncreaseLiquidityParams calldata params)
                            external
                            payable
                            override
                            checkDeadline(params.deadline)
                            returns (
                                uint128 liquidity,
                                uint256 amount0,
                                uint256 amount1
                            )
                        {
                            Position storage position = _positions[params.tokenId];
                            PoolAddress.PoolKey memory poolKey = _poolIdToPoolKey[position.poolId];
                            IUniswapV3Pool pool;
                            (liquidity, amount0, amount1, pool) = addLiquidity(
                                AddLiquidityParams({
                                    token0: poolKey.token0,
                                    token1: poolKey.token1,
                                    fee: poolKey.fee,
                                    tickLower: position.tickLower,
                                    tickUpper: position.tickUpper,
                                    amount0Desired: params.amount0Desired,
                                    amount1Desired: params.amount1Desired,
                                    amount0Min: params.amount0Min,
                                    amount1Min: params.amount1Min,
                                    recipient: address(this)
                                })
                            );
                            bytes32 positionKey = PositionKey.compute(address(this), position.tickLower, position.tickUpper);
                            // this is now updated to the current transaction
                            (, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, , ) = pool.positions(positionKey);
                            position.tokensOwed0 += uint128(
                                FullMath.mulDiv(
                                    feeGrowthInside0LastX128 - position.feeGrowthInside0LastX128,
                                    position.liquidity,
                                    FixedPoint128.Q128
                                )
                            );
                            position.tokensOwed1 += uint128(
                                FullMath.mulDiv(
                                    feeGrowthInside1LastX128 - position.feeGrowthInside1LastX128,
                                    position.liquidity,
                                    FixedPoint128.Q128
                                )
                            );
                            position.feeGrowthInside0LastX128 = feeGrowthInside0LastX128;
                            position.feeGrowthInside1LastX128 = feeGrowthInside1LastX128;
                            position.liquidity += liquidity;
                            emit IncreaseLiquidity(params.tokenId, liquidity, amount0, amount1);
                        }
                        /// @inheritdoc INonfungiblePositionManager
                        function decreaseLiquidity(DecreaseLiquidityParams calldata params)
                            external
                            payable
                            override
                            isAuthorizedForToken(params.tokenId)
                            checkDeadline(params.deadline)
                            returns (uint256 amount0, uint256 amount1)
                        {
                            require(params.liquidity > 0);
                            Position storage position = _positions[params.tokenId];
                            uint128 positionLiquidity = position.liquidity;
                            require(positionLiquidity >= params.liquidity);
                            PoolAddress.PoolKey memory poolKey = _poolIdToPoolKey[position.poolId];
                            IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey));
                            (amount0, amount1) = pool.burn(position.tickLower, position.tickUpper, params.liquidity);
                            require(amount0 >= params.amount0Min && amount1 >= params.amount1Min, 'Price slippage check');
                            bytes32 positionKey = PositionKey.compute(address(this), position.tickLower, position.tickUpper);
                            // this is now updated to the current transaction
                            (, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, , ) = pool.positions(positionKey);
                            position.tokensOwed0 +=
                                uint128(amount0) +
                                uint128(
                                    FullMath.mulDiv(
                                        feeGrowthInside0LastX128 - position.feeGrowthInside0LastX128,
                                        positionLiquidity,
                                        FixedPoint128.Q128
                                    )
                                );
                            position.tokensOwed1 +=
                                uint128(amount1) +
                                uint128(
                                    FullMath.mulDiv(
                                        feeGrowthInside1LastX128 - position.feeGrowthInside1LastX128,
                                        positionLiquidity,
                                        FixedPoint128.Q128
                                    )
                                );
                            position.feeGrowthInside0LastX128 = feeGrowthInside0LastX128;
                            position.feeGrowthInside1LastX128 = feeGrowthInside1LastX128;
                            // subtraction is safe because we checked positionLiquidity is gte params.liquidity
                            position.liquidity = positionLiquidity - params.liquidity;
                            emit DecreaseLiquidity(params.tokenId, params.liquidity, amount0, amount1);
                        }
                        /// @inheritdoc INonfungiblePositionManager
                        function collect(CollectParams calldata params)
                            external
                            payable
                            override
                            isAuthorizedForToken(params.tokenId)
                            returns (uint256 amount0, uint256 amount1)
                        {
                            require(params.amount0Max > 0 || params.amount1Max > 0);
                            // allow collecting to the nft position manager address with address 0
                            address recipient = params.recipient == address(0) ? address(this) : params.recipient;
                            Position storage position = _positions[params.tokenId];
                            PoolAddress.PoolKey memory poolKey = _poolIdToPoolKey[position.poolId];
                            IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey));
                            (uint128 tokensOwed0, uint128 tokensOwed1) = (position.tokensOwed0, position.tokensOwed1);
                            // trigger an update of the position fees owed and fee growth snapshots if it has any liquidity
                            if (position.liquidity > 0) {
                                pool.burn(position.tickLower, position.tickUpper, 0);
                                (, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, , ) =
                                    pool.positions(PositionKey.compute(address(this), position.tickLower, position.tickUpper));
                                tokensOwed0 += uint128(
                                    FullMath.mulDiv(
                                        feeGrowthInside0LastX128 - position.feeGrowthInside0LastX128,
                                        position.liquidity,
                                        FixedPoint128.Q128
                                    )
                                );
                                tokensOwed1 += uint128(
                                    FullMath.mulDiv(
                                        feeGrowthInside1LastX128 - position.feeGrowthInside1LastX128,
                                        position.liquidity,
                                        FixedPoint128.Q128
                                    )
                                );
                                position.feeGrowthInside0LastX128 = feeGrowthInside0LastX128;
                                position.feeGrowthInside1LastX128 = feeGrowthInside1LastX128;
                            }
                            // compute the arguments to give to the pool#collect method
                            (uint128 amount0Collect, uint128 amount1Collect) =
                                (
                                    params.amount0Max > tokensOwed0 ? tokensOwed0 : params.amount0Max,
                                    params.amount1Max > tokensOwed1 ? tokensOwed1 : params.amount1Max
                                );
                            // the actual amounts collected are returned
                            (amount0, amount1) = pool.collect(
                                recipient,
                                position.tickLower,
                                position.tickUpper,
                                amount0Collect,
                                amount1Collect
                            );
                            // sometimes there will be a few less wei than expected due to rounding down in core, but we just subtract the full amount expected
                            // instead of the actual amount so we can burn the token
                            (position.tokensOwed0, position.tokensOwed1) = (tokensOwed0 - amount0Collect, tokensOwed1 - amount1Collect);
                            emit Collect(params.tokenId, recipient, amount0Collect, amount1Collect);
                        }
                        /// @inheritdoc INonfungiblePositionManager
                        function burn(uint256 tokenId) external payable override isAuthorizedForToken(tokenId) {
                            Position storage position = _positions[tokenId];
                            require(position.liquidity == 0 && position.tokensOwed0 == 0 && position.tokensOwed1 == 0, 'Not cleared');
                            delete _positions[tokenId];
                            _burn(tokenId);
                        }
                        function _getAndIncrementNonce(uint256 tokenId) internal override returns (uint256) {
                            return uint256(_positions[tokenId].nonce++);
                        }
                        /// @inheritdoc IERC721
                        function getApproved(uint256 tokenId) public view override(ERC721, IERC721) returns (address) {
                            require(_exists(tokenId), 'ERC721: approved query for nonexistent token');
                            return _positions[tokenId].operator;
                        }
                        /// @dev Overrides _approve to use the operator in the position, which is packed with the position permit nonce
                        function _approve(address to, uint256 tokenId) internal override(ERC721) {
                            _positions[tokenId].operator = to;
                            emit Approval(ownerOf(tokenId), to, tokenId);
                        }
                    }
                    // 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
                    {
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.4.0;
                    /// @title FixedPoint128
                    /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
                    library FixedPoint128 {
                        uint256 internal constant Q128 = 0x100000000000000000000000000000000;
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity >=0.4.0;
                    /// @title Contains 512-bit math functions
                    /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
                    /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
                    library FullMath {
                        /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
                        /// @param a The multiplicand
                        /// @param b The multiplier
                        /// @param denominator The divisor
                        /// @return result The 256-bit result
                        /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
                        function mulDiv(
                            uint256 a,
                            uint256 b,
                            uint256 denominator
                        ) internal pure returns (uint256 result) {
                            // 512-bit multiply [prod1 prod0] = a * b
                            // Compute the product mod 2**256 and mod 2**256 - 1
                            // then 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; // Least significant 256 bits of the product
                            uint256 prod1; // Most significant 256 bits of the product
                            assembly {
                                let mm := mulmod(a, b, not(0))
                                prod0 := mul(a, b)
                                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                            }
                            // Handle non-overflow cases, 256 by 256 division
                            if (prod1 == 0) {
                                require(denominator > 0);
                                assembly {
                                    result := div(prod0, denominator)
                                }
                                return result;
                            }
                            // Make sure the result is less than 2**256.
                            // Also prevents denominator == 0
                            require(denominator > prod1);
                            ///////////////////////////////////////////////
                            // 512 by 256 division.
                            ///////////////////////////////////////////////
                            // Make division exact by subtracting the remainder from [prod1 prod0]
                            // Compute remainder using mulmod
                            uint256 remainder;
                            assembly {
                                remainder := mulmod(a, b, denominator)
                            }
                            // Subtract 256 bit number from 512 bit number
                            assembly {
                                prod1 := sub(prod1, gt(remainder, prod0))
                                prod0 := sub(prod0, remainder)
                            }
                            // Factor powers of two out of denominator
                            // Compute largest power of two divisor of denominator.
                            // Always >= 1.
                            uint256 twos = -denominator & denominator;
                            // Divide denominator by power of two
                            assembly {
                                denominator := div(denominator, twos)
                            }
                            // Divide [prod1 prod0] by the factors of two
                            assembly {
                                prod0 := div(prod0, twos)
                            }
                            // Shift in bits from prod1 into prod0. For this we need
                            // to flip `twos` such that it is 2**256 / twos.
                            // If twos is zero, then it becomes one
                            assembly {
                                twos := add(div(sub(0, twos), twos), 1)
                            }
                            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
                            // correct for four bits. That is, denominator * inv = 1 mod 2**4
                            uint256 inv = (3 * denominator) ^ 2;
                            // Now use 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.
                            inv *= 2 - denominator * inv; // inverse mod 2**8
                            inv *= 2 - denominator * inv; // inverse mod 2**16
                            inv *= 2 - denominator * inv; // inverse mod 2**32
                            inv *= 2 - denominator * inv; // inverse mod 2**64
                            inv *= 2 - denominator * inv; // inverse mod 2**128
                            inv *= 2 - denominator * inv; // 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 precoditions 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 * inv;
                            return result;
                        }
                        /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
                        /// @param a The multiplicand
                        /// @param b The multiplier
                        /// @param denominator The divisor
                        /// @return result The 256-bit result
                        function mulDivRoundingUp(
                            uint256 a,
                            uint256 b,
                            uint256 denominator
                        ) internal pure returns (uint256 result) {
                            result = mulDiv(a, b, denominator);
                            if (mulmod(a, b, denominator) > 0) {
                                require(result < type(uint256).max);
                                result++;
                            }
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.7.5;
                    pragma abicoder v2;
                    import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol';
                    import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol';
                    import './IPoolInitializer.sol';
                    import './IERC721Permit.sol';
                    import './IPeripheryPayments.sol';
                    import './IPeripheryImmutableState.sol';
                    import '../libraries/PoolAddress.sol';
                    /// @title Non-fungible token for positions
                    /// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
                    /// and authorized.
                    interface INonfungiblePositionManager is
                        IPoolInitializer,
                        IPeripheryPayments,
                        IPeripheryImmutableState,
                        IERC721Metadata,
                        IERC721Enumerable,
                        IERC721Permit
                    {
                        /// @notice Emitted when liquidity is increased for a position NFT
                        /// @dev Also emitted when a token is minted
                        /// @param tokenId The ID of the token for which liquidity was increased
                        /// @param liquidity The amount by which liquidity for the NFT position was increased
                        /// @param amount0 The amount of token0 that was paid for the increase in liquidity
                        /// @param amount1 The amount of token1 that was paid for the increase in liquidity
                        event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
                        /// @notice Emitted when liquidity is decreased for a position NFT
                        /// @param tokenId The ID of the token for which liquidity was decreased
                        /// @param liquidity The amount by which liquidity for the NFT position was decreased
                        /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
                        /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
                        event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
                        /// @notice Emitted when tokens are collected for a position NFT
                        /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
                        /// @param tokenId The ID of the token for which underlying tokens were collected
                        /// @param recipient The address of the account that received the collected tokens
                        /// @param amount0 The amount of token0 owed to the position that was collected
                        /// @param amount1 The amount of token1 owed to the position that was collected
                        event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);
                        /// @notice Returns the position information associated with a given token ID.
                        /// @dev Throws if the token ID is not valid.
                        /// @param tokenId The ID of the token that represents the position
                        /// @return nonce The nonce for permits
                        /// @return operator The address that is approved for spending
                        /// @return token0 The address of the token0 for a specific pool
                        /// @return token1 The address of the token1 for a specific pool
                        /// @return fee The fee associated with the pool
                        /// @return tickLower The lower end of the tick range for the position
                        /// @return tickUpper The higher end of the tick range for the position
                        /// @return liquidity The liquidity of the position
                        /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
                        /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
                        /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
                        /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
                        function positions(uint256 tokenId)
                            external
                            view
                            returns (
                                uint96 nonce,
                                address operator,
                                address token0,
                                address token1,
                                uint24 fee,
                                int24 tickLower,
                                int24 tickUpper,
                                uint128 liquidity,
                                uint256 feeGrowthInside0LastX128,
                                uint256 feeGrowthInside1LastX128,
                                uint128 tokensOwed0,
                                uint128 tokensOwed1
                            );
                        struct MintParams {
                            address token0;
                            address token1;
                            uint24 fee;
                            int24 tickLower;
                            int24 tickUpper;
                            uint256 amount0Desired;
                            uint256 amount1Desired;
                            uint256 amount0Min;
                            uint256 amount1Min;
                            address recipient;
                            uint256 deadline;
                        }
                        /// @notice Creates a new position wrapped in a NFT
                        /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
                        /// a method does not exist, i.e. the pool is assumed to be initialized.
                        /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
                        /// @return tokenId The ID of the token that represents the minted position
                        /// @return liquidity The amount of liquidity for this position
                        /// @return amount0 The amount of token0
                        /// @return amount1 The amount of token1
                        function mint(MintParams calldata params)
                            external
                            payable
                            returns (
                                uint256 tokenId,
                                uint128 liquidity,
                                uint256 amount0,
                                uint256 amount1
                            );
                        struct IncreaseLiquidityParams {
                            uint256 tokenId;
                            uint256 amount0Desired;
                            uint256 amount1Desired;
                            uint256 amount0Min;
                            uint256 amount1Min;
                            uint256 deadline;
                        }
                        /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
                        /// @param params tokenId The ID of the token for which liquidity is being increased,
                        /// amount0Desired The desired amount of token0 to be spent,
                        /// amount1Desired The desired amount of token1 to be spent,
                        /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
                        /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
                        /// deadline The time by which the transaction must be included to effect the change
                        /// @return liquidity The new liquidity amount as a result of the increase
                        /// @return amount0 The amount of token0 to acheive resulting liquidity
                        /// @return amount1 The amount of token1 to acheive resulting liquidity
                        function increaseLiquidity(IncreaseLiquidityParams calldata params)
                            external
                            payable
                            returns (
                                uint128 liquidity,
                                uint256 amount0,
                                uint256 amount1
                            );
                        struct DecreaseLiquidityParams {
                            uint256 tokenId;
                            uint128 liquidity;
                            uint256 amount0Min;
                            uint256 amount1Min;
                            uint256 deadline;
                        }
                        /// @notice Decreases the amount of liquidity in a position and accounts it to the position
                        /// @param params tokenId The ID of the token for which liquidity is being decreased,
                        /// amount The amount by which liquidity will be decreased,
                        /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
                        /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
                        /// deadline The time by which the transaction must be included to effect the change
                        /// @return amount0 The amount of token0 accounted to the position's tokens owed
                        /// @return amount1 The amount of token1 accounted to the position's tokens owed
                        function decreaseLiquidity(DecreaseLiquidityParams calldata params)
                            external
                            payable
                            returns (uint256 amount0, uint256 amount1);
                        struct CollectParams {
                            uint256 tokenId;
                            address recipient;
                            uint128 amount0Max;
                            uint128 amount1Max;
                        }
                        /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
                        /// @param params tokenId The ID of the NFT for which tokens are being collected,
                        /// recipient The account that should receive the tokens,
                        /// amount0Max The maximum amount of token0 to collect,
                        /// amount1Max The maximum amount of token1 to collect
                        /// @return amount0 The amount of fees collected in token0
                        /// @return amount1 The amount of fees collected in token1
                        function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
                        /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
                        /// must be collected first.
                        /// @param tokenId The ID of the token that is being burned
                        function burn(uint256 tokenId) external payable;
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    import './INonfungiblePositionManager.sol';
                    /// @title Describes position NFT tokens via URI
                    interface INonfungibleTokenPositionDescriptor {
                        /// @notice Emitted when a token is given a new priority order in the displayed price ratio
                        /// @param token The token being given priority order
                        /// @param priority Represents priority in ratio - higher integers get numerator priority
                        event UpdateTokenRatioPriority(address token, int256 priority);
                        /// @notice Produces the URI describing a particular token ID for a position manager
                        /// @dev Note this URI may be a data: URI with the JSON contents directly inlined
                        /// @param positionManager The position manager for which to describe the token
                        /// @param tokenId The ID of the token for which to produce a description, which may not be valid
                        /// @return The URI of the ERC721-compliant metadata
                        function tokenURI(INonfungiblePositionManager positionManager, uint256 tokenId)
                            external
                            view
                            returns (string memory);
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    library PositionKey {
                        /// @dev Returns the key of the position in the core library
                        function compute(
                            address owner,
                            int24 tickLower,
                            int24 tickUpper
                        ) internal pure returns (bytes32) {
                            return keccak256(abi.encodePacked(owner, tickLower, tickUpper));
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
                    library PoolAddress {
                        bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
                        /// @notice The identifying key of the pool
                        struct PoolKey {
                            address token0;
                            address token1;
                            uint24 fee;
                        }
                        /// @notice Returns PoolKey: the ordered tokens with the matched fee levels
                        /// @param tokenA The first token of a pool, unsorted
                        /// @param tokenB The second token of a pool, unsorted
                        /// @param fee The fee level of the pool
                        /// @return Poolkey The pool details with ordered token0 and token1 assignments
                        function getPoolKey(
                            address tokenA,
                            address tokenB,
                            uint24 fee
                        ) internal pure returns (PoolKey memory) {
                            if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
                            return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
                        }
                        /// @notice Deterministically computes the pool address given the factory and PoolKey
                        /// @param factory The Uniswap V3 factory contract address
                        /// @param key The PoolKey
                        /// @return pool The contract address of the V3 pool
                        function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
                            require(key.token0 < key.token1);
                            pool = address(
                                uint256(
                                    keccak256(
                                        abi.encodePacked(
                                            hex'ff',
                                            factory,
                                            keccak256(abi.encode(key.token0, key.token1, key.fee)),
                                            POOL_INIT_CODE_HASH
                                        )
                                    )
                                )
                            );
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity =0.7.6;
                    pragma abicoder v2;
                    import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol';
                    import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol';
                    import '@uniswap/v3-core/contracts/libraries/TickMath.sol';
                    import '../libraries/PoolAddress.sol';
                    import '../libraries/CallbackValidation.sol';
                    import '../libraries/LiquidityAmounts.sol';
                    import './PeripheryPayments.sol';
                    import './PeripheryImmutableState.sol';
                    /// @title Liquidity management functions
                    /// @notice Internal functions for safely managing liquidity in Uniswap V3
                    abstract contract LiquidityManagement is IUniswapV3MintCallback, PeripheryImmutableState, PeripheryPayments {
                        struct MintCallbackData {
                            PoolAddress.PoolKey poolKey;
                            address payer;
                        }
                        /// @inheritdoc IUniswapV3MintCallback
                        function uniswapV3MintCallback(
                            uint256 amount0Owed,
                            uint256 amount1Owed,
                            bytes calldata data
                        ) external override {
                            MintCallbackData memory decoded = abi.decode(data, (MintCallbackData));
                            CallbackValidation.verifyCallback(factory, decoded.poolKey);
                            if (amount0Owed > 0) pay(decoded.poolKey.token0, decoded.payer, msg.sender, amount0Owed);
                            if (amount1Owed > 0) pay(decoded.poolKey.token1, decoded.payer, msg.sender, amount1Owed);
                        }
                        struct AddLiquidityParams {
                            address token0;
                            address token1;
                            uint24 fee;
                            address recipient;
                            int24 tickLower;
                            int24 tickUpper;
                            uint256 amount0Desired;
                            uint256 amount1Desired;
                            uint256 amount0Min;
                            uint256 amount1Min;
                        }
                        /// @notice Add liquidity to an initialized pool
                        function addLiquidity(AddLiquidityParams memory params)
                            internal
                            returns (
                                uint128 liquidity,
                                uint256 amount0,
                                uint256 amount1,
                                IUniswapV3Pool pool
                            )
                        {
                            PoolAddress.PoolKey memory poolKey =
                                PoolAddress.PoolKey({token0: params.token0, token1: params.token1, fee: params.fee});
                            pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey));
                            // compute the liquidity amount
                            {
                                (uint160 sqrtPriceX96, , , , , , ) = pool.slot0();
                                uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(params.tickLower);
                                uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(params.tickUpper);
                                liquidity = LiquidityAmounts.getLiquidityForAmounts(
                                    sqrtPriceX96,
                                    sqrtRatioAX96,
                                    sqrtRatioBX96,
                                    params.amount0Desired,
                                    params.amount1Desired
                                );
                            }
                            (amount0, amount1) = pool.mint(
                                params.recipient,
                                params.tickLower,
                                params.tickUpper,
                                liquidity,
                                abi.encode(MintCallbackData({poolKey: poolKey, payer: msg.sender}))
                            );
                            require(amount0 >= params.amount0Min && amount1 >= params.amount1Min, 'Price slippage check');
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity =0.7.6;
                    import '../interfaces/IPeripheryImmutableState.sol';
                    /// @title Immutable state
                    /// @notice Immutable state used by periphery contracts
                    abstract contract PeripheryImmutableState is IPeripheryImmutableState {
                        /// @inheritdoc IPeripheryImmutableState
                        address public immutable override factory;
                        /// @inheritdoc IPeripheryImmutableState
                        address public immutable override WETH9;
                        constructor(address _factory, address _WETH9) {
                            factory = _factory;
                            WETH9 = _WETH9;
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity =0.7.6;
                    pragma abicoder v2;
                    import '../interfaces/IMulticall.sol';
                    /// @title Multicall
                    /// @notice Enables calling multiple methods in a single call to the contract
                    abstract contract Multicall is IMulticall {
                        /// @inheritdoc IMulticall
                        function multicall(bytes[] calldata data) external payable override returns (bytes[] memory results) {
                            results = new bytes[](data.length);
                            for (uint256 i = 0; i < data.length; i++) {
                                (bool success, bytes memory result) = address(this).delegatecall(data[i]);
                                if (!success) {
                                    // Next 5 lines from https://ethereum.stackexchange.com/a/83577
                                    if (result.length < 68) revert();
                                    assembly {
                                        result := add(result, 0x04)
                                    }
                                    revert(abi.decode(result, (string)));
                                }
                                results[i] = result;
                            }
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity =0.7.6;
                    import '@openzeppelin/contracts/token/ERC721/ERC721.sol';
                    import '@openzeppelin/contracts/utils/Address.sol';
                    import '../libraries/ChainId.sol';
                    import '../interfaces/external/IERC1271.sol';
                    import '../interfaces/IERC721Permit.sol';
                    import './BlockTimestamp.sol';
                    /// @title ERC721 with permit
                    /// @notice Nonfungible tokens that support an approve via signature, i.e. permit
                    abstract contract ERC721Permit is BlockTimestamp, ERC721, IERC721Permit {
                        /// @dev Gets the current nonce for a token ID and then increments it, returning the original value
                        function _getAndIncrementNonce(uint256 tokenId) internal virtual returns (uint256);
                        /// @dev The hash of the name used in the permit signature verification
                        bytes32 private immutable nameHash;
                        /// @dev The hash of the version string used in the permit signature verification
                        bytes32 private immutable versionHash;
                        /// @notice Computes the nameHash and versionHash
                        constructor(
                            string memory name_,
                            string memory symbol_,
                            string memory version_
                        ) ERC721(name_, symbol_) {
                            nameHash = keccak256(bytes(name_));
                            versionHash = keccak256(bytes(version_));
                        }
                        /// @inheritdoc IERC721Permit
                        function DOMAIN_SEPARATOR() public view override returns (bytes32) {
                            return
                                keccak256(
                                    abi.encode(
                                        // keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
                                        0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
                                        nameHash,
                                        versionHash,
                                        ChainId.get(),
                                        address(this)
                                    )
                                );
                        }
                        /// @inheritdoc IERC721Permit
                        /// @dev Value is equal to keccak256("Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)");
                        bytes32 public constant override PERMIT_TYPEHASH =
                            0x49ecf333e5b8c95c40fdafc95c1ad136e8914a8fb55e9dc8bb01eaa83a2df9ad;
                        /// @inheritdoc IERC721Permit
                        function permit(
                            address spender,
                            uint256 tokenId,
                            uint256 deadline,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) external payable override {
                            require(_blockTimestamp() <= deadline, 'Permit expired');
                            bytes32 digest =
                                keccak256(
                                    abi.encodePacked(
                                        '\\x19\\x01',
                                        DOMAIN_SEPARATOR(),
                                        keccak256(abi.encode(PERMIT_TYPEHASH, spender, tokenId, _getAndIncrementNonce(tokenId), deadline))
                                    )
                                );
                            address owner = ownerOf(tokenId);
                            require(spender != owner, 'ERC721Permit: approval to current owner');
                            if (Address.isContract(owner)) {
                                require(IERC1271(owner).isValidSignature(digest, abi.encodePacked(r, s, v)) == 0x1626ba7e, 'Unauthorized');
                            } else {
                                address recoveredAddress = ecrecover(digest, v, r, s);
                                require(recoveredAddress != address(0), 'Invalid signature');
                                require(recoveredAddress == owner, 'Unauthorized');
                            }
                            _approve(spender, tokenId);
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity =0.7.6;
                    import './BlockTimestamp.sol';
                    abstract contract PeripheryValidation is BlockTimestamp {
                        modifier checkDeadline(uint256 deadline) {
                            require(_blockTimestamp() <= deadline, 'Transaction too old');
                            _;
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
                    import '@openzeppelin/contracts/drafts/IERC20Permit.sol';
                    import '../interfaces/ISelfPermit.sol';
                    import '../interfaces/external/IERC20PermitAllowed.sol';
                    /// @title Self Permit
                    /// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route
                    /// @dev These functions are expected to be embedded in multicalls to allow EOAs to approve a contract and call a function
                    /// that requires an approval in a single transaction.
                    abstract contract SelfPermit is ISelfPermit {
                        /// @inheritdoc ISelfPermit
                        function selfPermit(
                            address token,
                            uint256 value,
                            uint256 deadline,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) public payable override {
                            IERC20Permit(token).permit(msg.sender, address(this), value, deadline, v, r, s);
                        }
                        /// @inheritdoc ISelfPermit
                        function selfPermitIfNecessary(
                            address token,
                            uint256 value,
                            uint256 deadline,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) external payable override {
                            if (IERC20(token).allowance(msg.sender, address(this)) < value) selfPermit(token, value, deadline, v, r, s);
                        }
                        /// @inheritdoc ISelfPermit
                        function selfPermitAllowed(
                            address token,
                            uint256 nonce,
                            uint256 expiry,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) public payable override {
                            IERC20PermitAllowed(token).permit(msg.sender, address(this), nonce, expiry, true, v, r, s);
                        }
                        /// @inheritdoc ISelfPermit
                        function selfPermitAllowedIfNecessary(
                            address token,
                            uint256 nonce,
                            uint256 expiry,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) external payable override {
                            if (IERC20(token).allowance(msg.sender, address(this)) < type(uint256).max)
                                selfPermitAllowed(token, nonce, expiry, v, r, s);
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity =0.7.6;
                    import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol';
                    import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
                    import './PeripheryImmutableState.sol';
                    import '../interfaces/IPoolInitializer.sol';
                    /// @title Creates and initializes V3 Pools
                    abstract contract PoolInitializer is IPoolInitializer, PeripheryImmutableState {
                        /// @inheritdoc IPoolInitializer
                        function createAndInitializePoolIfNecessary(
                            address token0,
                            address token1,
                            uint24 fee,
                            uint160 sqrtPriceX96
                        ) external payable override returns (address pool) {
                            require(token0 < token1);
                            pool = IUniswapV3Factory(factory).getPool(token0, token1, fee);
                            if (pool == address(0)) {
                                pool = IUniswapV3Factory(factory).createPool(token0, token1, fee);
                                IUniswapV3Pool(pool).initialize(sqrtPriceX96);
                            } else {
                                (uint160 sqrtPriceX96Existing, , , , , , ) = IUniswapV3Pool(pool).slot0();
                                if (sqrtPriceX96Existing == 0) {
                                    IUniswapV3Pool(pool).initialize(sqrtPriceX96);
                                }
                            }
                        }
                    }
                    // 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);
                    }
                    // 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
                            );
                    }
                    // 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
                            );
                    }
                    // 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;
                    }
                    // 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);
                    }
                    // 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);
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.7.0;
                    import "./IERC721.sol";
                    /**
                     * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
                     * @dev See https://eips.ethereum.org/EIPS/eip-721
                     */
                    interface IERC721Metadata is IERC721 {
                        /**
                         * @dev Returns the token collection name.
                         */
                        function name() external view returns (string memory);
                        /**
                         * @dev Returns the token collection symbol.
                         */
                        function symbol() external view returns (string memory);
                        /**
                         * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
                         */
                        function tokenURI(uint256 tokenId) external view returns (string memory);
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.7.0;
                    import "./IERC721.sol";
                    /**
                     * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
                     * @dev See https://eips.ethereum.org/EIPS/eip-721
                     */
                    interface IERC721Enumerable is IERC721 {
                        /**
                         * @dev Returns the total amount of tokens stored by the contract.
                         */
                        function totalSupply() external view returns (uint256);
                        /**
                         * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
                         * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
                         */
                        function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
                        /**
                         * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
                         * Use along with {totalSupply} to enumerate all tokens.
                         */
                        function tokenByIndex(uint256 index) external view returns (uint256);
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.7.5;
                    pragma abicoder v2;
                    /// @title Creates and initializes V3 Pools
                    /// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
                    /// require the pool to exist.
                    interface IPoolInitializer {
                        /// @notice Creates a new pool if it does not exist, then initializes if not initialized
                        /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
                        /// @param token0 The contract address of token0 of the pool
                        /// @param token1 The contract address of token1 of the pool
                        /// @param fee The fee amount of the v3 pool for the specified token pair
                        /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
                        /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
                        function createAndInitializePoolIfNecessary(
                            address token0,
                            address token1,
                            uint24 fee,
                            uint160 sqrtPriceX96
                        ) external payable returns (address pool);
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.7.5;
                    import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
                    /// @title ERC721 with permit
                    /// @notice Extension to ERC721 that includes a permit function for signature based approvals
                    interface IERC721Permit is IERC721 {
                        /// @notice The permit typehash used in the permit signature
                        /// @return The typehash for the permit
                        function PERMIT_TYPEHASH() external pure returns (bytes32);
                        /// @notice The domain separator used in the permit signature
                        /// @return The domain seperator used in encoding of permit signature
                        function DOMAIN_SEPARATOR() external view returns (bytes32);
                        /// @notice Approve of a specific token ID for spending by spender via signature
                        /// @param spender The account that is being approved
                        /// @param tokenId The ID of the token that is being approved for spending
                        /// @param deadline The deadline timestamp by which the call must be mined for the approve to work
                        /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
                        /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
                        /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
                        function permit(
                            address spender,
                            uint256 tokenId,
                            uint256 deadline,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) external payable;
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.7.5;
                    /// @title Periphery Payments
                    /// @notice Functions to ease deposits and withdrawals of ETH
                    interface IPeripheryPayments {
                        /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
                        /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
                        /// @param amountMinimum The minimum amount of WETH9 to unwrap
                        /// @param recipient The address receiving ETH
                        function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;
                        /// @notice Refunds any ETH balance held by this contract to the `msg.sender`
                        /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
                        /// that use ether for the input amount
                        function refundETH() external payable;
                        /// @notice Transfers the full amount of a token held by this contract to recipient
                        /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
                        /// @param token The contract address of the token which will be transferred to `recipient`
                        /// @param amountMinimum The minimum amount of token required for a transfer
                        /// @param recipient The destination address of the token
                        function sweepToken(
                            address token,
                            uint256 amountMinimum,
                            address recipient
                        ) external payable;
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title Immutable state
                    /// @notice Functions that return immutable state of the router
                    interface IPeripheryImmutableState {
                        /// @return Returns the address of the Uniswap V3 factory
                        function factory() external view returns (address);
                        /// @return Returns the address of WETH9
                        function WETH9() external view returns (address);
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.7.0;
                    import "../../introspection/IERC165.sol";
                    /**
                     * @dev Required interface of an ERC721 compliant contract.
                     */
                    interface IERC721 is IERC165 {
                        /**
                         * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
                         */
                        event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
                        /**
                         * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
                         */
                        event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
                        /**
                         * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
                         */
                        event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
                        /**
                         * @dev Returns the number of tokens in ``owner``'s account.
                         */
                        function balanceOf(address owner) external view returns (uint256 balance);
                        /**
                         * @dev Returns the owner of the `tokenId` token.
                         *
                         * Requirements:
                         *
                         * - `tokenId` must exist.
                         */
                        function ownerOf(uint256 tokenId) external view returns (address owner);
                        /**
                         * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
                         * are aware of the ERC721 protocol to prevent tokens from being forever locked.
                         *
                         * Requirements:
                         *
                         * - `from` cannot be the zero address.
                         * - `to` cannot be the zero address.
                         * - `tokenId` token must exist and be owned by `from`.
                         * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
                         * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
                         *
                         * Emits a {Transfer} event.
                         */
                        function safeTransferFrom(address from, address to, uint256 tokenId) external;
                        /**
                         * @dev Transfers `tokenId` token from `from` to `to`.
                         *
                         * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
                         *
                         * Requirements:
                         *
                         * - `from` cannot be the zero address.
                         * - `to` cannot be the zero address.
                         * - `tokenId` token must be owned by `from`.
                         * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
                         *
                         * Emits a {Transfer} event.
                         */
                        function transferFrom(address from, address to, uint256 tokenId) external;
                        /**
                         * @dev Gives permission to `to` to transfer `tokenId` token to another account.
                         * The approval is cleared when the token is transferred.
                         *
                         * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
                         *
                         * Requirements:
                         *
                         * - The caller must own the token or be an approved operator.
                         * - `tokenId` must exist.
                         *
                         * Emits an {Approval} event.
                         */
                        function approve(address to, uint256 tokenId) external;
                        /**
                         * @dev Returns the account approved for `tokenId` token.
                         *
                         * Requirements:
                         *
                         * - `tokenId` must exist.
                         */
                        function getApproved(uint256 tokenId) external view returns (address operator);
                        /**
                         * @dev Approve or remove `operator` as an operator for the caller.
                         * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
                         *
                         * Requirements:
                         *
                         * - The `operator` cannot be the caller.
                         *
                         * Emits an {ApprovalForAll} event.
                         */
                        function setApprovalForAll(address operator, bool _approved) external;
                        /**
                         * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
                         *
                         * See {setApprovalForAll}
                         */
                        function isApprovedForAll(address owner, address operator) external view returns (bool);
                        /**
                          * @dev Safely transfers `tokenId` token from `from` to `to`.
                          *
                          * Requirements:
                          *
                          * - `from` cannot be the zero address.
                          * - `to` cannot be the zero address.
                          * - `tokenId` token must exist and be owned by `from`.
                          * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
                          * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
                          *
                          * Emits a {Transfer} event.
                          */
                        function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.7.0;
                    /**
                     * @dev Interface of the ERC165 standard, as defined in the
                     * https://eips.ethereum.org/EIPS/eip-165[EIP].
                     *
                     * Implementers can declare support of contract interfaces, which can then be
                     * queried by others ({ERC165Checker}).
                     *
                     * For an implementation, see {ERC165}.
                     */
                    interface IERC165 {
                        /**
                         * @dev Returns true if this contract implements the interface defined by
                         * `interfaceId`. See the corresponding
                         * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
                         * to learn more about how these ids are created.
                         *
                         * This function call must use less than 30 000 gas.
                         */
                        function supportsInterface(bytes4 interfaceId) external view returns (bool);
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title The interface for the Uniswap V3 Factory
                    /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees
                    interface IUniswapV3Factory {
                        /// @notice Emitted when the owner of the factory is changed
                        /// @param oldOwner The owner before the owner was changed
                        /// @param newOwner The owner after the owner was changed
                        event OwnerChanged(address indexed oldOwner, address indexed newOwner);
                        /// @notice Emitted when a pool is created
                        /// @param token0 The first token of the pool by address sort order
                        /// @param token1 The second token of the pool by address sort order
                        /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
                        /// @param tickSpacing The minimum number of ticks between initialized ticks
                        /// @param pool The address of the created pool
                        event PoolCreated(
                            address indexed token0,
                            address indexed token1,
                            uint24 indexed fee,
                            int24 tickSpacing,
                            address pool
                        );
                        /// @notice Emitted when a new fee amount is enabled for pool creation via the factory
                        /// @param fee The enabled fee, denominated in hundredths of a bip
                        /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee
                        event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);
                        /// @notice Returns the current owner of the factory
                        /// @dev Can be changed by the current owner via setOwner
                        /// @return The address of the factory owner
                        function owner() external view returns (address);
                        /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled
                        /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context
                        /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee
                        /// @return The tick spacing
                        function feeAmountTickSpacing(uint24 fee) external view returns (int24);
                        /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist
                        /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
                        /// @param tokenA The contract address of either token0 or token1
                        /// @param tokenB The contract address of the other token
                        /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
                        /// @return pool The pool address
                        function getPool(
                            address tokenA,
                            address tokenB,
                            uint24 fee
                        ) external view returns (address pool);
                        /// @notice Creates a pool for the given two tokens and fee
                        /// @param tokenA One of the two tokens in the desired pool
                        /// @param tokenB The other of the two tokens in the desired pool
                        /// @param fee The desired fee for the pool
                        /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
                        /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
                        /// are invalid.
                        /// @return pool The address of the newly created pool
                        function createPool(
                            address tokenA,
                            address tokenB,
                            uint24 fee
                        ) external returns (address pool);
                        /// @notice Updates the owner of the factory
                        /// @dev Must be called by the current owner
                        /// @param _owner The new owner of the factory
                        function setOwner(address _owner) external;
                        /// @notice Enables a fee amount with the given tickSpacing
                        /// @dev Fee amounts may never be removed once enabled
                        /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)
                        /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount
                        function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title Callback for IUniswapV3PoolActions#mint
                    /// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface
                    interface IUniswapV3MintCallback {
                        /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
                        /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
                        /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
                        /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
                        /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
                        /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
                        function uniswapV3MintCallback(
                            uint256 amount0Owed,
                            uint256 amount1Owed,
                            bytes calldata data
                        ) external;
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.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 {
                        /// @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) {
                            uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
                            require(absTick <= uint256(MAX_TICK), '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) {
                            // second inequality must be < because the price can never reach the price at the max tick
                            require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, '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;
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity =0.7.6;
                    import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
                    import './PoolAddress.sol';
                    /// @notice Provides validation for callbacks from Uniswap V3 Pools
                    library CallbackValidation {
                        /// @notice Returns the address of a valid Uniswap V3 Pool
                        /// @param factory The contract address of the Uniswap V3 factory
                        /// @param tokenA The contract address of either token0 or token1
                        /// @param tokenB The contract address of the other token
                        /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
                        /// @return pool The V3 pool contract address
                        function verifyCallback(
                            address factory,
                            address tokenA,
                            address tokenB,
                            uint24 fee
                        ) internal view returns (IUniswapV3Pool pool) {
                            return verifyCallback(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee));
                        }
                        /// @notice Returns the address of a valid Uniswap V3 Pool
                        /// @param factory The contract address of the Uniswap V3 factory
                        /// @param poolKey The identifying key of the V3 pool
                        /// @return pool The V3 pool contract address
                        function verifyCallback(address factory, PoolAddress.PoolKey memory poolKey)
                            internal
                            view
                            returns (IUniswapV3Pool pool)
                        {
                            pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey));
                            require(msg.sender == address(pool));
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
                    import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol';
                    /// @title Liquidity amount functions
                    /// @notice Provides functions for computing liquidity amounts from token amounts and prices
                    library LiquidityAmounts {
                        /// @notice Downcasts uint256 to uint128
                        /// @param x The uint258 to be downcasted
                        /// @return y The passed value, downcasted to uint128
                        function toUint128(uint256 x) private pure returns (uint128 y) {
                            require((y = uint128(x)) == x);
                        }
                        /// @notice Computes the amount of liquidity received for a given amount of token0 and price range
                        /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
                        /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
                        /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
                        /// @param amount0 The amount0 being sent in
                        /// @return liquidity The amount of returned liquidity
                        function getLiquidityForAmount0(
                            uint160 sqrtRatioAX96,
                            uint160 sqrtRatioBX96,
                            uint256 amount0
                        ) internal pure returns (uint128 liquidity) {
                            if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
                            uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
                            return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
                        }
                        /// @notice Computes the amount of liquidity received for a given amount of token1 and price range
                        /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
                        /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
                        /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
                        /// @param amount1 The amount1 being sent in
                        /// @return liquidity The amount of returned liquidity
                        function getLiquidityForAmount1(
                            uint160 sqrtRatioAX96,
                            uint160 sqrtRatioBX96,
                            uint256 amount1
                        ) internal pure returns (uint128 liquidity) {
                            if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
                            return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
                        }
                        /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
                        /// pool prices and the prices at the tick boundaries
                        /// @param sqrtRatioX96 A sqrt price representing the current pool prices
                        /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
                        /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
                        /// @param amount0 The amount of token0 being sent in
                        /// @param amount1 The amount of token1 being sent in
                        /// @return liquidity The maximum amount of liquidity received
                        function getLiquidityForAmounts(
                            uint160 sqrtRatioX96,
                            uint160 sqrtRatioAX96,
                            uint160 sqrtRatioBX96,
                            uint256 amount0,
                            uint256 amount1
                        ) internal pure returns (uint128 liquidity) {
                            if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
                            if (sqrtRatioX96 <= sqrtRatioAX96) {
                                liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
                            } else if (sqrtRatioX96 < sqrtRatioBX96) {
                                uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
                                uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
                                liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
                            } else {
                                liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
                            }
                        }
                        /// @notice Computes the amount of token0 for a given amount of liquidity and a price range
                        /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
                        /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
                        /// @param liquidity The liquidity being valued
                        /// @return amount0 The amount of token0
                        function getAmount0ForLiquidity(
                            uint160 sqrtRatioAX96,
                            uint160 sqrtRatioBX96,
                            uint128 liquidity
                        ) internal pure returns (uint256 amount0) {
                            if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
                            return
                                FullMath.mulDiv(
                                    uint256(liquidity) << FixedPoint96.RESOLUTION,
                                    sqrtRatioBX96 - sqrtRatioAX96,
                                    sqrtRatioBX96
                                ) / sqrtRatioAX96;
                        }
                        /// @notice Computes the amount of token1 for a given amount of liquidity and a price range
                        /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
                        /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
                        /// @param liquidity The liquidity being valued
                        /// @return amount1 The amount of token1
                        function getAmount1ForLiquidity(
                            uint160 sqrtRatioAX96,
                            uint160 sqrtRatioBX96,
                            uint128 liquidity
                        ) internal pure returns (uint256 amount1) {
                            if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
                            return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
                        }
                        /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
                        /// pool prices and the prices at the tick boundaries
                        /// @param sqrtRatioX96 A sqrt price representing the current pool prices
                        /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
                        /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
                        /// @param liquidity The liquidity being valued
                        /// @return amount0 The amount of token0
                        /// @return amount1 The amount of token1
                        function getAmountsForLiquidity(
                            uint160 sqrtRatioX96,
                            uint160 sqrtRatioAX96,
                            uint160 sqrtRatioBX96,
                            uint128 liquidity
                        ) internal pure returns (uint256 amount0, uint256 amount1) {
                            if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
                            if (sqrtRatioX96 <= sqrtRatioAX96) {
                                amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
                            } else if (sqrtRatioX96 < sqrtRatioBX96) {
                                amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
                                amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
                            } else {
                                amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
                            }
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.7.5;
                    import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
                    import '../interfaces/IPeripheryPayments.sol';
                    import '../interfaces/external/IWETH9.sol';
                    import '../libraries/TransferHelper.sol';
                    import './PeripheryImmutableState.sol';
                    abstract contract PeripheryPayments is IPeripheryPayments, PeripheryImmutableState {
                        receive() external payable {
                            require(msg.sender == WETH9, 'Not WETH9');
                        }
                        /// @inheritdoc IPeripheryPayments
                        function unwrapWETH9(uint256 amountMinimum, address recipient) external payable override {
                            uint256 balanceWETH9 = IWETH9(WETH9).balanceOf(address(this));
                            require(balanceWETH9 >= amountMinimum, 'Insufficient WETH9');
                            if (balanceWETH9 > 0) {
                                IWETH9(WETH9).withdraw(balanceWETH9);
                                TransferHelper.safeTransferETH(recipient, balanceWETH9);
                            }
                        }
                        /// @inheritdoc IPeripheryPayments
                        function sweepToken(
                            address token,
                            uint256 amountMinimum,
                            address recipient
                        ) external payable override {
                            uint256 balanceToken = IERC20(token).balanceOf(address(this));
                            require(balanceToken >= amountMinimum, 'Insufficient token');
                            if (balanceToken > 0) {
                                TransferHelper.safeTransfer(token, recipient, balanceToken);
                            }
                        }
                        /// @inheritdoc IPeripheryPayments
                        function refundETH() external payable override {
                            if (address(this).balance > 0) TransferHelper.safeTransferETH(msg.sender, address(this).balance);
                        }
                        /// @param token The token to pay
                        /// @param payer The entity that must pay
                        /// @param recipient The entity that will receive payment
                        /// @param value The amount to pay
                        function pay(
                            address token,
                            address payer,
                            address recipient,
                            uint256 value
                        ) internal {
                            if (token == WETH9 && address(this).balance >= value) {
                                // pay with WETH9
                                IWETH9(WETH9).deposit{value: value}(); // wrap only what is needed to pay
                                IWETH9(WETH9).transfer(recipient, value);
                            } else if (payer == address(this)) {
                                // pay with tokens already in the contract (for the exact input multihop case)
                                TransferHelper.safeTransfer(token, recipient, value);
                            } else {
                                // pull payment
                                TransferHelper.safeTransferFrom(token, payer, recipient, value);
                            }
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.4.0;
                    /// @title FixedPoint96
                    /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
                    /// @dev Used in SqrtPriceMath.sol
                    library FixedPoint96 {
                        uint8 internal constant RESOLUTION = 96;
                        uint256 internal constant Q96 = 0x1000000000000000000000000;
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.7.0;
                    /**
                     * @dev Interface of the ERC20 standard as defined in the EIP.
                     */
                    interface IERC20 {
                        /**
                         * @dev Returns the amount of tokens in existence.
                         */
                        function totalSupply() external view returns (uint256);
                        /**
                         * @dev Returns the amount of tokens owned by `account`.
                         */
                        function balanceOf(address account) external view returns (uint256);
                        /**
                         * @dev Moves `amount` tokens from the caller's account to `recipient`.
                         *
                         * Returns a boolean value indicating whether the operation succeeded.
                         *
                         * Emits a {Transfer} event.
                         */
                        function transfer(address recipient, uint256 amount) external returns (bool);
                        /**
                         * @dev Returns the remaining number of tokens that `spender` will be
                         * allowed to spend on behalf of `owner` through {transferFrom}. This is
                         * zero by default.
                         *
                         * This value changes when {approve} or {transferFrom} are called.
                         */
                        function allowance(address owner, address spender) external view returns (uint256);
                        /**
                         * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                         *
                         * Returns a boolean value indicating whether the operation succeeded.
                         *
                         * IMPORTANT: Beware that changing an allowance with this method brings the risk
                         * that someone may use both the old and the new allowance by unfortunate
                         * transaction ordering. One possible solution to mitigate this race
                         * condition is to first reduce the spender's allowance to 0 and set the
                         * desired value afterwards:
                         * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                         *
                         * Emits an {Approval} event.
                         */
                        function approve(address spender, uint256 amount) external returns (bool);
                        /**
                         * @dev Moves `amount` tokens from `sender` to `recipient` using the
                         * allowance mechanism. `amount` is then deducted from the caller's
                         * allowance.
                         *
                         * Returns a boolean value indicating whether the operation succeeded.
                         *
                         * Emits a {Transfer} event.
                         */
                        function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
                        /**
                         * @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);
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity =0.7.6;
                    import '@openzeppelin/contracts/token/ERC20/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;
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.6.0;
                    import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
                    library TransferHelper {
                        /// @notice Transfers tokens from the targeted address to the given destination
                        /// @notice Errors with 'STF' if transfer fails
                        /// @param token The contract address of the token to be transferred
                        /// @param from The originating address from which the tokens will be transferred
                        /// @param to The destination address of the transfer
                        /// @param value The amount to be transferred
                        function safeTransferFrom(
                            address token,
                            address from,
                            address to,
                            uint256 value
                        ) internal {
                            (bool success, bytes memory data) =
                                token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
                            require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
                        }
                        /// @notice Transfers tokens from msg.sender to a recipient
                        /// @dev Errors with ST if transfer fails
                        /// @param token The contract address of the token which will be transferred
                        /// @param to The recipient of the transfer
                        /// @param value The value of the transfer
                        function safeTransfer(
                            address token,
                            address to,
                            uint256 value
                        ) internal {
                            (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
                            require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
                        }
                        /// @notice Approves the stipulated contract to spend the given allowance in the given token
                        /// @dev Errors with 'SA' if transfer fails
                        /// @param token The contract address of the token to be approved
                        /// @param to The target of the approval
                        /// @param value The amount of the given token the target will be allowed to spend
                        function safeApprove(
                            address token,
                            address to,
                            uint256 value
                        ) internal {
                            (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
                            require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');
                        }
                        /// @notice Transfers ETH to the recipient address
                        /// @dev Fails with `STE`
                        /// @param to The destination of the transfer
                        /// @param value The value to be transferred
                        function safeTransferETH(address to, uint256 value) internal {
                            (bool success, ) = to.call{value: value}(new bytes(0));
                            require(success, 'STE');
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.7.5;
                    pragma abicoder v2;
                    /// @title Multicall interface
                    /// @notice Enables calling multiple methods in a single call to the contract
                    interface IMulticall {
                        /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
                        /// @dev The `msg.value` should not be trusted for any method callable from multicall.
                        /// @param data The encoded function data for each of the calls to make to this contract
                        /// @return results The results from each of the calls passed in via data
                        function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.7.0;
                    import "../../utils/Context.sol";
                    import "./IERC721.sol";
                    import "./IERC721Metadata.sol";
                    import "./IERC721Enumerable.sol";
                    import "./IERC721Receiver.sol";
                    import "../../introspection/ERC165.sol";
                    import "../../math/SafeMath.sol";
                    import "../../utils/Address.sol";
                    import "../../utils/EnumerableSet.sol";
                    import "../../utils/EnumerableMap.sol";
                    import "../../utils/Strings.sol";
                    /**
                     * @title ERC721 Non-Fungible Token Standard basic implementation
                     * @dev see https://eips.ethereum.org/EIPS/eip-721
                     */
                    contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
                        using SafeMath for uint256;
                        using Address for address;
                        using EnumerableSet for EnumerableSet.UintSet;
                        using EnumerableMap for EnumerableMap.UintToAddressMap;
                        using Strings for uint256;
                        // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
                        // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
                        bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
                        // Mapping from holder address to their (enumerable) set of owned tokens
                        mapping (address => EnumerableSet.UintSet) private _holderTokens;
                        // Enumerable mapping from token ids to their owners
                        EnumerableMap.UintToAddressMap private _tokenOwners;
                        // Mapping from token ID to approved address
                        mapping (uint256 => address) private _tokenApprovals;
                        // Mapping from owner to operator approvals
                        mapping (address => mapping (address => bool)) private _operatorApprovals;
                        // Token name
                        string private _name;
                        // Token symbol
                        string private _symbol;
                        // Optional mapping for token URIs
                        mapping (uint256 => string) private _tokenURIs;
                        // Base URI
                        string private _baseURI;
                        /*
                         *     bytes4(keccak256('balanceOf(address)')) == 0x70a08231
                         *     bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
                         *     bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
                         *     bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
                         *     bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
                         *     bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
                         *     bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
                         *     bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
                         *     bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
                         *
                         *     => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
                         *        0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
                         */
                        bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
                        /*
                         *     bytes4(keccak256('name()')) == 0x06fdde03
                         *     bytes4(keccak256('symbol()')) == 0x95d89b41
                         *     bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
                         *
                         *     => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
                         */
                        bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
                        /*
                         *     bytes4(keccak256('totalSupply()')) == 0x18160ddd
                         *     bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
                         *     bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
                         *
                         *     => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
                         */
                        bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
                        /**
                         * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
                         */
                        constructor (string memory name_, string memory symbol_) {
                            _name = name_;
                            _symbol = symbol_;
                            // register the supported interfaces to conform to ERC721 via ERC165
                            _registerInterface(_INTERFACE_ID_ERC721);
                            _registerInterface(_INTERFACE_ID_ERC721_METADATA);
                            _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
                        }
                        /**
                         * @dev See {IERC721-balanceOf}.
                         */
                        function balanceOf(address owner) public view virtual override returns (uint256) {
                            require(owner != address(0), "ERC721: balance query for the zero address");
                            return _holderTokens[owner].length();
                        }
                        /**
                         * @dev See {IERC721-ownerOf}.
                         */
                        function ownerOf(uint256 tokenId) public view virtual override returns (address) {
                            return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
                        }
                        /**
                         * @dev See {IERC721Metadata-name}.
                         */
                        function name() public view virtual override returns (string memory) {
                            return _name;
                        }
                        /**
                         * @dev See {IERC721Metadata-symbol}.
                         */
                        function symbol() public view virtual override returns (string memory) {
                            return _symbol;
                        }
                        /**
                         * @dev See {IERC721Metadata-tokenURI}.
                         */
                        function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
                            require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
                            string memory _tokenURI = _tokenURIs[tokenId];
                            string memory base = baseURI();
                            // If there is no base URI, return the token URI.
                            if (bytes(base).length == 0) {
                                return _tokenURI;
                            }
                            // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
                            if (bytes(_tokenURI).length > 0) {
                                return string(abi.encodePacked(base, _tokenURI));
                            }
                            // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
                            return string(abi.encodePacked(base, tokenId.toString()));
                        }
                        /**
                        * @dev Returns the base URI set via {_setBaseURI}. This will be
                        * automatically added as a prefix in {tokenURI} to each token's URI, or
                        * to the token ID if no specific URI is set for that token ID.
                        */
                        function baseURI() public view virtual returns (string memory) {
                            return _baseURI;
                        }
                        /**
                         * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
                         */
                        function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
                            return _holderTokens[owner].at(index);
                        }
                        /**
                         * @dev See {IERC721Enumerable-totalSupply}.
                         */
                        function totalSupply() public view virtual override returns (uint256) {
                            // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
                            return _tokenOwners.length();
                        }
                        /**
                         * @dev See {IERC721Enumerable-tokenByIndex}.
                         */
                        function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
                            (uint256 tokenId, ) = _tokenOwners.at(index);
                            return tokenId;
                        }
                        /**
                         * @dev See {IERC721-approve}.
                         */
                        function approve(address to, uint256 tokenId) public virtual override {
                            address owner = ERC721.ownerOf(tokenId);
                            require(to != owner, "ERC721: approval to current owner");
                            require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
                                "ERC721: approve caller is not owner nor approved for all"
                            );
                            _approve(to, tokenId);
                        }
                        /**
                         * @dev See {IERC721-getApproved}.
                         */
                        function getApproved(uint256 tokenId) public view virtual override returns (address) {
                            require(_exists(tokenId), "ERC721: approved query for nonexistent token");
                            return _tokenApprovals[tokenId];
                        }
                        /**
                         * @dev See {IERC721-setApprovalForAll}.
                         */
                        function setApprovalForAll(address operator, bool approved) public virtual override {
                            require(operator != _msgSender(), "ERC721: approve to caller");
                            _operatorApprovals[_msgSender()][operator] = approved;
                            emit ApprovalForAll(_msgSender(), operator, approved);
                        }
                        /**
                         * @dev See {IERC721-isApprovedForAll}.
                         */
                        function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
                            return _operatorApprovals[owner][operator];
                        }
                        /**
                         * @dev See {IERC721-transferFrom}.
                         */
                        function transferFrom(address from, address to, uint256 tokenId) public virtual override {
                            //solhint-disable-next-line max-line-length
                            require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
                            _transfer(from, to, tokenId);
                        }
                        /**
                         * @dev See {IERC721-safeTransferFrom}.
                         */
                        function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
                            safeTransferFrom(from, to, tokenId, "");
                        }
                        /**
                         * @dev See {IERC721-safeTransferFrom}.
                         */
                        function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
                            require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
                            _safeTransfer(from, to, tokenId, _data);
                        }
                        /**
                         * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
                         * are aware of the ERC721 protocol to prevent tokens from being forever locked.
                         *
                         * `_data` is additional data, it has no specified format and it is sent in call to `to`.
                         *
                         * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
                         * implement alternative mechanisms to perform token transfer, such as signature-based.
                         *
                         * Requirements:
                         *
                         * - `from` cannot be the zero address.
                         * - `to` cannot be the zero address.
                         * - `tokenId` token must exist and be owned by `from`.
                         * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
                         *
                         * Emits a {Transfer} event.
                         */
                        function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
                            _transfer(from, to, tokenId);
                            require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
                        }
                        /**
                         * @dev Returns whether `tokenId` exists.
                         *
                         * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
                         *
                         * Tokens start existing when they are minted (`_mint`),
                         * and stop existing when they are burned (`_burn`).
                         */
                        function _exists(uint256 tokenId) internal view virtual returns (bool) {
                            return _tokenOwners.contains(tokenId);
                        }
                        /**
                         * @dev Returns whether `spender` is allowed to manage `tokenId`.
                         *
                         * Requirements:
                         *
                         * - `tokenId` must exist.
                         */
                        function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
                            require(_exists(tokenId), "ERC721: operator query for nonexistent token");
                            address owner = ERC721.ownerOf(tokenId);
                            return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
                        }
                        /**
                         * @dev Safely mints `tokenId` and transfers it to `to`.
                         *
                         * Requirements:
                         d*
                         * - `tokenId` must not exist.
                         * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
                         *
                         * Emits a {Transfer} event.
                         */
                        function _safeMint(address to, uint256 tokenId) internal virtual {
                            _safeMint(to, tokenId, "");
                        }
                        /**
                         * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
                         * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
                         */
                        function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
                            _mint(to, tokenId);
                            require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
                        }
                        /**
                         * @dev Mints `tokenId` and transfers it to `to`.
                         *
                         * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
                         *
                         * Requirements:
                         *
                         * - `tokenId` must not exist.
                         * - `to` cannot be the zero address.
                         *
                         * Emits a {Transfer} event.
                         */
                        function _mint(address to, uint256 tokenId) internal virtual {
                            require(to != address(0), "ERC721: mint to the zero address");
                            require(!_exists(tokenId), "ERC721: token already minted");
                            _beforeTokenTransfer(address(0), to, tokenId);
                            _holderTokens[to].add(tokenId);
                            _tokenOwners.set(tokenId, to);
                            emit Transfer(address(0), to, tokenId);
                        }
                        /**
                         * @dev Destroys `tokenId`.
                         * The approval is cleared when the token is burned.
                         *
                         * Requirements:
                         *
                         * - `tokenId` must exist.
                         *
                         * Emits a {Transfer} event.
                         */
                        function _burn(uint256 tokenId) internal virtual {
                            address owner = ERC721.ownerOf(tokenId); // internal owner
                            _beforeTokenTransfer(owner, address(0), tokenId);
                            // Clear approvals
                            _approve(address(0), tokenId);
                            // Clear metadata (if any)
                            if (bytes(_tokenURIs[tokenId]).length != 0) {
                                delete _tokenURIs[tokenId];
                            }
                            _holderTokens[owner].remove(tokenId);
                            _tokenOwners.remove(tokenId);
                            emit Transfer(owner, address(0), tokenId);
                        }
                        /**
                         * @dev Transfers `tokenId` from `from` to `to`.
                         *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
                         *
                         * Requirements:
                         *
                         * - `to` cannot be the zero address.
                         * - `tokenId` token must be owned by `from`.
                         *
                         * Emits a {Transfer} event.
                         */
                        function _transfer(address from, address to, uint256 tokenId) internal virtual {
                            require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
                            require(to != address(0), "ERC721: transfer to the zero address");
                            _beforeTokenTransfer(from, to, tokenId);
                            // Clear approvals from the previous owner
                            _approve(address(0), tokenId);
                            _holderTokens[from].remove(tokenId);
                            _holderTokens[to].add(tokenId);
                            _tokenOwners.set(tokenId, to);
                            emit Transfer(from, to, tokenId);
                        }
                        /**
                         * @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
                         *
                         * Requirements:
                         *
                         * - `tokenId` must exist.
                         */
                        function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
                            require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
                            _tokenURIs[tokenId] = _tokenURI;
                        }
                        /**
                         * @dev Internal function to set the base URI for all token IDs. It is
                         * automatically added as a prefix to the value returned in {tokenURI},
                         * or to the token ID if {tokenURI} is empty.
                         */
                        function _setBaseURI(string memory baseURI_) internal virtual {
                            _baseURI = baseURI_;
                        }
                        /**
                         * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
                         * The call is not executed if the target address is not a contract.
                         *
                         * @param from address representing the previous owner of the given token ID
                         * @param to target address that will receive the tokens
                         * @param tokenId uint256 ID of the token to be transferred
                         * @param _data bytes optional data to send along with the call
                         * @return bool whether the call correctly returned the expected magic value
                         */
                        function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
                            private returns (bool)
                        {
                            if (!to.isContract()) {
                                return true;
                            }
                            bytes memory returndata = to.functionCall(abi.encodeWithSelector(
                                IERC721Receiver(to).onERC721Received.selector,
                                _msgSender(),
                                from,
                                tokenId,
                                _data
                            ), "ERC721: transfer to non ERC721Receiver implementer");
                            bytes4 retval = abi.decode(returndata, (bytes4));
                            return (retval == _ERC721_RECEIVED);
                        }
                        /**
                         * @dev Approve `to` to operate on `tokenId`
                         *
                         * Emits an {Approval} event.
                         */
                        function _approve(address to, uint256 tokenId) internal virtual {
                            _tokenApprovals[tokenId] = to;
                            emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
                        }
                        /**
                         * @dev Hook that is called before any token transfer. This includes minting
                         * and burning.
                         *
                         * Calling conditions:
                         *
                         * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
                         * transferred to `to`.
                         * - When `from` is zero, `tokenId` will be minted for `to`.
                         * - When `to` is zero, ``from``'s `tokenId` will be burned.
                         * - `from` cannot be the zero address.
                         * - `to` cannot be the zero address.
                         *
                         * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
                         */
                        function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.7.0;
                    /**
                     * @dev Collection of functions related to the address type
                     */
                    library Address {
                        /**
                         * @dev Returns true if `account` is a contract.
                         *
                         * [IMPORTANT]
                         * ====
                         * It is unsafe to assume that an address for which this function returns
                         * false is an externally-owned account (EOA) and not a contract.
                         *
                         * Among others, `isContract` will return false for the following
                         * types of addresses:
                         *
                         *  - an externally-owned account
                         *  - a contract in construction
                         *  - an address where a contract will be created
                         *  - an address where a contract lived, but was destroyed
                         * ====
                         */
                        function isContract(address account) internal view returns (bool) {
                            // This method relies on extcodesize, which returns 0 for contracts in
                            // construction, since the code is only stored at the end of the
                            // constructor execution.
                            uint256 size;
                            // solhint-disable-next-line no-inline-assembly
                            assembly { size := extcodesize(account) }
                            return size > 0;
                        }
                        /**
                         * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                         * `recipient`, forwarding all available gas and reverting on errors.
                         *
                         * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                         * of certain opcodes, possibly making contracts go over the 2300 gas limit
                         * imposed by `transfer`, making them unable to receive funds via
                         * `transfer`. {sendValue} removes this limitation.
                         *
                         * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                         *
                         * IMPORTANT: because control is transferred to `recipient`, care must be
                         * taken to not create reentrancy vulnerabilities. Consider using
                         * {ReentrancyGuard} or the
                         * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                         */
                        function sendValue(address payable recipient, uint256 amount) internal {
                            require(address(this).balance >= amount, "Address: insufficient balance");
                            // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
                            (bool success, ) = recipient.call{ value: amount }("");
                            require(success, "Address: unable to send value, recipient may have reverted");
                        }
                        /**
                         * @dev Performs a Solidity function call using a low level `call`. A
                         * plain`call` is an unsafe replacement for a function call: use this
                         * function instead.
                         *
                         * If `target` reverts with a revert reason, it is bubbled up by this
                         * function (like regular Solidity function calls).
                         *
                         * Returns the raw returned data. To convert to the expected return value,
                         * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                         *
                         * Requirements:
                         *
                         * - `target` must be a contract.
                         * - calling `target` with `data` must not revert.
                         *
                         * _Available since v3.1._
                         */
                        function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                          return functionCall(target, data, "Address: low-level call failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                         * `errorMessage` as a fallback revert reason when `target` reverts.
                         *
                         * _Available since v3.1._
                         */
                        function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                            return functionCallWithValue(target, data, 0, errorMessage);
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                         * but also transferring `value` wei to `target`.
                         *
                         * Requirements:
                         *
                         * - the calling contract must have an ETH balance of at least `value`.
                         * - the called Solidity function must be `payable`.
                         *
                         * _Available since v3.1._
                         */
                        function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                            return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                         * with `errorMessage` as a fallback revert reason when `target` reverts.
                         *
                         * _Available since v3.1._
                         */
                        function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
                            require(address(this).balance >= value, "Address: insufficient balance for call");
                            require(isContract(target), "Address: call to non-contract");
                            // solhint-disable-next-line avoid-low-level-calls
                            (bool success, bytes memory returndata) = target.call{ value: value }(data);
                            return _verifyCallResult(success, returndata, errorMessage);
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                         * but performing a static call.
                         *
                         * _Available since v3.3._
                         */
                        function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                            return functionStaticCall(target, data, "Address: low-level static call failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                         * but performing a static call.
                         *
                         * _Available since v3.3._
                         */
                        function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
                            require(isContract(target), "Address: static call to non-contract");
                            // solhint-disable-next-line avoid-low-level-calls
                            (bool success, bytes memory returndata) = target.staticcall(data);
                            return _verifyCallResult(success, returndata, errorMessage);
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                         * but performing a delegate call.
                         *
                         * _Available since v3.4._
                         */
                        function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                            return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                        }
                        /**
                         * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                         * but performing a delegate call.
                         *
                         * _Available since v3.4._
                         */
                        function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                            require(isContract(target), "Address: delegate call to non-contract");
                            // solhint-disable-next-line avoid-low-level-calls
                            (bool success, bytes memory returndata) = target.delegatecall(data);
                            return _verifyCallResult(success, returndata, errorMessage);
                        }
                        function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
                            if (success) {
                                return returndata;
                            } else {
                                // 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
                                    // solhint-disable-next-line no-inline-assembly
                                    assembly {
                                        let returndata_size := mload(returndata)
                                        revert(add(32, returndata), returndata_size)
                                    }
                                } else {
                                    revert(errorMessage);
                                }
                            }
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.7.0;
                    /// @title Function for getting the current chain ID
                    library ChainId {
                        /// @dev Gets the current chain ID
                        /// @return chainId The current chain ID
                        function get() internal pure returns (uint256 chainId) {
                            assembly {
                                chainId := chainid()
                            }
                        }
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title Interface for verifying contract-based account signatures
                    /// @notice Interface that verifies provided signature for the data
                    /// @dev Interface defined by EIP-1271
                    interface IERC1271 {
                        /// @notice Returns whether the provided signature is valid for the provided data
                        /// @dev MUST return the bytes4 magic value 0x1626ba7e when function passes.
                        /// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5).
                        /// MUST allow external calls.
                        /// @param hash Hash of the data to be signed
                        /// @param signature Signature byte array associated with _data
                        /// @return magicValue The bytes4 magic value 0x1626ba7e
                        function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity =0.7.6;
                    /// @title Function for getting block timestamp
                    /// @dev Base contract that is overridden for tests
                    abstract contract BlockTimestamp {
                        /// @dev Method that exists purely to be overridden for tests
                        /// @return The current block timestamp
                        function _blockTimestamp() internal view virtual returns (uint256) {
                            return block.timestamp;
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity >=0.6.0 <0.8.0;
                    /*
                     * @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 GSN 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 payable) {
                            return msg.sender;
                        }
                        function _msgData() internal view virtual returns (bytes memory) {
                            this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
                            return msg.data;
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.7.0;
                    /**
                     * @title ERC721 token receiver interface
                     * @dev Interface for any contract that wants to support safeTransfers
                     * from ERC721 asset contracts.
                     */
                    interface IERC721Receiver {
                        /**
                         * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
                         * by `operator` from `from`, this function is called.
                         *
                         * It must return its Solidity selector to confirm the token transfer.
                         * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
                         *
                         * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
                         */
                        function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.7.0;
                    import "./IERC165.sol";
                    /**
                     * @dev Implementation of the {IERC165} interface.
                     *
                     * Contracts may inherit from this and call {_registerInterface} to declare
                     * their support of an interface.
                     */
                    abstract contract ERC165 is IERC165 {
                        /*
                         * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
                         */
                        bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
                        /**
                         * @dev Mapping of interface ids to whether or not it's supported.
                         */
                        mapping(bytes4 => bool) private _supportedInterfaces;
                        constructor () {
                            // Derived contracts need only register support for their own interfaces,
                            // we register support for ERC165 itself here
                            _registerInterface(_INTERFACE_ID_ERC165);
                        }
                        /**
                         * @dev See {IERC165-supportsInterface}.
                         *
                         * Time complexity O(1), guaranteed to always use less than 30 000 gas.
                         */
                        function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
                            return _supportedInterfaces[interfaceId];
                        }
                        /**
                         * @dev Registers the contract as an implementer of the interface defined by
                         * `interfaceId`. Support of the actual ERC165 interface is automatic and
                         * registering its interface id is not required.
                         *
                         * See {IERC165-supportsInterface}.
                         *
                         * Requirements:
                         *
                         * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
                         */
                        function _registerInterface(bytes4 interfaceId) internal virtual {
                            require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
                            _supportedInterfaces[interfaceId] = true;
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.7.0;
                    /**
                     * @dev Wrappers over Solidity's arithmetic operations with added overflow
                     * checks.
                     *
                     * Arithmetic operations in Solidity wrap on overflow. This can easily result
                     * in bugs, because programmers usually assume that an overflow raises an
                     * error, which is the standard behavior in high level programming languages.
                     * `SafeMath` restores this intuition by reverting the transaction when an
                     * operation overflows.
                     *
                     * Using this library instead of the unchecked operations eliminates an entire
                     * class of bugs, so it's recommended to use it always.
                     */
                    library SafeMath {
                        /**
                         * @dev Returns the addition of two unsigned integers, with an overflow flag.
                         *
                         * _Available since v3.4._
                         */
                        function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                            uint256 c = a + b;
                            if (c < a) return (false, 0);
                            return (true, c);
                        }
                        /**
                         * @dev Returns the substraction of two unsigned integers, with an overflow flag.
                         *
                         * _Available since v3.4._
                         */
                        function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                            if (b > a) return (false, 0);
                            return (true, a - b);
                        }
                        /**
                         * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
                         *
                         * _Available since v3.4._
                         */
                        function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                            // 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.
                         *
                         * _Available since v3.4._
                         */
                        function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                            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.
                         *
                         * _Available since v3.4._
                         */
                        function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                            if (b == 0) return (false, 0);
                            return (true, a % b);
                        }
                        /**
                         * @dev Returns the addition of two unsigned integers, reverting on
                         * overflow.
                         *
                         * Counterpart to Solidity's `+` operator.
                         *
                         * Requirements:
                         *
                         * - Addition cannot overflow.
                         */
                        function add(uint256 a, uint256 b) internal pure returns (uint256) {
                            uint256 c = a + b;
                            require(c >= a, "SafeMath: addition overflow");
                            return c;
                        }
                        /**
                         * @dev Returns the subtraction of two unsigned integers, reverting on
                         * overflow (when the result is negative).
                         *
                         * Counterpart to Solidity's `-` operator.
                         *
                         * Requirements:
                         *
                         * - Subtraction cannot overflow.
                         */
                        function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                            require(b <= a, "SafeMath: subtraction overflow");
                            return a - b;
                        }
                        /**
                         * @dev Returns the multiplication of two unsigned integers, reverting on
                         * overflow.
                         *
                         * Counterpart to Solidity's `*` operator.
                         *
                         * Requirements:
                         *
                         * - Multiplication cannot overflow.
                         */
                        function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                            if (a == 0) return 0;
                            uint256 c = a * b;
                            require(c / a == b, "SafeMath: multiplication overflow");
                            return c;
                        }
                        /**
                         * @dev Returns the integer division of two unsigned integers, reverting on
                         * division by zero. The result is rounded towards zero.
                         *
                         * Counterpart to Solidity's `/` operator. Note: this function uses a
                         * `revert` opcode (which leaves remaining gas untouched) while Solidity
                         * uses an invalid opcode to revert (consuming all remaining gas).
                         *
                         * Requirements:
                         *
                         * - The divisor cannot be zero.
                         */
                        function div(uint256 a, uint256 b) internal pure returns (uint256) {
                            require(b > 0, "SafeMath: division by zero");
                            return a / b;
                        }
                        /**
                         * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                         * reverting when dividing by zero.
                         *
                         * Counterpart to Solidity's `%` operator. This function uses a `revert`
                         * opcode (which leaves remaining gas untouched) while Solidity uses an
                         * invalid opcode to revert (consuming all remaining gas).
                         *
                         * Requirements:
                         *
                         * - The divisor cannot be zero.
                         */
                        function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                            require(b > 0, "SafeMath: modulo by zero");
                            return a % b;
                        }
                        /**
                         * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                         * overflow (when the result is negative).
                         *
                         * CAUTION: This function is deprecated because it requires allocating memory for the error
                         * message unnecessarily. For custom revert reasons use {trySub}.
                         *
                         * Counterpart to Solidity's `-` operator.
                         *
                         * Requirements:
                         *
                         * - Subtraction cannot overflow.
                         */
                        function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                            require(b <= a, errorMessage);
                            return a - b;
                        }
                        /**
                         * @dev Returns the integer division of two unsigned integers, reverting with custom message on
                         * division by zero. The result is rounded towards zero.
                         *
                         * CAUTION: This function is deprecated because it requires allocating memory for the error
                         * message unnecessarily. For custom revert reasons use {tryDiv}.
                         *
                         * Counterpart to Solidity's `/` operator. Note: this function uses a
                         * `revert` opcode (which leaves remaining gas untouched) while Solidity
                         * uses an invalid opcode to revert (consuming all remaining gas).
                         *
                         * Requirements:
                         *
                         * - The divisor cannot be zero.
                         */
                        function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                            require(b > 0, errorMessage);
                            return a / b;
                        }
                        /**
                         * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                         * reverting with custom message when dividing by zero.
                         *
                         * CAUTION: This function is deprecated because it requires allocating memory for the error
                         * message unnecessarily. For custom revert reasons use {tryMod}.
                         *
                         * Counterpart to Solidity's `%` operator. This function uses a `revert`
                         * opcode (which leaves remaining gas untouched) while Solidity uses an
                         * invalid opcode to revert (consuming all remaining gas).
                         *
                         * Requirements:
                         *
                         * - The divisor cannot be zero.
                         */
                        function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                            require(b > 0, errorMessage);
                            return a % b;
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.7.0;
                    /**
                     * @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.
                     *
                     * ```
                     * 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.
                     */
                    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 of the value in the `values` array, plus 1 because index 0
                            // means a value is not in the set.
                            mapping (bytes32 => uint256) _indexes;
                        }
                        /**
                         * @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._indexes[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 read and store the value's index to prevent multiple reads from the same storage slot
                            uint256 valueIndex = set._indexes[value];
                            if (valueIndex != 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 toDeleteIndex = valueIndex - 1;
                                uint256 lastIndex = set._values.length - 1;
                                // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
                                // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
                                bytes32 lastvalue = set._values[lastIndex];
                                // Move the last value to the index where the value to delete is
                                set._values[toDeleteIndex] = lastvalue;
                                // Update the index for the moved value
                                set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
                                // Delete the slot where the moved value was stored
                                set._values.pop();
                                // Delete the index for the deleted slot
                                delete set._indexes[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._indexes[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) {
                            require(set._values.length > index, "EnumerableSet: index out of bounds");
                            return set._values[index];
                        }
                        // 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);
                        }
                        // 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))));
                        }
                        // 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 on 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));
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.7.0;
                    /**
                     * @dev Library for managing an enumerable variant of Solidity's
                     * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
                     * type.
                     *
                     * Maps have the following properties:
                     *
                     * - Entries are added, removed, and checked for existence in constant time
                     * (O(1)).
                     * - Entries are enumerated in O(n). No guarantees are made on the ordering.
                     *
                     * ```
                     * contract Example {
                     *     // Add the library methods
                     *     using EnumerableMap for EnumerableMap.UintToAddressMap;
                     *
                     *     // Declare a set state variable
                     *     EnumerableMap.UintToAddressMap private myMap;
                     * }
                     * ```
                     *
                     * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
                     * supported.
                     */
                    library EnumerableMap {
                        // To implement this library for multiple types with as little code
                        // repetition as possible, we write it in terms of a generic Map type with
                        // bytes32 keys and values.
                        // The Map implementation uses private functions, and user-facing
                        // implementations (such as Uint256ToAddressMap) are just wrappers around
                        // the underlying Map.
                        // This means that we can only create new EnumerableMaps for types that fit
                        // in bytes32.
                        struct MapEntry {
                            bytes32 _key;
                            bytes32 _value;
                        }
                        struct Map {
                            // Storage of map keys and values
                            MapEntry[] _entries;
                            // Position of the entry defined by a key in the `entries` array, plus 1
                            // because index 0 means a key is not in the map.
                            mapping (bytes32 => uint256) _indexes;
                        }
                        /**
                         * @dev Adds a key-value pair to a map, or updates the value for an existing
                         * key. O(1).
                         *
                         * Returns true if the key was added to the map, that is if it was not
                         * already present.
                         */
                        function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
                            // We read and store the key's index to prevent multiple reads from the same storage slot
                            uint256 keyIndex = map._indexes[key];
                            if (keyIndex == 0) { // Equivalent to !contains(map, key)
                                map._entries.push(MapEntry({ _key: key, _value: value }));
                                // The entry is stored at length-1, but we add 1 to all indexes
                                // and use 0 as a sentinel value
                                map._indexes[key] = map._entries.length;
                                return true;
                            } else {
                                map._entries[keyIndex - 1]._value = value;
                                return false;
                            }
                        }
                        /**
                         * @dev Removes a key-value pair from a map. O(1).
                         *
                         * Returns true if the key was removed from the map, that is if it was present.
                         */
                        function _remove(Map storage map, bytes32 key) private returns (bool) {
                            // We read and store the key's index to prevent multiple reads from the same storage slot
                            uint256 keyIndex = map._indexes[key];
                            if (keyIndex != 0) { // Equivalent to contains(map, key)
                                // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
                                // in the array, and then remove the last entry (sometimes called as 'swap and pop').
                                // This modifies the order of the array, as noted in {at}.
                                uint256 toDeleteIndex = keyIndex - 1;
                                uint256 lastIndex = map._entries.length - 1;
                                // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
                                // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
                                MapEntry storage lastEntry = map._entries[lastIndex];
                                // Move the last entry to the index where the entry to delete is
                                map._entries[toDeleteIndex] = lastEntry;
                                // Update the index for the moved entry
                                map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
                                // Delete the slot where the moved entry was stored
                                map._entries.pop();
                                // Delete the index for the deleted slot
                                delete map._indexes[key];
                                return true;
                            } else {
                                return false;
                            }
                        }
                        /**
                         * @dev Returns true if the key is in the map. O(1).
                         */
                        function _contains(Map storage map, bytes32 key) private view returns (bool) {
                            return map._indexes[key] != 0;
                        }
                        /**
                         * @dev Returns the number of key-value pairs in the map. O(1).
                         */
                        function _length(Map storage map) private view returns (uint256) {
                            return map._entries.length;
                        }
                       /**
                        * @dev Returns the key-value pair stored at position `index` in the map. O(1).
                        *
                        * Note that there are no guarantees on the ordering of entries inside the
                        * array, and it may change when more entries are added or removed.
                        *
                        * Requirements:
                        *
                        * - `index` must be strictly less than {length}.
                        */
                        function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
                            require(map._entries.length > index, "EnumerableMap: index out of bounds");
                            MapEntry storage entry = map._entries[index];
                            return (entry._key, entry._value);
                        }
                        /**
                         * @dev Tries to returns the value associated with `key`.  O(1).
                         * Does not revert if `key` is not in the map.
                         */
                        function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
                            uint256 keyIndex = map._indexes[key];
                            if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
                            return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
                        }
                        /**
                         * @dev Returns the value associated with `key`.  O(1).
                         *
                         * Requirements:
                         *
                         * - `key` must be in the map.
                         */
                        function _get(Map storage map, bytes32 key) private view returns (bytes32) {
                            uint256 keyIndex = map._indexes[key];
                            require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
                            return map._entries[keyIndex - 1]._value; // All indexes are 1-based
                        }
                        /**
                         * @dev Same as {_get}, with a custom error message when `key` is not in the map.
                         *
                         * CAUTION: This function is deprecated because it requires allocating memory for the error
                         * message unnecessarily. For custom revert reasons use {_tryGet}.
                         */
                        function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
                            uint256 keyIndex = map._indexes[key];
                            require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
                            return map._entries[keyIndex - 1]._value; // All indexes are 1-based
                        }
                        // UintToAddressMap
                        struct UintToAddressMap {
                            Map _inner;
                        }
                        /**
                         * @dev Adds a key-value pair to a map, or updates the value for an existing
                         * key. O(1).
                         *
                         * Returns true if the key was added to the map, that is if it was not
                         * already present.
                         */
                        function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
                            return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
                        }
                        /**
                         * @dev Removes a value from a set. O(1).
                         *
                         * Returns true if the key was removed from the map, that is if it was present.
                         */
                        function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
                            return _remove(map._inner, bytes32(key));
                        }
                        /**
                         * @dev Returns true if the key is in the map. O(1).
                         */
                        function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
                            return _contains(map._inner, bytes32(key));
                        }
                        /**
                         * @dev Returns the number of elements in the map. O(1).
                         */
                        function length(UintToAddressMap storage map) internal view returns (uint256) {
                            return _length(map._inner);
                        }
                       /**
                        * @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
                            (bytes32 key, bytes32 value) = _at(map._inner, index);
                            return (uint256(key), address(uint160(uint256(value))));
                        }
                        /**
                         * @dev Tries to returns the value associated with `key`.  O(1).
                         * Does not revert if `key` is not in the map.
                         *
                         * _Available since v3.4._
                         */
                        function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
                            (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
                            return (success, address(uint160(uint256(value))));
                        }
                        /**
                         * @dev Returns the value associated with `key`.  O(1).
                         *
                         * Requirements:
                         *
                         * - `key` must be in the map.
                         */
                        function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
                            return address(uint160(uint256(_get(map._inner, bytes32(key)))));
                        }
                        /**
                         * @dev Same as {get}, with a custom error message when `key` is not in the map.
                         *
                         * CAUTION: This function is deprecated because it requires allocating memory for the error
                         * message unnecessarily. For custom revert reasons use {tryGet}.
                         */
                        function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
                            return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity ^0.7.0;
                    /**
                     * @dev String operations.
                     */
                    library Strings {
                        /**
                         * @dev Converts a `uint256` to its ASCII `string` representation.
                         */
                        function toString(uint256 value) internal pure returns (string memory) {
                            // Inspired by OraclizeAPI's implementation - MIT licence
                            // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
                            if (value == 0) {
                                return "0";
                            }
                            uint256 temp = value;
                            uint256 digits;
                            while (temp != 0) {
                                digits++;
                                temp /= 10;
                            }
                            bytes memory buffer = new bytes(digits);
                            uint256 index = digits - 1;
                            temp = value;
                            while (temp != 0) {
                                buffer[index--] = bytes1(uint8(48 + temp % 10));
                                temp /= 10;
                            }
                            return string(buffer);
                        }
                    }
                    // SPDX-License-Identifier: MIT
                    pragma solidity >=0.6.0 <0.8.0;
                    /**
                     * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
                     * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
                     *
                     * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
                     * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
                     * need to send a transaction, and thus is not required to hold Ether at all.
                     */
                    interface IERC20Permit {
                        /**
                         * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
                         * given `owner`'s signed approval.
                         *
                         * IMPORTANT: The same issues {IERC20-approve} has related to transaction
                         * ordering also apply here.
                         *
                         * Emits an {Approval} event.
                         *
                         * Requirements:
                         *
                         * - `spender` cannot be the zero address.
                         * - `deadline` must be a timestamp in the future.
                         * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
                         * over the EIP712-formatted function arguments.
                         * - the signature must use ``owner``'s current nonce (see {nonces}).
                         *
                         * For more information on the signature format, see the
                         * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
                         * section].
                         */
                        function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
                        /**
                         * @dev Returns the current nonce for `owner`. This value must be
                         * included whenever a signature is generated for {permit}.
                         *
                         * Every successful call to {permit} increases ``owner``'s nonce by one. This
                         * prevents a signature from being used multiple times.
                         */
                        function nonces(address owner) external view returns (uint256);
                        /**
                         * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
                         */
                        // solhint-disable-next-line func-name-mixedcase
                        function DOMAIN_SEPARATOR() external view returns (bytes32);
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.7.5;
                    /// @title Self Permit
                    /// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route
                    interface ISelfPermit {
                        /// @notice Permits this contract to spend a given token from `msg.sender`
                        /// @dev The `owner` is always msg.sender and the `spender` is always address(this).
                        /// @param token The address of the token spent
                        /// @param value The amount that can be spent of token
                        /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp
                        /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
                        /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
                        /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
                        function selfPermit(
                            address token,
                            uint256 value,
                            uint256 deadline,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) external payable;
                        /// @notice Permits this contract to spend a given token from `msg.sender`
                        /// @dev The `owner` is always msg.sender and the `spender` is always address(this).
                        /// Can be used instead of #selfPermit to prevent calls from failing due to a frontrun of a call to #selfPermit
                        /// @param token The address of the token spent
                        /// @param value The amount that can be spent of token
                        /// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp
                        /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
                        /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
                        /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
                        function selfPermitIfNecessary(
                            address token,
                            uint256 value,
                            uint256 deadline,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) external payable;
                        /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter
                        /// @dev The `owner` is always msg.sender and the `spender` is always address(this)
                        /// @param token The address of the token spent
                        /// @param nonce The current nonce of the owner
                        /// @param expiry The timestamp at which the permit is no longer valid
                        /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
                        /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
                        /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
                        function selfPermitAllowed(
                            address token,
                            uint256 nonce,
                            uint256 expiry,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) external payable;
                        /// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter
                        /// @dev The `owner` is always msg.sender and the `spender` is always address(this)
                        /// Can be used instead of #selfPermitAllowed to prevent calls from failing due to a frontrun of a call to #selfPermitAllowed.
                        /// @param token The address of the token spent
                        /// @param nonce The current nonce of the owner
                        /// @param expiry The timestamp at which the permit is no longer valid
                        /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
                        /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
                        /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
                        function selfPermitAllowedIfNecessary(
                            address token,
                            uint256 nonce,
                            uint256 expiry,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) external payable;
                    }
                    // SPDX-License-Identifier: GPL-2.0-or-later
                    pragma solidity >=0.5.0;
                    /// @title Interface for permit
                    /// @notice Interface used by DAI/CHAI for permit
                    interface IERC20PermitAllowed {
                        /// @notice Approve the spender to spend some tokens via the holder signature
                        /// @dev This is the permit interface used by DAI and CHAI
                        /// @param holder The address of the token holder, the token owner
                        /// @param spender The address of the token spender
                        /// @param nonce The holder's nonce, increases at each call to permit
                        /// @param expiry The timestamp at which the permit is no longer valid
                        /// @param allowed Boolean that sets approval amount, true for type(uint256).max and false for 0
                        /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
                        /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
                        /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
                        function permit(
                            address holder,
                            address spender,
                            uint256 nonce,
                            uint256 expiry,
                            bool allowed,
                            uint8 v,
                            bytes32 r,
                            bytes32 s
                        ) external;
                    }
                    

                    File 6 of 6: GnosisSafe
                    // SPDX-License-Identifier: LGPL-3.0-only
                    pragma solidity >=0.7.0 <0.9.0;
                    import "./base/ModuleManager.sol";
                    import "./base/OwnerManager.sol";
                    import "./base/FallbackManager.sol";
                    import "./base/GuardManager.sol";
                    import "./common/EtherPaymentFallback.sol";
                    import "./common/Singleton.sol";
                    import "./common/SignatureDecoder.sol";
                    import "./common/SecuredTokenTransfer.sol";
                    import "./common/StorageAccessible.sol";
                    import "./interfaces/ISignatureValidator.sol";
                    import "./external/GnosisSafeMath.sol";
                    /// @title Gnosis Safe - A multisignature wallet with support for confirmations using signed messages based on ERC191.
                    /// @author Stefan George - <[email protected]>
                    /// @author Richard Meissner - <[email protected]>
                    contract GnosisSafe is
                        EtherPaymentFallback,
                        Singleton,
                        ModuleManager,
                        OwnerManager,
                        SignatureDecoder,
                        SecuredTokenTransfer,
                        ISignatureValidatorConstants,
                        FallbackManager,
                        StorageAccessible,
                        GuardManager
                    {
                        using GnosisSafeMath for uint256;
                        string public constant VERSION = "1.3.0";
                        // keccak256(
                        //     "EIP712Domain(uint256 chainId,address verifyingContract)"
                        // );
                        bytes32 private constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218;
                        // keccak256(
                        //     "SafeTx(address to,uint256 value,bytes data,uint8 operation,uint256 safeTxGas,uint256 baseGas,uint256 gasPrice,address gasToken,address refundReceiver,uint256 nonce)"
                        // );
                        bytes32 private constant SAFE_TX_TYPEHASH = 0xbb8310d486368db6bd6f849402fdd73ad53d316b5a4b2644ad6efe0f941286d8;
                        event SafeSetup(address indexed initiator, address[] owners, uint256 threshold, address initializer, address fallbackHandler);
                        event ApproveHash(bytes32 indexed approvedHash, address indexed owner);
                        event SignMsg(bytes32 indexed msgHash);
                        event ExecutionFailure(bytes32 txHash, uint256 payment);
                        event ExecutionSuccess(bytes32 txHash, uint256 payment);
                        uint256 public nonce;
                        bytes32 private _deprecatedDomainSeparator;
                        // Mapping to keep track of all message hashes that have been approve by ALL REQUIRED owners
                        mapping(bytes32 => uint256) public signedMessages;
                        // Mapping to keep track of all hashes (message or transaction) that have been approve by ANY owners
                        mapping(address => mapping(bytes32 => uint256)) public approvedHashes;
                        // This constructor ensures that this contract can only be used as a master copy for Proxy contracts
                        constructor() {
                            // By setting the threshold it is not possible to call setup anymore,
                            // so we create a Safe with 0 owners and threshold 1.
                            // This is an unusable Safe, perfect for the singleton
                            threshold = 1;
                        }
                        /// @dev Setup function sets initial storage of contract.
                        /// @param _owners List of Safe owners.
                        /// @param _threshold Number of required confirmations for a Safe transaction.
                        /// @param to Contract address for optional delegate call.
                        /// @param data Data payload for optional delegate call.
                        /// @param fallbackHandler Handler for fallback calls to this contract
                        /// @param paymentToken Token that should be used for the payment (0 is ETH)
                        /// @param payment Value that should be paid
                        /// @param paymentReceiver Adddress that should receive the payment (or 0 if tx.origin)
                        function setup(
                            address[] calldata _owners,
                            uint256 _threshold,
                            address to,
                            bytes calldata data,
                            address fallbackHandler,
                            address paymentToken,
                            uint256 payment,
                            address payable paymentReceiver
                        ) external {
                            // setupOwners checks if the Threshold is already set, therefore preventing that this method is called twice
                            setupOwners(_owners, _threshold);
                            if (fallbackHandler != address(0)) internalSetFallbackHandler(fallbackHandler);
                            // As setupOwners can only be called if the contract has not been initialized we don't need a check for setupModules
                            setupModules(to, data);
                            if (payment > 0) {
                                // To avoid running into issues with EIP-170 we reuse the handlePayment function (to avoid adjusting code of that has been verified we do not adjust the method itself)
                                // baseGas = 0, gasPrice = 1 and gas = payment => amount = (payment + 0) * 1 = payment
                                handlePayment(payment, 0, 1, paymentToken, paymentReceiver);
                            }
                            emit SafeSetup(msg.sender, _owners, _threshold, to, fallbackHandler);
                        }
                        /// @dev Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that submitted the transaction.
                        ///      Note: The fees are always transferred, even if the user transaction fails.
                        /// @param to Destination address of Safe transaction.
                        /// @param value Ether value of Safe transaction.
                        /// @param data Data payload of Safe transaction.
                        /// @param operation Operation type of Safe transaction.
                        /// @param safeTxGas Gas that should be used for the Safe transaction.
                        /// @param baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
                        /// @param gasPrice Gas price that should be used for the payment calculation.
                        /// @param gasToken Token address (or 0 if ETH) that is used for the payment.
                        /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
                        /// @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v})
                        function execTransaction(
                            address to,
                            uint256 value,
                            bytes calldata data,
                            Enum.Operation operation,
                            uint256 safeTxGas,
                            uint256 baseGas,
                            uint256 gasPrice,
                            address gasToken,
                            address payable refundReceiver,
                            bytes memory signatures
                        ) public payable virtual returns (bool success) {
                            bytes32 txHash;
                            // Use scope here to limit variable lifetime and prevent `stack too deep` errors
                            {
                                bytes memory txHashData =
                                    encodeTransactionData(
                                        // Transaction info
                                        to,
                                        value,
                                        data,
                                        operation,
                                        safeTxGas,
                                        // Payment info
                                        baseGas,
                                        gasPrice,
                                        gasToken,
                                        refundReceiver,
                                        // Signature info
                                        nonce
                                    );
                                // Increase nonce and execute transaction.
                                nonce++;
                                txHash = keccak256(txHashData);
                                checkSignatures(txHash, txHashData, signatures);
                            }
                            address guard = getGuard();
                            {
                                if (guard != address(0)) {
                                    Guard(guard).checkTransaction(
                                        // Transaction info
                                        to,
                                        value,
                                        data,
                                        operation,
                                        safeTxGas,
                                        // Payment info
                                        baseGas,
                                        gasPrice,
                                        gasToken,
                                        refundReceiver,
                                        // Signature info
                                        signatures,
                                        msg.sender
                                    );
                                }
                            }
                            // We require some gas to emit the events (at least 2500) after the execution and some to perform code until the execution (500)
                            // We also include the 1/64 in the check that is not send along with a call to counteract potential shortings because of EIP-150
                            require(gasleft() >= ((safeTxGas * 64) / 63).max(safeTxGas + 2500) + 500, "GS010");
                            // Use scope here to limit variable lifetime and prevent `stack too deep` errors
                            {
                                uint256 gasUsed = gasleft();
                                // If the gasPrice is 0 we assume that nearly all available gas can be used (it is always more than safeTxGas)
                                // We only substract 2500 (compared to the 3000 before) to ensure that the amount passed is still higher than safeTxGas
                                success = execute(to, value, data, operation, gasPrice == 0 ? (gasleft() - 2500) : safeTxGas);
                                gasUsed = gasUsed.sub(gasleft());
                                // If no safeTxGas and no gasPrice was set (e.g. both are 0), then the internal tx is required to be successful
                                // This makes it possible to use `estimateGas` without issues, as it searches for the minimum gas where the tx doesn't revert
                                require(success || safeTxGas != 0 || gasPrice != 0, "GS013");
                                // We transfer the calculated tx costs to the tx.origin to avoid sending it to intermediate contracts that have made calls
                                uint256 payment = 0;
                                if (gasPrice > 0) {
                                    payment = handlePayment(gasUsed, baseGas, gasPrice, gasToken, refundReceiver);
                                }
                                if (success) emit ExecutionSuccess(txHash, payment);
                                else emit ExecutionFailure(txHash, payment);
                            }
                            {
                                if (guard != address(0)) {
                                    Guard(guard).checkAfterExecution(txHash, success);
                                }
                            }
                        }
                        function handlePayment(
                            uint256 gasUsed,
                            uint256 baseGas,
                            uint256 gasPrice,
                            address gasToken,
                            address payable refundReceiver
                        ) private returns (uint256 payment) {
                            // solhint-disable-next-line avoid-tx-origin
                            address payable receiver = refundReceiver == address(0) ? payable(tx.origin) : refundReceiver;
                            if (gasToken == address(0)) {
                                // For ETH we will only adjust the gas price to not be higher than the actual used gas price
                                payment = gasUsed.add(baseGas).mul(gasPrice < tx.gasprice ? gasPrice : tx.gasprice);
                                require(receiver.send(payment), "GS011");
                            } else {
                                payment = gasUsed.add(baseGas).mul(gasPrice);
                                require(transferToken(gasToken, receiver, payment), "GS012");
                            }
                        }
                        /**
                         * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise.
                         * @param dataHash Hash of the data (could be either a message hash or transaction hash)
                         * @param data That should be signed (this is passed to an external validator contract)
                         * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash.
                         */
                        function checkSignatures(
                            bytes32 dataHash,
                            bytes memory data,
                            bytes memory signatures
                        ) public view {
                            // Load threshold to avoid multiple storage loads
                            uint256 _threshold = threshold;
                            // Check that a threshold is set
                            require(_threshold > 0, "GS001");
                            checkNSignatures(dataHash, data, signatures, _threshold);
                        }
                        /**
                         * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise.
                         * @param dataHash Hash of the data (could be either a message hash or transaction hash)
                         * @param data That should be signed (this is passed to an external validator contract)
                         * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash.
                         * @param requiredSignatures Amount of required valid signatures.
                         */
                        function checkNSignatures(
                            bytes32 dataHash,
                            bytes memory data,
                            bytes memory signatures,
                            uint256 requiredSignatures
                        ) public view {
                            // Check that the provided signature data is not too short
                            require(signatures.length >= requiredSignatures.mul(65), "GS020");
                            // There cannot be an owner with address 0.
                            address lastOwner = address(0);
                            address currentOwner;
                            uint8 v;
                            bytes32 r;
                            bytes32 s;
                            uint256 i;
                            for (i = 0; i < requiredSignatures; i++) {
                                (v, r, s) = signatureSplit(signatures, i);
                                if (v == 0) {
                                    // If v is 0 then it is a contract signature
                                    // When handling contract signatures the address of the contract is encoded into r
                                    currentOwner = address(uint160(uint256(r)));
                                    // Check that signature data pointer (s) is not pointing inside the static part of the signatures bytes
                                    // This check is not completely accurate, since it is possible that more signatures than the threshold are send.
                                    // Here we only check that the pointer is not pointing inside the part that is being processed
                                    require(uint256(s) >= requiredSignatures.mul(65), "GS021");
                                    // Check that signature data pointer (s) is in bounds (points to the length of data -> 32 bytes)
                                    require(uint256(s).add(32) <= signatures.length, "GS022");
                                    // Check if the contract signature is in bounds: start of data is s + 32 and end is start + signature length
                                    uint256 contractSignatureLen;
                                    // solhint-disable-next-line no-inline-assembly
                                    assembly {
                                        contractSignatureLen := mload(add(add(signatures, s), 0x20))
                                    }
                                    require(uint256(s).add(32).add(contractSignatureLen) <= signatures.length, "GS023");
                                    // Check signature
                                    bytes memory contractSignature;
                                    // solhint-disable-next-line no-inline-assembly
                                    assembly {
                                        // The signature data for contract signatures is appended to the concatenated signatures and the offset is stored in s
                                        contractSignature := add(add(signatures, s), 0x20)
                                    }
                                    require(ISignatureValidator(currentOwner).isValidSignature(data, contractSignature) == EIP1271_MAGIC_VALUE, "GS024");
                                } else if (v == 1) {
                                    // If v is 1 then it is an approved hash
                                    // When handling approved hashes the address of the approver is encoded into r
                                    currentOwner = address(uint160(uint256(r)));
                                    // Hashes are automatically approved by the sender of the message or when they have been pre-approved via a separate transaction
                                    require(msg.sender == currentOwner || approvedHashes[currentOwner][dataHash] != 0, "GS025");
                                } else if (v > 30) {
                                    // If v > 30 then default va (27,28) has been adjusted for eth_sign flow
                                    // To support eth_sign and similar we adjust v and hash the messageHash with the Ethereum message prefix before applying ecrecover
                                    currentOwner = ecrecover(keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\
                    32", dataHash)), v - 4, r, s);
                                } else {
                                    // Default is the ecrecover flow with the provided data hash
                                    // Use ecrecover with the messageHash for EOA signatures
                                    currentOwner = ecrecover(dataHash, v, r, s);
                                }
                                require(currentOwner > lastOwner && owners[currentOwner] != address(0) && currentOwner != SENTINEL_OWNERS, "GS026");
                                lastOwner = currentOwner;
                            }
                        }
                        /// @dev Allows to estimate a Safe transaction.
                        ///      This method is only meant for estimation purpose, therefore the call will always revert and encode the result in the revert data.
                        ///      Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the safe with `execTransaction`
                        /// @param to Destination address of Safe transaction.
                        /// @param value Ether value of Safe transaction.
                        /// @param data Data payload of Safe transaction.
                        /// @param operation Operation type of Safe transaction.
                        /// @return Estimate without refunds and overhead fees (base transaction and payload data gas costs).
                        /// @notice Deprecated in favor of common/StorageAccessible.sol and will be removed in next version.
                        function requiredTxGas(
                            address to,
                            uint256 value,
                            bytes calldata data,
                            Enum.Operation operation
                        ) external returns (uint256) {
                            uint256 startGas = gasleft();
                            // We don't provide an error message here, as we use it to return the estimate
                            require(execute(to, value, data, operation, gasleft()));
                            uint256 requiredGas = startGas - gasleft();
                            // Convert response to string and return via error message
                            revert(string(abi.encodePacked(requiredGas)));
                        }
                        /**
                         * @dev Marks a hash as approved. This can be used to validate a hash that is used by a signature.
                         * @param hashToApprove The hash that should be marked as approved for signatures that are verified by this contract.
                         */
                        function approveHash(bytes32 hashToApprove) external {
                            require(owners[msg.sender] != address(0), "GS030");
                            approvedHashes[msg.sender][hashToApprove] = 1;
                            emit ApproveHash(hashToApprove, msg.sender);
                        }
                        /// @dev Returns the chain id used by this contract.
                        function getChainId() public view returns (uint256) {
                            uint256 id;
                            // solhint-disable-next-line no-inline-assembly
                            assembly {
                                id := chainid()
                            }
                            return id;
                        }
                        function domainSeparator() public view returns (bytes32) {
                            return keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, getChainId(), this));
                        }
                        /// @dev Returns the bytes that are hashed to be signed by owners.
                        /// @param to Destination address.
                        /// @param value Ether value.
                        /// @param data Data payload.
                        /// @param operation Operation type.
                        /// @param safeTxGas Gas that should be used for the safe transaction.
                        /// @param baseGas Gas costs for that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
                        /// @param gasPrice Maximum gas price that should be used for this transaction.
                        /// @param gasToken Token address (or 0 if ETH) that is used for the payment.
                        /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
                        /// @param _nonce Transaction nonce.
                        /// @return Transaction hash bytes.
                        function encodeTransactionData(
                            address to,
                            uint256 value,
                            bytes calldata data,
                            Enum.Operation operation,
                            uint256 safeTxGas,
                            uint256 baseGas,
                            uint256 gasPrice,
                            address gasToken,
                            address refundReceiver,
                            uint256 _nonce
                        ) public view returns (bytes memory) {
                            bytes32 safeTxHash =
                                keccak256(
                                    abi.encode(
                                        SAFE_TX_TYPEHASH,
                                        to,
                                        value,
                                        keccak256(data),
                                        operation,
                                        safeTxGas,
                                        baseGas,
                                        gasPrice,
                                        gasToken,
                                        refundReceiver,
                                        _nonce
                                    )
                                );
                            return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator(), safeTxHash);
                        }
                        /// @dev Returns hash to be signed by owners.
                        /// @param to Destination address.
                        /// @param value Ether value.
                        /// @param data Data payload.
                        /// @param operation Operation type.
                        /// @param safeTxGas Fas that should be used for the safe transaction.
                        /// @param baseGas Gas costs for data used to trigger the safe transaction.
                        /// @param gasPrice Maximum gas price that should be used for this transaction.
                        /// @param gasToken Token address (or 0 if ETH) that is used for the payment.
                        /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
                        /// @param _nonce Transaction nonce.
                        /// @return Transaction hash.
                        function getTransactionHash(
                            address to,
                            uint256 value,
                            bytes calldata data,
                            Enum.Operation operation,
                            uint256 safeTxGas,
                            uint256 baseGas,
                            uint256 gasPrice,
                            address gasToken,
                            address refundReceiver,
                            uint256 _nonce
                        ) public view returns (bytes32) {
                            return keccak256(encodeTransactionData(to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce));
                        }
                    }
                    // SPDX-License-Identifier: LGPL-3.0-only
                    pragma solidity >=0.7.0 <0.9.0;
                    import "../common/Enum.sol";
                    /// @title Executor - A contract that can execute transactions
                    /// @author Richard Meissner - <[email protected]>
                    contract Executor {
                        function execute(
                            address to,
                            uint256 value,
                            bytes memory data,
                            Enum.Operation operation,
                            uint256 txGas
                        ) internal returns (bool success) {
                            if (operation == Enum.Operation.DelegateCall) {
                                // solhint-disable-next-line no-inline-assembly
                                assembly {
                                    success := delegatecall(txGas, to, add(data, 0x20), mload(data), 0, 0)
                                }
                            } else {
                                // solhint-disable-next-line no-inline-assembly
                                assembly {
                                    success := call(txGas, to, value, add(data, 0x20), mload(data), 0, 0)
                                }
                            }
                        }
                    }
                    // SPDX-License-Identifier: LGPL-3.0-only
                    pragma solidity >=0.7.0 <0.9.0;
                    import "../common/SelfAuthorized.sol";
                    /// @title Fallback Manager - A contract that manages fallback calls made to this contract
                    /// @author Richard Meissner - <[email protected]>
                    contract FallbackManager is SelfAuthorized {
                        event ChangedFallbackHandler(address handler);
                        // keccak256("fallback_manager.handler.address")
                        bytes32 internal constant FALLBACK_HANDLER_STORAGE_SLOT = 0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d5;
                        function internalSetFallbackHandler(address handler) internal {
                            bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;
                            // solhint-disable-next-line no-inline-assembly
                            assembly {
                                sstore(slot, handler)
                            }
                        }
                        /// @dev Allows to add a contract to handle fallback calls.
                        ///      Only fallback calls without value and with data will be forwarded.
                        ///      This can only be done via a Safe transaction.
                        /// @param handler contract to handle fallbacks calls.
                        function setFallbackHandler(address handler) public authorized {
                            internalSetFallbackHandler(handler);
                            emit ChangedFallbackHandler(handler);
                        }
                        // solhint-disable-next-line payable-fallback,no-complex-fallback
                        fallback() external {
                            bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;
                            // solhint-disable-next-line no-inline-assembly
                            assembly {
                                let handler := sload(slot)
                                if iszero(handler) {
                                    return(0, 0)
                                }
                                calldatacopy(0, 0, calldatasize())
                                // The msg.sender address is shifted to the left by 12 bytes to remove the padding
                                // Then the address without padding is stored right after the calldata
                                mstore(calldatasize(), shl(96, caller()))
                                // Add 20 bytes for the address appended add the end
                                let success := call(gas(), handler, 0, 0, add(calldatasize(), 20), 0, 0)
                                returndatacopy(0, 0, returndatasize())
                                if iszero(success) {
                                    revert(0, returndatasize())
                                }
                                return(0, returndatasize())
                            }
                        }
                    }
                    // SPDX-License-Identifier: LGPL-3.0-only
                    pragma solidity >=0.7.0 <0.9.0;
                    import "../common/Enum.sol";
                    import "../common/SelfAuthorized.sol";
                    interface Guard {
                        function checkTransaction(
                            address to,
                            uint256 value,
                            bytes memory data,
                            Enum.Operation operation,
                            uint256 safeTxGas,
                            uint256 baseGas,
                            uint256 gasPrice,
                            address gasToken,
                            address payable refundReceiver,
                            bytes memory signatures,
                            address msgSender
                        ) external;
                        function checkAfterExecution(bytes32 txHash, bool success) external;
                    }
                    /// @title Fallback Manager - A contract that manages fallback calls made to this contract
                    /// @author Richard Meissner - <[email protected]>
                    contract GuardManager is SelfAuthorized {
                        event ChangedGuard(address guard);
                        // keccak256("guard_manager.guard.address")
                        bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8;
                        /// @dev Set a guard that checks transactions before execution
                        /// @param guard The address of the guard to be used or the 0 address to disable the guard
                        function setGuard(address guard) external authorized {
                            bytes32 slot = GUARD_STORAGE_SLOT;
                            // solhint-disable-next-line no-inline-assembly
                            assembly {
                                sstore(slot, guard)
                            }
                            emit ChangedGuard(guard);
                        }
                        function getGuard() internal view returns (address guard) {
                            bytes32 slot = GUARD_STORAGE_SLOT;
                            // solhint-disable-next-line no-inline-assembly
                            assembly {
                                guard := sload(slot)
                            }
                        }
                    }
                    // SPDX-License-Identifier: LGPL-3.0-only
                    pragma solidity >=0.7.0 <0.9.0;
                    import "../common/Enum.sol";
                    import "../common/SelfAuthorized.sol";
                    import "./Executor.sol";
                    /// @title Module Manager - A contract that manages modules that can execute transactions via this contract
                    /// @author Stefan George - <[email protected]>
                    /// @author Richard Meissner - <[email protected]>
                    contract ModuleManager is SelfAuthorized, Executor {
                        event EnabledModule(address module);
                        event DisabledModule(address module);
                        event ExecutionFromModuleSuccess(address indexed module);
                        event ExecutionFromModuleFailure(address indexed module);
                        address internal constant SENTINEL_MODULES = address(0x1);
                        mapping(address => address) internal modules;
                        function setupModules(address to, bytes memory data) internal {
                            require(modules[SENTINEL_MODULES] == address(0), "GS100");
                            modules[SENTINEL_MODULES] = SENTINEL_MODULES;
                            if (to != address(0))
                                // Setup has to complete successfully or transaction fails.
                                require(execute(to, 0, data, Enum.Operation.DelegateCall, gasleft()), "GS000");
                        }
                        /// @dev Allows to add a module to the whitelist.
                        ///      This can only be done via a Safe transaction.
                        /// @notice Enables the module `module` for the Safe.
                        /// @param module Module to be whitelisted.
                        function enableModule(address module) public authorized {
                            // Module address cannot be null or sentinel.
                            require(module != address(0) && module != SENTINEL_MODULES, "GS101");
                            // Module cannot be added twice.
                            require(modules[module] == address(0), "GS102");
                            modules[module] = modules[SENTINEL_MODULES];
                            modules[SENTINEL_MODULES] = module;
                            emit EnabledModule(module);
                        }
                        /// @dev Allows to remove a module from the whitelist.
                        ///      This can only be done via a Safe transaction.
                        /// @notice Disables the module `module` for the Safe.
                        /// @param prevModule Module that pointed to the module to be removed in the linked list
                        /// @param module Module to be removed.
                        function disableModule(address prevModule, address module) public authorized {
                            // Validate module address and check that it corresponds to module index.
                            require(module != address(0) && module != SENTINEL_MODULES, "GS101");
                            require(modules[prevModule] == module, "GS103");
                            modules[prevModule] = modules[module];
                            modules[module] = address(0);
                            emit DisabledModule(module);
                        }
                        /// @dev Allows a Module to execute a Safe transaction without any further confirmations.
                        /// @param to Destination address of module transaction.
                        /// @param value Ether value of module transaction.
                        /// @param data Data payload of module transaction.
                        /// @param operation Operation type of module transaction.
                        function execTransactionFromModule(
                            address to,
                            uint256 value,
                            bytes memory data,
                            Enum.Operation operation
                        ) public virtual returns (bool success) {
                            // Only whitelisted modules are allowed.
                            require(msg.sender != SENTINEL_MODULES && modules[msg.sender] != address(0), "GS104");
                            // Execute transaction without further confirmations.
                            success = execute(to, value, data, operation, gasleft());
                            if (success) emit ExecutionFromModuleSuccess(msg.sender);
                            else emit ExecutionFromModuleFailure(msg.sender);
                        }
                        /// @dev Allows a Module to execute a Safe transaction without any further confirmations and return data
                        /// @param to Destination address of module transaction.
                        /// @param value Ether value of module transaction.
                        /// @param data Data payload of module transaction.
                        /// @param operation Operation type of module transaction.
                        function execTransactionFromModuleReturnData(
                            address to,
                            uint256 value,
                            bytes memory data,
                            Enum.Operation operation
                        ) public returns (bool success, bytes memory returnData) {
                            success = execTransactionFromModule(to, value, data, operation);
                            // solhint-disable-next-line no-inline-assembly
                            assembly {
                                // Load free memory location
                                let ptr := mload(0x40)
                                // We allocate memory for the return data by setting the free memory location to
                                // current free memory location + data size + 32 bytes for data size value
                                mstore(0x40, add(ptr, add(returndatasize(), 0x20)))
                                // Store the size
                                mstore(ptr, returndatasize())
                                // Store the data
                                returndatacopy(add(ptr, 0x20), 0, returndatasize())
                                // Point the return data to the correct memory location
                                returnData := ptr
                            }
                        }
                        /// @dev Returns if an module is enabled
                        /// @return True if the module is enabled
                        function isModuleEnabled(address module) public view returns (bool) {
                            return SENTINEL_MODULES != module && modules[module] != address(0);
                        }
                        /// @dev Returns array of modules.
                        /// @param start Start of the page.
                        /// @param pageSize Maximum number of modules that should be returned.
                        /// @return array Array of modules.
                        /// @return next Start of the next page.
                        function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next) {
                            // Init array with max page size
                            array = new address[](pageSize);
                            // Populate return array
                            uint256 moduleCount = 0;
                            address currentModule = modules[start];
                            while (currentModule != address(0x0) && currentModule != SENTINEL_MODULES && moduleCount < pageSize) {
                                array[moduleCount] = currentModule;
                                currentModule = modules[currentModule];
                                moduleCount++;
                            }
                            next = currentModule;
                            // Set correct size of returned array
                            // solhint-disable-next-line no-inline-assembly
                            assembly {
                                mstore(array, moduleCount)
                            }
                        }
                    }
                    // SPDX-License-Identifier: LGPL-3.0-only
                    pragma solidity >=0.7.0 <0.9.0;
                    import "../common/SelfAuthorized.sol";
                    /// @title OwnerManager - Manages a set of owners and a threshold to perform actions.
                    /// @author Stefan George - <[email protected]>
                    /// @author Richard Meissner - <[email protected]>
                    contract OwnerManager is SelfAuthorized {
                        event AddedOwner(address owner);
                        event RemovedOwner(address owner);
                        event ChangedThreshold(uint256 threshold);
                        address internal constant SENTINEL_OWNERS = address(0x1);
                        mapping(address => address) internal owners;
                        uint256 internal ownerCount;
                        uint256 internal threshold;
                        /// @dev Setup function sets initial storage of contract.
                        /// @param _owners List of Safe owners.
                        /// @param _threshold Number of required confirmations for a Safe transaction.
                        function setupOwners(address[] memory _owners, uint256 _threshold) internal {
                            // Threshold can only be 0 at initialization.
                            // Check ensures that setup function can only be called once.
                            require(threshold == 0, "GS200");
                            // Validate that threshold is smaller than number of added owners.
                            require(_threshold <= _owners.length, "GS201");
                            // There has to be at least one Safe owner.
                            require(_threshold >= 1, "GS202");
                            // Initializing Safe owners.
                            address currentOwner = SENTINEL_OWNERS;
                            for (uint256 i = 0; i < _owners.length; i++) {
                                // Owner address cannot be null.
                                address owner = _owners[i];
                                require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this) && currentOwner != owner, "GS203");
                                // No duplicate owners allowed.
                                require(owners[owner] == address(0), "GS204");
                                owners[currentOwner] = owner;
                                currentOwner = owner;
                            }
                            owners[currentOwner] = SENTINEL_OWNERS;
                            ownerCount = _owners.length;
                            threshold = _threshold;
                        }
                        /// @dev Allows to add a new owner to the Safe and update the threshold at the same time.
                        ///      This can only be done via a Safe transaction.
                        /// @notice Adds the owner `owner` to the Safe and updates the threshold to `_threshold`.
                        /// @param owner New owner address.
                        /// @param _threshold New threshold.
                        function addOwnerWithThreshold(address owner, uint256 _threshold) public authorized {
                            // Owner address cannot be null, the sentinel or the Safe itself.
                            require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this), "GS203");
                            // No duplicate owners allowed.
                            require(owners[owner] == address(0), "GS204");
                            owners[owner] = owners[SENTINEL_OWNERS];
                            owners[SENTINEL_OWNERS] = owner;
                            ownerCount++;
                            emit AddedOwner(owner);
                            // Change threshold if threshold was changed.
                            if (threshold != _threshold) changeThreshold(_threshold);
                        }
                        /// @dev Allows to remove an owner from the Safe and update the threshold at the same time.
                        ///      This can only be done via a Safe transaction.
                        /// @notice Removes the owner `owner` from the Safe and updates the threshold to `_threshold`.
                        /// @param prevOwner Owner that pointed to the owner to be removed in the linked list
                        /// @param owner Owner address to be removed.
                        /// @param _threshold New threshold.
                        function removeOwner(
                            address prevOwner,
                            address owner,
                            uint256 _threshold
                        ) public authorized {
                            // Only allow to remove an owner, if threshold can still be reached.
                            require(ownerCount - 1 >= _threshold, "GS201");
                            // Validate owner address and check that it corresponds to owner index.
                            require(owner != address(0) && owner != SENTINEL_OWNERS, "GS203");
                            require(owners[prevOwner] == owner, "GS205");
                            owners[prevOwner] = owners[owner];
                            owners[owner] = address(0);
                            ownerCount--;
                            emit RemovedOwner(owner);
                            // Change threshold if threshold was changed.
                            if (threshold != _threshold) changeThreshold(_threshold);
                        }
                        /// @dev Allows to swap/replace an owner from the Safe with another address.
                        ///      This can only be done via a Safe transaction.
                        /// @notice Replaces the owner `oldOwner` in the Safe with `newOwner`.
                        /// @param prevOwner Owner that pointed to the owner to be replaced in the linked list
                        /// @param oldOwner Owner address to be replaced.
                        /// @param newOwner New owner address.
                        function swapOwner(
                            address prevOwner,
                            address oldOwner,
                            address newOwner
                        ) public authorized {
                            // Owner address cannot be null, the sentinel or the Safe itself.
                            require(newOwner != address(0) && newOwner != SENTINEL_OWNERS && newOwner != address(this), "GS203");
                            // No duplicate owners allowed.
                            require(owners[newOwner] == address(0), "GS204");
                            // Validate oldOwner address and check that it corresponds to owner index.
                            require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, "GS203");
                            require(owners[prevOwner] == oldOwner, "GS205");
                            owners[newOwner] = owners[oldOwner];
                            owners[prevOwner] = newOwner;
                            owners[oldOwner] = address(0);
                            emit RemovedOwner(oldOwner);
                            emit AddedOwner(newOwner);
                        }
                        /// @dev Allows to update the number of required confirmations by Safe owners.
                        ///      This can only be done via a Safe transaction.
                        /// @notice Changes the threshold of the Safe to `_threshold`.
                        /// @param _threshold New threshold.
                        function changeThreshold(uint256 _threshold) public authorized {
                            // Validate that threshold is smaller than number of owners.
                            require(_threshold <= ownerCount, "GS201");
                            // There has to be at least one Safe owner.
                            require(_threshold >= 1, "GS202");
                            threshold = _threshold;
                            emit ChangedThreshold(threshold);
                        }
                        function getThreshold() public view returns (uint256) {
                            return threshold;
                        }
                        function isOwner(address owner) public view returns (bool) {
                            return owner != SENTINEL_OWNERS && owners[owner] != address(0);
                        }
                        /// @dev Returns array of owners.
                        /// @return Array of Safe owners.
                        function getOwners() public view returns (address[] memory) {
                            address[] memory array = new address[](ownerCount);
                            // populate return array
                            uint256 index = 0;
                            address currentOwner = owners[SENTINEL_OWNERS];
                            while (currentOwner != SENTINEL_OWNERS) {
                                array[index] = currentOwner;
                                currentOwner = owners[currentOwner];
                                index++;
                            }
                            return array;
                        }
                    }
                    // SPDX-License-Identifier: LGPL-3.0-only
                    pragma solidity >=0.7.0 <0.9.0;
                    /// @title Enum - Collection of enums
                    /// @author Richard Meissner - <[email protected]>
                    contract Enum {
                        enum Operation {Call, DelegateCall}
                    }
                    // SPDX-License-Identifier: LGPL-3.0-only
                    pragma solidity >=0.7.0 <0.9.0;
                    /// @title EtherPaymentFallback - A contract that has a fallback to accept ether payments
                    /// @author Richard Meissner - <[email protected]>
                    contract EtherPaymentFallback {
                        event SafeReceived(address indexed sender, uint256 value);
                        /// @dev Fallback function accepts Ether transactions.
                        receive() external payable {
                            emit SafeReceived(msg.sender, msg.value);
                        }
                    }
                    // SPDX-License-Identifier: LGPL-3.0-only
                    pragma solidity >=0.7.0 <0.9.0;
                    /// @title SecuredTokenTransfer - Secure token transfer
                    /// @author Richard Meissner - <[email protected]>
                    contract SecuredTokenTransfer {
                        /// @dev Transfers a token and returns if it was a success
                        /// @param token Token that should be transferred
                        /// @param receiver Receiver to whom the token should be transferred
                        /// @param amount The amount of tokens that should be transferred
                        function transferToken(
                            address token,
                            address receiver,
                            uint256 amount
                        ) internal returns (bool transferred) {
                            // 0xa9059cbb - keccack("transfer(address,uint256)")
                            bytes memory data = abi.encodeWithSelector(0xa9059cbb, receiver, amount);
                            // solhint-disable-next-line no-inline-assembly
                            assembly {
                                // We write the return value to scratch space.
                                // See https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html#layout-in-memory
                                let success := call(sub(gas(), 10000), token, 0, add(data, 0x20), mload(data), 0, 0x20)
                                switch returndatasize()
                                    case 0 {
                                        transferred := success
                                    }
                                    case 0x20 {
                                        transferred := iszero(or(iszero(success), iszero(mload(0))))
                                    }
                                    default {
                                        transferred := 0
                                    }
                            }
                        }
                    }
                    // SPDX-License-Identifier: LGPL-3.0-only
                    pragma solidity >=0.7.0 <0.9.0;
                    /// @title SelfAuthorized - authorizes current contract to perform actions
                    /// @author Richard Meissner - <[email protected]>
                    contract SelfAuthorized {
                        function requireSelfCall() private view {
                            require(msg.sender == address(this), "GS031");
                        }
                        modifier authorized() {
                            // This is a function call as it minimized the bytecode size
                            requireSelfCall();
                            _;
                        }
                    }
                    // SPDX-License-Identifier: LGPL-3.0-only
                    pragma solidity >=0.7.0 <0.9.0;
                    /// @title SignatureDecoder - Decodes signatures that a encoded as bytes
                    /// @author Richard Meissner - <[email protected]>
                    contract SignatureDecoder {
                        /// @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s`.
                        /// @notice Make sure to peform a bounds check for @param pos, to avoid out of bounds access on @param signatures
                        /// @param pos which signature to read. A prior bounds check of this parameter should be performed, to avoid out of bounds access
                        /// @param signatures concatenated rsv signatures
                        function signatureSplit(bytes memory signatures, uint256 pos)
                            internal
                            pure
                            returns (
                                uint8 v,
                                bytes32 r,
                                bytes32 s
                            )
                        {
                            // The signature format is a compact form of:
                            //   {bytes32 r}{bytes32 s}{uint8 v}
                            // Compact means, uint8 is not padded to 32 bytes.
                            // solhint-disable-next-line no-inline-assembly
                            assembly {
                                let signaturePos := mul(0x41, pos)
                                r := mload(add(signatures, add(signaturePos, 0x20)))
                                s := mload(add(signatures, add(signaturePos, 0x40)))
                                // Here we are loading the last 32 bytes, including 31 bytes
                                // of 's'. There is no 'mload8' to do this.
                                //
                                // 'byte' is not working due to the Solidity parser, so lets
                                // use the second best option, 'and'
                                v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff)
                            }
                        }
                    }
                    // SPDX-License-Identifier: LGPL-3.0-only
                    pragma solidity >=0.7.0 <0.9.0;
                    /// @title Singleton - Base for singleton contracts (should always be first super contract)
                    ///         This contract is tightly coupled to our proxy contract (see `proxies/GnosisSafeProxy.sol`)
                    /// @author Richard Meissner - <[email protected]>
                    contract Singleton {
                        // singleton always needs to be first declared variable, to ensure that it is at the same location as in the Proxy contract.
                        // It should also always be ensured that the address is stored alone (uses a full word)
                        address private singleton;
                    }
                    // SPDX-License-Identifier: LGPL-3.0-only
                    pragma solidity >=0.7.0 <0.9.0;
                    /// @title StorageAccessible - generic base contract that allows callers to access all internal storage.
                    /// @notice See https://github.com/gnosis/util-contracts/blob/bb5fe5fb5df6d8400998094fb1b32a178a47c3a1/contracts/StorageAccessible.sol
                    contract StorageAccessible {
                        /**
                         * @dev Reads `length` bytes of storage in the currents contract
                         * @param offset - the offset in the current contract's storage in words to start reading from
                         * @param length - the number of words (32 bytes) of data to read
                         * @return the bytes that were read.
                         */
                        function getStorageAt(uint256 offset, uint256 length) public view returns (bytes memory) {
                            bytes memory result = new bytes(length * 32);
                            for (uint256 index = 0; index < length; index++) {
                                // solhint-disable-next-line no-inline-assembly
                                assembly {
                                    let word := sload(add(offset, index))
                                    mstore(add(add(result, 0x20), mul(index, 0x20)), word)
                                }
                            }
                            return result;
                        }
                        /**
                         * @dev Performs a delegetecall on a targetContract in the context of self.
                         * Internally reverts execution to avoid side effects (making it static).
                         *
                         * This method reverts with data equal to `abi.encode(bool(success), bytes(response))`.
                         * Specifically, the `returndata` after a call to this method will be:
                         * `success:bool || response.length:uint256 || response:bytes`.
                         *
                         * @param targetContract Address of the contract containing the code to execute.
                         * @param calldataPayload Calldata that should be sent to the target contract (encoded method name and arguments).
                         */
                        function simulateAndRevert(address targetContract, bytes memory calldataPayload) external {
                            // solhint-disable-next-line no-inline-assembly
                            assembly {
                                let success := delegatecall(gas(), targetContract, add(calldataPayload, 0x20), mload(calldataPayload), 0, 0)
                                mstore(0x00, success)
                                mstore(0x20, returndatasize())
                                returndatacopy(0x40, 0, returndatasize())
                                revert(0, add(returndatasize(), 0x40))
                            }
                        }
                    }
                    // SPDX-License-Identifier: LGPL-3.0-only
                    pragma solidity >=0.7.0 <0.9.0;
                    /**
                     * @title GnosisSafeMath
                     * @dev Math operations with safety checks that revert on error
                     * Renamed from SafeMath to GnosisSafeMath to avoid conflicts
                     * TODO: remove once open zeppelin update to solc 0.5.0
                     */
                    library GnosisSafeMath {
                        /**
                         * @dev Multiplies two numbers, reverts on overflow.
                         */
                        function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                            // 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-solidity/pull/522
                            if (a == 0) {
                                return 0;
                            }
                            uint256 c = a * b;
                            require(c / a == b);
                            return c;
                        }
                        /**
                         * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
                         */
                        function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                            require(b <= a);
                            uint256 c = a - b;
                            return c;
                        }
                        /**
                         * @dev Adds two numbers, reverts on overflow.
                         */
                        function add(uint256 a, uint256 b) internal pure returns (uint256) {
                            uint256 c = a + b;
                            require(c >= a);
                            return c;
                        }
                        /**
                         * @dev Returns the largest of two numbers.
                         */
                        function max(uint256 a, uint256 b) internal pure returns (uint256) {
                            return a >= b ? a : b;
                        }
                    }
                    // SPDX-License-Identifier: LGPL-3.0-only
                    pragma solidity >=0.7.0 <0.9.0;
                    contract ISignatureValidatorConstants {
                        // bytes4(keccak256("isValidSignature(bytes,bytes)")
                        bytes4 internal constant EIP1271_MAGIC_VALUE = 0x20c13b0b;
                    }
                    abstract contract ISignatureValidator is ISignatureValidatorConstants {
                        /**
                         * @dev Should return whether the signature provided is valid for the provided data
                         * @param _data Arbitrary length data signed on the behalf of address(this)
                         * @param _signature Signature byte array associated with _data
                         *
                         * MUST return the bytes4 magic value 0x20c13b0b when function passes.
                         * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
                         * MUST allow external calls
                         */
                        function isValidSignature(bytes memory _data, bytes memory _signature) public view virtual returns (bytes4);
                    }