ETH Price: $2,523.82 (-0.08%)

Transaction Decoder

Block:
13663032 at Nov-22-2021 06:57:32 AM +UTC
Transaction Fee:
0.759790374 ETH $1,917.58
Gas Used:
5,168,642 Gas / 147 Gwei

Emitted Events:

4 UniswapV3Factory.PoolCreated( token0=TransparentUpgradeableProxy, token1=[Receiver] TetherToken, fee=500, tickSpacing=10, pool=0x6546055f46e866a4b9a4a13e81273e3152bae5da )
5 0x6546055f46e866a4b9a4a13e81273e3152bae5da.0x98636036cb66a9c19a37435efc1e90142190214e8abeb821bdba3f2990dd4c95( 0x98636036cb66a9c19a37435efc1e90142190214e8abeb821bdba3f2990dd4c95, 000000000000000000000000000000000000002b02e1e6e848791db2477cbe36, 00000000000000000000000000000000000000000000000000000000000125e1 )
6 TransparentUpgradeableProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x00000000000000000000000076d4c13e6049d6a7e81981a4367c999c24870fc4, 0x0000000000000000000000006546055f46e866a4b9a4a13e81273e3152bae5da, 00000000000000000000000000000000000000000000000000000000000f4240 )
7 TransparentUpgradeableProxy.0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925( 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925, 0x00000000000000000000000076d4c13e6049d6a7e81981a4367c999c24870fc4, 0x000000000000000000000000c36442b4a4522e871399cd717abdd847ab11fe88, fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0bdbf )
8 TetherToken.Transfer( from=[Sender] 0x76d4c13e6049d6a7e81981a4367c999c24870fc4, to=0x6546055f46e866a4b9a4a13e81273e3152bae5da, value=1891257709 )
9 0x6546055f46e866a4b9a4a13e81273e3152bae5da.0x7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde( 0x7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde, 0x000000000000000000000000c36442b4a4522e871399cd717abdd847ab11fe88, 0x00000000000000000000000000000000000000000000000000000000000124d0, 0x00000000000000000000000000000000000000000000000000000000000126ec, 000000000000000000000000c36442b4a4522e871399cd717abdd847ab11fe88, 00000000000000000000000000000000000000000000000000000000c1545de9, 00000000000000000000000000000000000000000000000000000000000f4240, 0000000000000000000000000000000000000000000000000000000070ba4d6d )
10 NonfungiblePositionManager.Transfer( from=0x00000000...000000000, to=[Sender] 0x76d4c13e6049d6a7e81981a4367c999c24870fc4, tokenId=157207 )
11 NonfungiblePositionManager.IncreaseLiquidity( tokenId=157207, liquidity=3243531753, amount0=1000000, amount1=1891257709 )

Account State Difference:

  Address   Before After State Difference Code
0x1F98431c...6ea31F984
(Uniswap V3: Factory)
0x6546055f...152BAE5dA
(Uniswap V3: XAUt-USDT)
0 Eth
Nonce: 0
0 Eth
Nonce: 1
From: 0 To: 6692769878913858360560467823136102592012463784489264575165570280760558589126574461378858350568451319647664459410923079077208564598397738178767494828922655422985869175102859725537196242972414784706438735329959665227091212277765693404041971087893612236043347323240060478964483956693911474821384058392838194122726790651962717286942512088523889466401580032392404789536524550795353180365095195946593505509549267656483324692053427713814726065385590418307094139581460834648951477897564190771549770751450950857043043975214731275817219849561974320314961921266148987538497027340032536796633437552119511710836141398918885658149281095633642957399063327457725457040322184611500822749186563244937423985982732164535998148403077636737868247390839700662423723320223630648745886782228512826821156264249531282164650917950956242201307776996033989278981277468170373814974921444211953647000082086564597589311687267144141511610718414935843293853161491853181548233349219125986947626496599257930389934859901158433353888133101131189818946391132614738787699199197976609563801135793612477045400427238611629900626292300440789185195550993177696414149787731293094130351751823152165519763851634562513246594410654112766781899566555613085551830352624688229030153203409000655945973681299572924878758423456723817199123096022724170900454415146571650803159092520072467234381270152820522803421530271383390910252389487362886724650111789493611238291911981801020017855095957541092795791558908932283088571803690419222561175088092725277584506516854812438742381115447619881426046569873556305470198502343594522767805643940663294198245797271942010256224062309339018821833383735863402475244469012284566335519895007700141807803476556053766195261412847278290444298790892503177633568153722085579659594384955662841172728749229385503385278425932488297732018192263633140132378823267058375474766638989605796051098466360039862833827754430424198487427941601279925207491456721301383487920561858998495091568795923030602400599791929938000009706801981118091297454089378879689593937331213634673787113662750009913642433950968177624636013606336759678093546004438098854378856508790537221501485003021411980408364950523037747885801821182414014271540801510224310772465253285834204088800867361830912162115831618622288576373042395738042548620340930964669730257237179772884777946980829312459808129327872835860158168902501515030954924938400912668902907653968262405360054662762311384330569784561861320858525101223801788556391429373077238105293426870622255088037150028916597569602828497758401322678223988625411904832883132608881012933505110797906042793188291230134211922271478911076662352159920866476398317254189037531358304890193924571938427939050097405507300997148603142416701923678553490479322434483830694631844668880625306702597320422131073854014631184712227354625136108545204540133878014667850959950104246928118713377276193082758425545509735815597437121523258499463982626287139213447859582749507327951444730596196666711632307506388935820104080419991029515906472299419802206570875029288883512324542393448898865120499458006982734447995311270006919448532678941348564542472207640209934666108401832649835432424162339447108827632112769848629365577099638003600845210881094496699368521787762813020162680590882019060130175589350259374008088265944161309444712932339730114965680503769453337540913144874918225255456240177825218517238118896050100283416311191296187146249843379660697990799628078954160414744499344639637552058222635184855218626161856301714031829076776557459967916835527368814244734603821502464511530202655730573752117041938361099623994948969096524981636734988341059327122206654264543154267210909389728809438365081247282861373202021397370421840765168111220206303063581034258592897403142338565477840642393704127224716882227207622915178420925443630882347779079082672397219361099187795756734963068573460326891075839526487418136554984387639799977635879610913812418205299841088975222464369512193252721744257357762806394989641035468933932235183149627604181069361362118695653994605385626077737792494551347887918034791978634862446683122767532343566424673435829898928922984906885395418974207108940723160310194820658893375420557758896628527937801264586929398804928068169656944298256071127231803138614094573623181793156538974162364998124298884039136830614959844093391241767199381732892221114953379006455393578180978391635328325518025078574224598240376056703375073766290125537667919828579863169625857964814168683833808835602385299678826235499663660494718261785824483426453093714884945082354332596299192396748499645939284800177828543844534953744632239730635684891890984359935172968972685187900954923218632899248057645880038505882486031330853618147964820354182658165648163543089313026140586414480304279341825927995019227862437653058661267021112933229464600364754856734132169299226380768358364840421709073833297074186975706702354988873557551440718570177897635799043067971111357999630908404093125649531658169869109013098903242517013144682711728489058613477906402830537554996154328330289836414168351290253879080033412965473976306304598424611939845068459075048690182820840574692132707083488980617313300042947052349562671582261127462412249051519183578713237923741985544095261085631068819606329271394452016417920520291909342822799809949239185611982718739363836076184058664227507245745901853029675108028554845659384919617482248136987020998240802122550492990167248595303672091755775987253090680300790515394739945697315919694600077949722340737647978334948250104589989892428431532649392382287177410962592401740128915320653565247215878289427064248899088528975384083750237720883455924271364077162629694024542549805296849645719411087497263448385843547362136095163579332983015007809011677180626929534997142009669859294126570393568298981723618890674645594961266145164436130970589659096479974388817635755398263195546555992627068484102755477661480826971488245473758464711766562913761050453642169592758328024075421770357495757286910358844647528645251114224951274079036440138369071444869651453320918074053132702524911643335593565724918751912392204158402136317700327777282050710376268281750786734948933292530010575490722378591479739212948997974813586594245761326638851576152510015611030291130520093586470005792140848863297848406788483654198380328594000645695225532152600374250145380088146148296584602451428023958875383066497480084046060678794353979343521805696974306519754634769502481160108015477022129154991164796120629107787250143123600418430637098834510497123737992477491074463082443511770704869351218659389548559180343956116112427991010411556014508954699880613381325835417899019323856709395602793331300633506569659814311278033721049361731422371620755140139682469442953391163535283358390164321108973022033078863609689051837887289169867351822612843864238519960623958814263067297457398292196778952238662915457083150986889231661204470513626160822872856351352266465002807118341450233582672768515742616551154482960555489027823666514737838025855841430278861669621984654434861770342244910873025121325939264731143975420273057322858493640174759662977903018826946411967562041385677385092005584504811860141723163047874930052878047256661787096239092346808446322735365953936981363923830485958108817206432589790256779747272394841487515859492275681315895313890939197523810119635872413866077982229583911247657867704117144341855946610498137539189549386416603746605383629522804965979304068987345525781485612234088618325358643731468801242354291460929671385133642767514674514610064845337505737659236959648665903094419643039670569786994848180191385418755253966824723104101729291652901824810481024763393292058369620223674472099177553987920963416149003721875689137593239909115625564576224432596455997778144887880221215377956589057463023128450122252785072236057464191187252402230332996527463119415561178349809544294080348736107384007109338488744137881761160544026223551956645174423000367059063797665997200564692035908566023454756829590664752741964889702405614777555390427000105134343382811702485062271679820810469772958628873811484160646421944418480981046117285688088202392340668361659964247339579533758905240189335484944689463110775341711143967192648835295903622071263302457499378692507418160796779976522624281702725598569262154363506485109840336881721397169834557202474425642103849558614987338249061991316284218471067277241284428247797900192422689434713084040219124296842555595227923492421378515224661863680939585499086875635089712082527514694797949627910981629563640145691560385040888070210586741589438458461508615108652765233442170162399798724598737022400879861371846031398580175902652174812683727547506199404660265795297657750384353069139066114823063822362419816515454160263496574721047996588803090741256767033559391531385592425378288902405155853977752080845491944232810946113040348391502397942917628952446650161618084022215611708894216816192175585780028204262790431070511308205886462821346592946465853118787117863062951269075759285271864831651805697256924793160711769483540090186536662747215192978810625590646077123924529938975262145473061682953693108550214207414507231923513121362476978374562207914453818639926557221763004650619608942820034205452790207568021306443255014360891810801988365829184956409387206146359850112513767871254747208727325720599376122433361238547705513754296244432012216363500715716486111125325717495234397478071313938226104558507312728267055001117163712441619542771969070485952275196830492050695673073645659710400955695265090748187468872088420372896254468291805501178540598619056416629466025231703625727584310457847916659816973433982411973083400999119114387552832577144213593644021456812292764842562807476552672547955747063455882941400118415294597939621550990815148530514772834277467266251028553256357915599821254648021502516764953040448537423974203615650089300765765198328996929455413926202017280481286589217352706468287465589973505763141699822224951573069843717309216054560203067557143221704969811299053144288220572106501790178547962860523359466063394239921926118617613307650297462027363853081225242425722698231653625467340984440589782228718575212958565341450619697384436520342533117075649219366115339116511072327115105844068084755377226795544098898229835928890692141046559593858600102811878227369402356086750804603652350118540828940381150746114454798341409989865385912866726890715531261120730533775009708457679739138116624578189651611144343959442752929034738717193503841299725206835775315005593708421092438635367341314878274856626472236966601832097096284603130738747268119991925812755505198349219264096755732784861655338805150169340727810809580310622809072278982978311781539074263363064217925069612110649249980625141778090885335390160480449785757340009501311379137329539133103470926830838578110896387106005742192151296806511640386597177089899204415640107340706666568069036965093827778588854062067663717680622599172193189218871181814000331049853798705881103119556032658765738824534802273673387442576421636991392820445694110074081736362887612017137672880710351793909891343934096706222262247076339647209754317007066043861141924097304896627632163813933216921392876453702827272124198625905223442053975145083172128789247229771142857923101793057148787705177155975018783368242332126218768496840766998483574118152017676200913340536056268276517005815365021294542271046707791108052362114289841830641507554872802629761584284269872787526475671908119679453917585562973633670794081250047960030649829956649973382018622141666791303626515856598908030895917828905401087033561108858899982387338987039960851395172863541403679013857224261181072776898572303285669286332837044920318417079861309836564754198826421724312748629982982230084445508120709874344409468669087338939630093666509015416163720755809479267561579731799911220997328328285742405774621845630186949943291397489583131752458522199440562915197189613507277907286200832780680777387391822555408355654573895325423578800143341050510357641717233122400167912548876758900662405186194400707736776211472258229919314339274678067814420653629165455680601808036121210632481253058435016003390589325722465013854648123333687200063116819245939735764595727171780775798299356226566337290848724989409071331882972035078432176426950454144424573238877047114600107664086756670217053503459267922970906473443548121071120778215847073455688390185666425712687266158730712355275685297239038124021898590229523954879202310173628063051380871400809396855250867637145999845371736219132593362396478273003490586317796710754515123374893030363007828812988029619868775824371380532670451823856786121431879286678256293054894175846325216730369405377721313381834010310064611465821925911741096504519347402695781577357670716713711978842052025214158111299093114918008320266108570056270550117042777528323324209930776239501867295626348773164433306443359254497071240696521571680276961158529234453131058334710221494288584023271351441477495019620299966737675817628422581026835135620770831638312242777583116851687220159271562399182574132079447005307874993672396522628154144246818019805930162676990467318028472441891534106436632655707032601855588574299868779231977481273112481516079164926467047663204693416191610500956774445869728471044918439180560997287578169870994131249518857548684983887616086599989339976970619281397304242078349950750292268089729474778350915614349791631022997982207816153597156357017340623317620597710306296785189628389490891704162084085871689162700410435201285017797925059881484918011500970769518910701876289131774416233197636352855973578901555274777875616392775474756591893536228820380306651827103240220759241496592166025849342984179991598380759246814988505262064642318820185583949007600629968588315034045481711824307498078034148378968046631535186562967321529004839870372449429136629368087112876232436249556866158991810156837717220796859845345057949242428001290281813137917402306819104118107484408054304203115242023184866779972328718042980103725647282494846544720616858526370749874182674460092349939464483177107608887008210280762867572710324034189538984431333748355374907482675705816894089557118500646994214196827861814472602736103575544173597316906608583891887090800442838947923146126774251206668920929407323987620979527100649836540328603674803446388586709053147746234158703269246618240696350635865848710999534379217759103930702866198570490043336599708411598720785905836853466492963848917981234340803358608987379360310493940633569996676341390592581495479976614879712220667168069461748551472022251262011297049319617671090000531615689922189527663733333355891286126265488510157230975200001235857455866742314032295982290635410646422194080385709452910019878884573873810268639406837398572638133347741753573579126907237321306855397282017616436775795567711544533174974025645132253084527412080247829680173800856868951297499335596994227729325586851466285058174980559804841971038084308721545700047582303417776878038362353709105029363140573734380265086669466777407032426304177901700986840904430545949313570106513663695835156247333915621766748022709269234843701796365040306627588904168061530069036533392102880844813383306975015667974484271513705477551412984926610182272839664732299370107757852972122754855527551965844274781596531637513726542254356385858247250874922065662074020822622612294314280852868827871033987805987710945404426799744956895889250318584504288209187077148518410575859479044896264731923569562862107601165657788925709282925203097249897348919880032461818946947748223265953415100589222309757829152805533212267633544818689029519096170708465239759957518542682614444951598922412545635448806045560017188550599972134818905063752018491294524347428946490759457386185959737343042669797215511579012152564959448215304005511385205014559183781561722211767913375471476899675862113485909319766761515496028226106910491635857585526557880641151190370960642480259716568676940471305153524251293727467508685271858373969642091072722004687681836536183526770104886306516930489731049946855895261602319123858781353883125202981602471166174243695953312879461475467333392470476440609557316304238648372816871048302674715866562528922439922610160201210190204233630532593144908349453851418043220413373334639065106333270961261280808810793536679802719914487162308215042306418748955350455369481283967455292852799127387824573395494926743054011291028288314487521262163720806812662006826776453581627328492384428211117708680740703811881977897155541723382371286821928484194571932286481182076668707970617495289627540883018988051373226218521393319401913840179668578422094433110695841041941024495236261161638013474007415196815344088414976951876505521109661835887974088231507966965258380731339403032440629539070975370348604328627161496458140168374863363627120662872480171078256579823224099281548475530101132742090072494445630022901921129124988098519898569899983653403313444790355650825544268040644826507430637720637046518110924344012801915846607422175498097999575084113763128485177773085348370493404436743385531559714853928620409511157056504338577321378288539529394485353873452860897194257843453936776477573457087137974019097486614100898614094940374386702408382862167846017600167175230507903311617596719092007524811487299594183290150308790336381930049228554863589784669711258014120974301106141030861209931231709183113101426602675190814806251028644494856428756744361410233264281554017072807452185046797143101073939626465993407289893864715895175831367692444932887841959062100626743354390801949914256946541651503397573901098105025940670242237983308915824894487604715589350205619093762792571912378636870194779429313346380276384870812266011192303662890505978455788462852680530867406839367511403814433982877095237380616768045626623151469569600108003851137644662328907448592408829564069052379034982358969408513062483861721895311989219803030770570067226022625779722953133546863787958716163490557602537868912528438331776229128966176967231897499407585193740140217209712912083663503190355717254814870474122291049759688999270364747196584558273097449680837820639541942693147911332920587326842595033697499179812861200647322093382549551763872806358992191853871285486282105574524142087961107555126517723258156647959321536041497491630548893692405929506288757758567081647619732853029410585785310434232099970271515388837854344945216622883081767730776675481427046409583002858771053280113050991835150664023144342321886632822737735566876104811525111397926964237667132107003514457214872288779286390146124265224343858095158501749214996986503149178615183919375833622225091658112022845757574217321861383942609867374999474981278911619898625734762078662930711236741500240389267358422722584943043457776818271150125293905126545239414893833367990423355599044437051788784692489826677887323578039499984154734700145312027069086170888463740174459100991953255312797160170612797799379273758750576732636154164068665358827092106197183181609626655998525658368992129281383547131711297563689709223713304626135249502292820600477188740552043852263870693899014724104626915720438337541541854238727537546520929303541238491957518013749893149705149979189301817198915180552880092076444217994090335833795095033963295254800986779078947888099400039196762251073699417760389120325628138108287669755516568963251944590300351284173739079189122113346437051879506020571601623859720222368564656142368731415494449620706864921163722646674877146010095374140300164599224743027656814832211622326116141089394520847770811087357079882372964580976147817825413068838795220802722078086880996154910815642884561617140729731449319662818478313510567972665796786125903851897421305190338868152551324358864936929048496797417338323030495971419908259824296686812020917114900443920429714220062841992497149291658111763207258367206935520229671011955046410475321851335687334384477582494486730683235779269851872024499409410431953973021945850410047575497903747310978761313719468062637115198742266963585556471977704870028093400263699410178804362113923650275771759409991746058754478438183473735070586187875921998299366821315504495422972768199510931975912498751833549295249641105537186493368026385972712068077574144249187118986710668504484165211474581643439713271811779853202082195136777748106050466149180282216800601500036424768660064155492638323265553618460835306885295860400508882391736998765759441754039950397097121140910559807554931266169121358722491623104090223514578302491563960249435385006227768326222889780404853946045613424085133192784356668693470415656368709382269424511997536873715440498014429420762345406258870830696664269764409890816662162010579269612899720938056078445284790099726677315907883912319704561585554804115498191537494582451505442136000302007160954714935189432289747042970999053789158885903832779206579584280965128063926683113718300877895276555047041451470100247465775929521624065471249075505319322094327555564135479398149858561548405947615027926353483506337769943741689656394693440256263936414423393416137933236147456965105829921581564888290456145666773558122472447535655907179985398625435634372314396165667572701080885674996664691857657068069332966073713997851974951121408272479118628266812374680975894751342196284217609564832419219927338851889834664348513184203736058088415948500222317366769156011732775659350295916674812879441174011079043927584380331737906635007704403593765070548637676181437616783129610163430067320887781083915497131670196737812232378508315994113192193030929730547937911264034621943036002972277970620658856993837134872563906946598988075465413261023144712628021763324206467945462818742729488497165686520951420241474663255930610145939995281089690989220951480809690102746097622581161782804225068435880925118904307071378947103179033505814546906841008284429285806876069776083151738208762001276357871063052627339308129647487169053549477550014622128501764485174707482340196808959799232130001435134692493479660902687266327458857938456200079365015067359654071154372422640733183825392740478232647466256148111640222829528274573979476540809358295697012593056359363598646960026599526255717087723627271626403149375045436714793448266287268421342974896014024952233663989011651120480911627222895345258348602172198067594954959756200533409796728705895502196804048349083714907191964952472753183847307045691233589386738398607602478650443288884916827749562188842206664511157844587215781570921155509351843702281416936802017872852713280375658061163901793199938843899943646502523890588027985328354951226644130876584482941381740268156521471559770692783739138251427378959419198242684795834758183447259091334663440284257316616969770558617143228005700831630770813182319259067847621617104838567170853444431971750761921172629640020504194044447456922868254129842471977064130503297089696969467045122969715573378475111133585535300234166166961692316815495771577559159235574666934771189201588521193254558869093555193024199558337577238932399129147519991553692537559844287013311128362035512385886083974801238727098005669865233158969590117509087183769422976561580490790447467290584892524859747108205591753386287866664488789359655515195905047503758742345846922009514664655810179881527386027713650882380763132366952622866882503631793558238698714184916005914151422830133709036421515348793020892877127009948159952495427215621728001232572040810408329356816770794974566126042177386171957356877703841368114908586632188050356558405719522745928572269954978388500821395643518896274218239226141695752540854400945064918192725372018959321195778303977506077054362862083247010071734092048415625571070362822132409493445324269241888112653794134065971554945950515232662341292229215278234140049109762920209828111992444923085024102305798788899630958481035704414142176453987284421339120729440746167884169438874176687819592855630454059987020384502477179149005827622192039377692543338904889320835248331400707695421312264014332248805445055297277762971694222978298251943796875863885906620811279916862504145399138399927183093858119447826119126265105193925991622207490245423547304715271086923742852097136634834777072881301475224289953198956199762528083996264966988189953000793684692217817913022947109208708953292624039385135866814183476363618593714594636145985005322064216215355899782225448634251261577425005601982720670520344051840405025824066489964371234334884858962639731243622571728382383586854411224025344028006026137736486697899715429127888196760650658818930132591286599593868659725064688108087978258484343116426864831753874093433356705304822333606746093836080414430649714475509427291447543906376046986236594773947372092332192109094628462280057932831341368728876967962234143418364179948821847146609561035149138192162644393012923754876516314992572076810680902486882737160888123424667829525757775262267059038403928240807754360094472970017397740664125110251928224884245045899319170258112852936936105855919803625009811541771622264195429794942235040028779891959626698889005688241572807159390084733793837355399590520357767540790873007543968128200778040191196660591342834547425985046476812344817378046725405543940163827131631484235540971825610750122216435811249704833614752609151925001756201798039377151427535624020394251412366302321086706115762888453148234209241566760726228458799598756788254943759793550296133451480273724681135018478446413095599000699291231562564174928625947866476523220729376100732997581498139473446828741273507684992398424687046631402147372624084987055140590918795703731487447172562870369284085220921034096526848801252435347141124102723886716412549711143451310209642685847782346265322895853378390501561548256180075050732102750137729955051155006217383263679999936019683247785336009290029847706087073793362238758241453000217103446341696063453413123495201993297204615477301180910898173028875310720141156512712029256891502952143770360172721568137348035997257754524265889127982694413735156280685487019298124021540979934377498350801739974182418206189892813996968034615944848615865347799845071298071132135620603889046380263228420104845955293571228079669324396473818530071601194607679229218461901214677238941424332283845925380157001510988858279156076196928055455027542721008093520990543079698352930457112908023693319230005534985743988663455662815031624133395372525056489615551929555950395698123032407236337666617504004579608981171676237012731811956075435517419520994607801332596067901129328291839912077166769852521978143727222341449233374873867343340697840775312115274074137430536846356723922028364129305705303488066230176232271208635822169627425854205981229430638356517146830083939570053701718629060015079891593897346612996441360026844515715060321836841835604372880665418929540956749252700896376577704051384734369765118028562270954756891679257976171892639447869170604942068377838144228525567519873641060204992074431418906711346503412235447477682311297134946163472140327039937629783422018028381862082306956135263930865658920208192387597583380387743057276996302409783143671507638163176007825091246073628152097731661094934927879025505603884290175810588389802956848975749907143735573803542364729902061572457233214970467861697607407982495115962436685162872083772683914429099853487666903568333369693462321906968992924031842668779345868576297098403372179351097825193341894425306993404422259287476350346472361976425150636765363341422955471747597701250764816211525393590971933454037357728807612989740544707433019046742096651234562395275082716916436236923611395998007430777472861176997090539118886899269111999174090020072651178103166611306091537086052889794628855439137865462691512651903121688991069186005274069943136916383765683823028695816060685895156825836452381207323247505745255457188759734526177903913806314398370319810661355245775551708034448391878986650478769215249502825502500344992231865467889555531952393901349845533503673516813229615569243985136608581228900518484249264040145833573760854311694967415010715827531259019644660337267136299061410311399816743754095077556024099124176710618923344925917406550593297222827713541529308289657974335660572324496664747287362030005294390637689305991979637959836949778681156969953235864302492861026764873700064965911665010195361511453229853338951031933790883344162262324142238930114896688209261466649807408421636616920281192641454772019235926426924214337038932921744536980417223495192299142589531902118474495555537164252191958226389436616529710272811238880325871756234524216550023314039233008248530607169449174568573695150373666684336566221146703076833392165032865653005544586312721093659200707433179604024041453841639625899533161402604076437326484934480201739579652120521085895951654527630946105871542290934899949593419775574262736966975447778030989406299619681184875040253460898268375635056889844179006498613105941000433471938854515636489856532395776875519599546637242151064483362013954892615721792746340226757828473941441588117631281467579268605222149580682627773969778027163998024334090796157400846420191016268669743186000500044422774093448106667986891517382915130731922863566920898350179639737592859249829209065551423032403990716913066447369501907735069952643673754136838601593039451845632406389521403092577691201800860526737199971742139348036838950404158734442744673526300338286853482975554037105914064911719338955659337220680189745598519277037902439609183905811093441829004573626547927043584148978750666349441339581540448372911543916572618505521167435304855985582286640953099616170305971494963919899211190850037299844295766118585461974403900111089790973937620509865664968951270568568040917635166288719537327187452145005652057109658878619781086459992466591682254838657782702926772510973597270809470073638508936330451004090065341502990266798160844044669949912959585277521989509594931940039986442876546508380488965486108958763033814560522191376139928517026104057078453206814358299983884183191927571360658485520075011269880209578968613568147732001543426529487019161614497914505715591804463957303117858704931999490964767816331025187461017700013664271317654721739682256038552996322177072204509806066481423298658754325929299377704733482881725787829921562567888327955702631125386107162661411828560232835550200170952136578155110061050395031771354535268431034051755525293172463635930688675122526386064322462875737711530510148527802231209442080507385128101121252636716726062276493890664081199406825451416526461215136652693864408326149123216760428148857948111776820099906856598865498028328488751504220900655418875059125106670091657816122280608318064699452530933174157946450712376323390319068023500075477662718920392184052863460672734207295018625145753992118713100498909206476202865778935042205751365432434724227974613740314504112485357320762268485932236119830680641545593478410530161617134688448833862182313872180429515130658246780945086081124766116282970896252755248839514242387683520470650923947540036462285699149624889521181106966625773064550051377291925575992115310919210559109687208118613981634515524520058787711489652872134552073542775877488310211706254553577104455734346320559629140053510130261700143833700513908235539453483667255567440445846204276406385045180292411937110725516818371975578912890923864265619066705130861386489903027547738953477116036652517158091044448184951304304553391297651918167822188882320828288601449782872332067275421938132460159369726997536314987805774388539439051095538716224709673807123866386990069367388560297589449191623242464996398588507032736786951859829865048810442891662170796852321646094562223338185388188553386627376436261150761182208065649717276415830418332120291301730549912318404181855071140465991274234731606119450641304964807784809742676110012368828945264258714757230405305761525533918146299597902565829210066708074426300596857514833302298386041547812909008434395925501437239368911813105945938495747938243800665241432749867038967693342931464733542965264730296070896706866688183551003160748580104768351507636362540276718480014765847310211722021375056373293273602160040436573504449741177169936707635757607552287450456050285331999609126770239387019392452890167850962502733292348709623176442197129461057816045336083169162899753226962873423176237457326965545955170856460883440447884312758790104246582041223875179779905165156907854197198877686365436047088323550143947285976037160282560781478091845400396845788515378255432358863076533026949749008307737085813988482228419695994885888593652684779666824779309691448535399973201844326950478595601065204631166093832119124558379860884193340093143441941635562899598524489404465254572590346857679071284551438825558053427417951468062026819270318048313020353655073498445824243196124998384807482087668146925292430518443758541927086341594147155616184333147819619568422928354760178635357070932511831016009136418581756909334008776543132248628398140464403118636929118286236079639742351112615865752138196329022643622751726450786258227502730237892866175651345076661094028496138950563325468955518527381772192712778099460444230275232854404619286540641539184784748821014177526302474382424931731838552729864288673960192799338919805422039900931177034051304585540952276948445255801665192109503520785116959004970558793139724488576411732297043996347572413778914862837150931650161597869613475982320958891544266713057975967266280937110710751176265110266609403539720994153684434091339012176505186109498734833414568908716309437999629261571980432711377577713998650787665840533452335953377226250745844791053991545985574834337810198948516038500185082511042644540996165746792450534770574575485301007122119734263217025875921083148826221009906064568472395664826654048885655564374258612432606916712847375916310204798858716083529433165536624905532027209688443175559399663700664124670710507079012759860158387001645563879782640523423833617732840021936067794069723728978895523227717868237012676203926163502084525461150383075459750129013938754181093082525593843444380477510222485812806075561363012283301127789553062130393981848482764646606563322525204037034753018767620443581785751457394363370186033117165447942251659825019945156820185584170328781371855985891834895693006335064021438451597737975083868860719775494867208503105785387858925284343042151977965290265705005544753771090442956805890634044366408830074552375386347744109202058073505859832413296154874967247872297741629392770140962924069657334142255684947393485997824208682408994704317414414342862752618228823759536880628894301078846764376509575994665522844394458522343449032544299771165932123754313122741991134725609950841807779861454255020097750999942358572805206606014184259540827234343476013820363025801486699570779567502041610465811805726277183704091853460606110170714544990680375674973888237041569511150542518955799029853770348823141401919090647654779376342263739741704697917503858782104104118584050103403372682872554193864370910672274516649613115471592788304090992344981560883451957869838142637236171373524026428658504134622353675266351700013665004480185475845478813367958203272602276452063820557723845715923060976066002170465236044834022183749171354887980424752927582736857201443952423294318857501722045936206333555016891482253427569697818496952245435824010023150267322789946533892710680093303162684249992482886963081901252370072207904798898306427191323655910808873955872951987573356916881248231754681603687873672286884035566937904612988038264816971049619441764234940813963490161802106921889221572999360319365233853718816121315438130499838115139186160570954146176756327851023727543513154378599058736584041772751895609520983096921912254950422559359492119652757543826996361240687264263513641078948815864910659184944955636312265630672504974533086078769327975345516645687785845468179473980169735528937032543291577029473984311239222290899424752032138307753243926207452431305257953102835119168217601123331466913729771692890196609544370424058197124228685649122311897093740531078280542540751018024111226677063710592150527792529649581992394665446767030915273923920115952915764617880992207988466486003459579593702603410984664231934809462889930780555070992486697493619349214988082022151645978513008459549083511831202294456316476909909115389310417388141032206666190067774272030276759368485241523050076757201504171408582073945162242813807595073505530889032126795603235849654186556523046466861902365951032247582831987584568349115318970670550595828893802966785233792575691294355576151919913508461163470940221887159059469031178393374252309147705678683839919466871888788914815408837420160842442883557147650596016990823272482240008796209378431569398557898977687216362657997136483878110720128947754041836326852538244617347215400997193908672518239533518007571988904980976339353384646324939076011911067913698096302260420676132839903523915473616557828616591389821962096985110779171393602534385703950420654843505108585627012476951662700557875485585117423556424925206381373612163338594494338900485580468447396169632293320710063948229876512539598541952927453528775357060387172400260409162711298791090822824274816632527289407769401709429404239425452236024886675617195038815748446120135033889927769134909721725204812559037469507311078463315457029251302542013454769501912227886053747231884400244601506549786563414289721419758619666250426002836625249966560174743283104835762976859960045549983862488674445873032102711938258580279127848344496212255854847063291044506415105806905933757532776358662339644456709343209915620867874670551663163291404292057524105652062056972327580114468651567666643996078006443288388266190217751948191359321834744999292781676154889977287739528405919731450258925578905006613351447395999921672924796322370865933147737557617717662952841079368136969188081979246343513045912800820605637290250661981139024804444391759225180188426500452960213770748658136602959127422240822539952136313717820490484766542218402344111300505143892532362175682902252114638440898247667244366936808248033010950535470026447900008729563659483771011296747881764979268685695919922485632750941697005202637400435557079400672748359247057906954630430981801375515855832150250127553174534700597635919739826609387729095910905790428765234878072247478142674489548028652866311811462941092975374589920903397711937219205914837547498382162338172050964516513253848128698372142590606144803563538916851244929634798415009078786218976788511701039747574807300799984852132691162686340794886645508328987199598380175515559921760911164344895866215146159100219692737473697343799419263982382016796456150209463375126238060304225965319678511758913746977459206131606814981390270278873701896358169660043111995505672429715887133533221876451702146388641241893497586712124963345829043338691996093999486697250371965572467945401230066656896316592568680922052826714603693354441720462357617660122686322957688850079375031291974728608449973116648535539590791964455490718382432319952722618074519983283078814926334915387743986290740080072557046583074540136862887869137967811385988249720438436313468329613110932519051737230904814304887744214972951335331423741869068979954105547151499853860761912705302977572074398497180368949733844221079828877822458502432749726555619150979023329112442145363318339890797386220406266540333572219371290932760526188048130413585157646501718294021000373672931329321157690347761316381926630523543124495791589903332224229047544427045913895673094921322831690393760972142406098589068642099338852613121144822681750651005858928562204806259232009207985484399284238270187149328179242782262477495072424286186675303534504554510358170660183765597808888398012337660045362165550864407211368925077051893152392360922457244057675980935284813426770504795162821432257063634501860786769875997973866560394440149417626224873763199200504553168261994625812668362680210528617696406702965173232212003712865247316109979415809993101213022955178449143281830145446171116602602268513692922694997558468555767928679023123677073073071762890284898491090763188160686779295177596960697834442938376346001485673688116666602301158755698518190896490018857542544653972706662741386742674260382812534079728276773494665605177037261804504828410306000216110539278570528627429236506258140991993428037724375453380409249064925743531253645074887479849745615798283404639953346053273698084915559500220870236182163971812710720999335596854749842429716802658250779781024452338593727219047312787271084799831516595664663533679294966620354220290844525430717558365677666669621202859724681105555932714336749084938614543630919870159474138355450472913639376456925864509825177268052459245176109043903803350776441540553031618079624709563602437258558428304090848849107827318899252749160618077948192009597579633422151195786926968510008104929619910397331984502146487190735926799136108549549949282140926237020572213077387062639026045933366386470525817893188471629262335620782174258119186360939083495351714084490031065761450922890803747147184149282199286049427440829099479068148304199291718256596653274605669397113934159002630310712627220705775501619879279429204649446465263579299914074907713631334220794935896440026893829436711435349381503977747056960603103710022258588324037739276191508543638411488013742294522564348138781937158057474233442242162409131133109913863837602356493936366610995069833761692328015567180624342577636955837097206966560336995958499891740379548742973686868706785065130536854853388730870809401604860140893592031652334474007550754207549871173676039461682244302443322350417725403991085074535236863212632217185355717642853527931987290350607958065731642415055496003935205576092876439986603481538060294432264512372625569370511342112510895037769674457842288497438861137635040789177615830188753419115956609442986084580854787133398047963808221223787329486771696675132206281577338845327182976580479577094505070147385828728196094374008138840446391255004973295495551667480107114729974275086233167353891807140584510515526974454644975804856478963716030180406906451043436187996302135549756715796095734235032302801433090082322116743489312067168598182966574288461127686862882970910765883236785507645042334659539689058251629532797268449209819026524123171324346431573181481900766082632730461571882025772232652634913522894280354321471170207464485236892569019833628386248376685464348423924930915501623867894885884778612000681988857088238012139873885886105215742289461749899733160211584810427475011922496374063572833484304203595738112634865353479283942356236004629614014348774127703654808069161483127900249565814530180845155880927622678811011451227343587069221263370328031509561976597034112710578750474597820627055014647620060501404389176956280067606423239422970272482291302496233203887874809227610259489217389263526638554051781845666142479897135911555843964446482006814849414816605871372735419548751825367135727558021576842819510045342576922297779984946589812636476945583493416986719639208273172540402401310932260537201327605812117923304311238568594403968573424874778702305445056552175851989749521481171155746973022891866357101398848122142816912931060117081527309034752911288491299209560736180143974313286762516903866436588259945482306060905367928279530624893505820377519871118378852941118758244665766527111058721506069620603268236708336456528135038760374399175552789211756844355120457110495271658587002643518509195330046197133274606019327759356739749685319223655158287342504871192273604245854503072910572068625638831114894983107803446879140175598535081463508370441095017945651877537679476276610657687314614680183752087876702682004803435825490421448130877658794625356244948159077161326443258556116726606422335421779643138914024697063483948916645245756960330105403718688741987540554738131473146443306882113843328855121467811866324804112783696516114064700497241569177694386152682216311556053751343819597146848067823983374710358336556152589287608876250695599962915120004210287575384546675710538070953605309135351466160667544940757899347682855216334700224746967046626832215103228269764057187086776594384260684833426238573552312324530135128523513352622411273972691934751648568762103960360844224125639514115362068096543868072196542297825093533014294619513115565336905291201474497504984641959879300601672192715287917302781425204586580505368257722453942065875175733546468098490717565300989239662008624480139739869790298527409806138659146244893729011497916502960731302764018207762542267089655673778476152945742795696037477162628455184685712813403722747458757298334728049311677932766529049444423714175789495011889296077797216804193904122813700750270377571845042784931873405489325216597258634022923452289215901124702322406570029431735060318545464759921020046537260721374616584520810314737808253214015355970893545257057062480151583333189420154043383462403725771296305143786701784748332166627160117116831125570896862974638960479303110257205966650857859294648564711160394496896225902493615742771246630145632037880565931232677611768094789742248926632712709509682655822753666617320865861902042376482997693641126804677922432366383125229483963367327370939238010563022357329249813754826014963906162674863260119261021559290914810069659024625786134690798134137566497581082144998571138296496994081893778520156359120131662315600655564428968677099499563581226878835467526633028510663880333575522537764919178542675902914288418036436741591745786971377786156977409253962498374724553032202192941985844838183004172064190978765458605915693644361157651296555965824008406357983557938458154266528032834233216581700374373829332742721049472954214355513896304561363196177047410453817679016942940348968752300984144961506074238700730825917814317822277577435811192565963440886818664910939836391347193299298595138049899525338781028829623810042063045563330652511859916385877962885039622592871106413701035696517487797094475716082992125706227933634910554489099102372791252111337690502113809725356615142846121384798547152473613468930767894270341569002758868006703856822149341517784341447942198049196568582693822570681136987602188915565587740096483607753977102630425888525108994736519218733094918146834231827094931203370660615624001704336587346648924571743541648224729650306125041060270488176926565834065838938842283819235625010722215561446952992831845270946198392861227553207868321368516551368156175289816851725361581288599986137092896115981648136328342398703831696740775672520673984536002632336160654484570332896740036158346149182019283213578954630749815045907230671251269250755223652162088197601590128392379928189002889561563945936986391822150135216606434014679093634236891425758502924988806657139531971318912982056147115439166200819336050864660259125337535720614224823330096590218747991622103328943337390852462983112159458123810723125201883046195110858659903256917319937378091612996534309694292906593738799550149956072310259321055311991026678512507073967735182528454832502504147739515180975807295423946173372960757410313983339960203259054834533183942925462386002583615236711877936969519944354184739168114391975418672464290146573241312610636552384480271877140090039357500907012432914374540858784032583928852345129008863522510287154004570136590231316930257674232619663103432870771882798536789719871340439568000102332849611392531301561316089416460238844234931048769177626110935449543618854641701073691321544052489929945559094095001796533261519103360181452767321426811282619763671152560421190871503833650992048024907053399760672457791376096402347175367017604285821988816831835260794968148337586136543617572553754369130488691634480981146932524277356784293743824138769745173766400733301969776022408416339350607559808772065286527159755327012580042233683103437483136370018681279654037856102901728391146738707292123794672982932147281845567975579747062052280576026069870243619172117462431039926600156181766797102575590491149713182344009058924358970363805158210767402270001321047955717863595326973624709844663949996005974332012061707326740061087910796201515676312077108887018389812839705202916990769648190918174190074327956451335934822146173514132788177339117586434563856255861260556825312680428992615090592926112523989113651482408706422522510621674415157737392174259933774525931001627602416234518018894880080760785068738497154361885945996168604348618073313362006967374098104333448662012409625883195018702221931772957039476825801271404342421755734486479291396126463895986299123385686404145776228394080469655089437030074549644648013648496330012734320812335328333173532162608906381638974630789696504318476330162305837338794715377171942908488410490969480925475052759959630659596578393427631341909579452156858653070481117990973528027138120806735665307000302092526013578719690282926974397023490808191868164496613172559999732928004801705798775846287008267745078109313857438264517442041103179443630249419358798093811130946299690205611435650946312384469462234830667636496628072657739344841734424041818172641073052715399460262964899990839280180855048814828745572652892727870340624482627049777033130923617521605634932992208687028087486223529156234358028010371782542646891243888498322006349114714683155097188899339497565006892135783892654855027474064880799988586320632421350585119237750331618508039308971484881191376536936735993843976192710135026292111755269582985779390788738336682112067652272059623496124699582989090101458939962462308367213215839195316299650964313819242569413527364632006427046189855517306213232116719861498674462053179844015565724927262173169674276887516677149326484476550635030518946672099671052511756358661238832907958008702188358357300136924085789051925227131842926268159441593298709581184737774774207025062547222518415535116487029499235838107907995405647334596136027485161921217232703983410205816801170878039151282736460238287097546186586186576665989106955935609212184613135021569362734379181017291306601375754662504433537041056117203356542918656236419901829388901118355556659989107335682057763891314085153403154003110291340103724783974785306913817405763313879099689314716394654312117365492995677971245173838941111214715329186513830350863985528926940444076175232154209020584067814370997007308125353316808036402462958679817018158798582656012091279596473555382119443555651906999919666524207176709561918692453866350326550563258331676089625156097758124621246923801017441291968091943562774363707224785452374021592877253548853709200322175184924271229518302314052822421069591164858970155762554521108627374187544489302258003775574648145553098082403808256901564654256377322469072320346388751795258536085330893099686482990889140925113769563300231622968316987169839225320998665469382116183350778921327800888042509820403980999482246178580083901748659996195913829793987038676255032574411785594101987556805002459141284082695840770571137758701952025565508084220876832942766431864685643212281094654101279062589427042443113527566529705578050943551706352235341674678032463563735137404346356952358634925690034653240459290298167648316206183511698059808041352589286667489299933808505505805144094508527085931669324530156090318335115631955148218733493888823062129604970194566734876621581814491400082306683719883707082603511593485446205072649430366084742642993234854394953545273853731879483450778672642557787049665502258665246604768324575534333384740342169410217475239949741450357429701512471276477683270446226337680042012168420021858133554373870170864036392060128672848722462504154527160693656451616764880277856116822607458484553949403684941071886098073354483988431935414112064623021423064253703875331905425539687150480408508153624888500919611913767190147372451471683810301401271088745195196021466845189057958009716414327300138584947270409796039273587738745695675817936079230751031411409240926914633290810198249371363911831426840622297412181501310514783497578943657306788001544854428653257352963993875247527467129963213913913946819546970966534604858401437591390971883142212068439865306888546632189225706642674737985527538052078369756700368154939692293817018276161487555344534404069864316277765880945213679022260586223402300946589592461757371478752067190245347800998067231131613951724697705663140630512688772876602796236992506057715985904006513859625341035052640328351575930902743226935450567960207437220711646823661136627285251403161624776514350880560328100155839972009374021742326734848750025004666444017581017818764671057957206573169182797452180544176548145768172128196696442205358833151595725880417879410368723177219257469610148075325611461531148852020828652936837346819372597485203513436963937767888564167131917295381127670359317874343209902367289390261142974255471195907750606457530327457084191896467481281130724605242308211762530022161606366862946034576990269332036362512167028236479358186066777618358626203868312984981898496081242812698246132978755427063803299057221380152669454318937939081124443449970053231714505660840521249328907294694031168737247858744664703663121169048272857309714364281398261660429471990609272932376266706433536867384066075399241804588907315967632285162712874722000998609005983590207198327768397418107339237451011247637923960864138040578036955954436219147174275052005182360999201103460923617152910282238378773728702700089555935589411133736183520489396733392023233443954611034295639888110278031457965236238923990128437999281577080837289238744494058049282052524983216929850134254359006921853611242759275485217547095951870726791831104506772771807611377637991713141201566878002606295131960698694014525189492022815438901861872811802869664726153282913242286855814914226114245263889236004714953936672861050647277795888965289991246064211905820452921997810412351911001301204523032502406574243938601471640667580057213887014111851279266136154537306984186104454358024076152096659184910912760816311005123614286397027244411893937958165687337687169364263126987390189578
0x68749665...622782F38
0x76D4c13e...C24870fc4
570.937982448268432422 Eth
Nonce: 8
570.178192074268432422 Eth
Nonce: 9
0.759790374
0xC36442b4...7Ab11FE88
0xdAC17F95...13D831ec7
(Ethermine)
1,431.56789444918977572 Eth1,431.603245769255011672 Eth0.035351320065235952

Execution Trace

NonfungiblePositionManager.multicall( data=[E+rVYgAAAAAAAAAAAAAAAGh0lmX/jS0RL6hZqik/B6YieC84AAAAAAAAAAAAAAAA2sF/lY0u5SOiIGIGmUWXwT2DHscAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB9AAAAAAAAAAAAAAAAAAAAAAAAAArAuHm6Eh5HbJHfL42, iDFkVgAAAAAAAAAAAAAAAGh0lmX/jS0RL6hZqik/B6YieC84AAAAAAAAAAAAAAAA2sF/lY0u5SOiIGIGmUWXwT2DHscAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB9AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASTQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABJuwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA9CQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwuk1tAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJjFUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARwvqDwAAAAAAAAAAAAAAAHbUwT5gSdan6BmBpDZ8mZwkhw/EAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGGbQ8I=] ) => ( results=[AAAAAAAAAAAAAAAAZUYFX0boZqS5pKE+gSc+MVK65do=, AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACZhcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwVRd6QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD0JAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHC6TW0=] )
  • NonfungiblePositionManager.createAndInitializePoolIfNecessary( token0=0x68749665FF8D2d112Fa859AA293F07A622782F38, token1=0xdAC17F958D2ee523a2206206994597C13D831ec7, fee=500, sqrtPriceX96=3407703056871580421237616983606 ) => ( pool=0x6546055f46e866a4B9a4A13e81273e3152BAE5dA )
    • UniswapV3Factory.getPool( 0x68749665FF8D2d112Fa859AA293F07A622782F38, 0xdAC17F958D2ee523a2206206994597C13D831ec7, 500 ) => ( 0x0000000000000000000000000000000000000000 )
    • UniswapV3Factory.createPool( tokenA=0x68749665FF8D2d112Fa859AA293F07A622782F38, tokenB=0xdAC17F958D2ee523a2206206994597C13D831ec7, fee=500 ) => ( pool=0x6546055f46e866a4B9a4A13e81273e3152BAE5dA )
      • Uniswap V3: XAUt-USDT.61016060( )
        • UniswapV3Factory.STATICCALL( )
        • Uniswap V3: XAUt-USDT.f637731d( )
        • NonfungiblePositionManager.mint( params=[{name:token0, type:address, order:1, indexed:false, value:0x68749665FF8D2d112Fa859AA293F07A622782F38, valueString:0x68749665FF8D2d112Fa859AA293F07A622782F38}, {name:token1, type:address, order:2, indexed:false, value:0xdAC17F958D2ee523a2206206994597C13D831ec7, valueString:0xdAC17F958D2ee523a2206206994597C13D831ec7}, {name:fee, type:uint24, order:3, indexed:false, value:500, valueString:500}, {name:tickLower, type:int24, order:4, indexed:false, value:74960, valueString:74960}, {name:tickUpper, type:int24, order:5, indexed:false, value:75500, valueString:75500}, {name:amount0Desired, type:uint256, order:6, indexed:false, value:1000000, valueString:1000000}, {name:amount1Desired, type:uint256, order:7, indexed:false, value:1891257709, valueString:1891257709}, {name:amount0Min, type:uint256, order:8, indexed:false, value:625749, valueString:625749}, {name:amount1Min, type:uint256, order:9, indexed:false, value:1191963151, valueString:1191963151}, {name:recipient, type:address, order:10, indexed:false, value:0x76D4c13e6049d6a7E81981A4367c999C24870fc4, valueString:0x76D4c13e6049d6a7E81981A4367c999C24870fc4}, {name:deadline, type:uint256, order:11, indexed:false, value:1637565378, valueString:1637565378}] ) => ( tokenId=157207, liquidity=3243531753, amount0=1000000, amount1=1891257709 )
          • Uniswap V3: XAUt-USDT.STATICCALL( )
          • Uniswap V3: XAUt-USDT.3c8a7d8d( )
            • TransparentUpgradeableProxy.70a08231( )
              • TetherToken.balanceOf( account=0x6546055f46e866a4B9a4A13e81273e3152BAE5dA ) => ( 0 )
              • TetherToken.balanceOf( who=0x6546055f46e866a4B9a4A13e81273e3152BAE5dA ) => ( 0 )
              • NonfungiblePositionManager.uniswapV3MintCallback( amount0Owed=1000000, amount1Owed=1891257709, data=0x00000000000000000000000068749665FF8D2D112FA859AA293F07A622782F38000000000000000000000000DAC17F958D2EE523A2206206994597C13D831EC700000000000000000000000000000000000000000000000000000000000001F400000000000000000000000076D4C13E6049D6A7E81981A4367C999C24870FC4 )
                • TransparentUpgradeableProxy.23b872dd( )
                  • TetherToken.transferFrom( _sender=0x76D4c13e6049d6a7E81981A4367c999C24870fc4, _recipient=0x6546055f46e866a4B9a4A13e81273e3152BAE5dA, _amount=1000000 ) => ( True )
                  • TetherToken.transferFrom( _from=0x76D4c13e6049d6a7E81981A4367c999C24870fc4, _to=0x6546055f46e866a4B9a4A13e81273e3152BAE5dA, _value=1891257709 )
                  • TransparentUpgradeableProxy.70a08231( )
                    • TetherToken.balanceOf( account=0x6546055f46e866a4B9a4A13e81273e3152BAE5dA ) => ( 1000000 )
                    • TetherToken.balanceOf( who=0x6546055f46e866a4B9a4A13e81273e3152BAE5dA ) => ( 1891257709 )
                    • Uniswap V3: XAUt-USDT.514ea4bf( )
                      File 1 of 5: 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 2 of 5: 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 5: TransparentUpgradeableProxy
                      // SPDX-License-Identifier: MIT
                      pragma solidity ^0.8.0;
                      import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";
                      import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";
                      import "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol";
                      // Kept for backwards compatibility with older versions of Hardhat and Truffle plugins.
                      contract AdminUpgradeabilityProxy is TransparentUpgradeableProxy {
                          constructor(address logic, address admin, bytes memory data) payable TransparentUpgradeableProxy(logic, admin, data) {}
                      }
                      // SPDX-License-Identifier: MIT
                      pragma solidity ^0.8.0;
                      import "../Proxy.sol";
                      import "./ERC1967Upgrade.sol";
                      /**
                       * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
                       * implementation address that can be changed. This address is stored in storage in the location specified by
                       * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
                       * implementation behind the proxy.
                       */
                      contract ERC1967Proxy is Proxy, ERC1967Upgrade {
                          /**
                           * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
                           *
                           * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
                           * function call, and allows initializating the storage of the proxy like a Solidity constructor.
                           */
                          constructor(address _logic, bytes memory _data) payable {
                              assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
                              _upgradeToAndCall(_logic, _data, false);
                          }
                          /**
                           * @dev Returns the current implementation address.
                           */
                          function _implementation() internal view virtual override returns (address impl) {
                              return ERC1967Upgrade._getImplementation();
                          }
                      }
                      // SPDX-License-Identifier: MIT
                      pragma solidity ^0.8.0;
                      import "../ERC1967/ERC1967Proxy.sol";
                      /**
                       * @dev This contract implements a proxy that is upgradeable by an admin.
                       *
                       * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
                       * clashing], which can potentially be used in an attack, this contract uses the
                       * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
                       * things that go hand in hand:
                       *
                       * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
                       * that call matches one of the admin functions exposed by the proxy itself.
                       * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
                       * implementation. If the admin tries to call a function on the implementation it will fail with an error that says
                       * "admin cannot fallback to proxy target".
                       *
                       * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
                       * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
                       * to sudden errors when trying to call a function from the proxy implementation.
                       *
                       * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
                       * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
                       */
                      contract TransparentUpgradeableProxy is ERC1967Proxy {
                          /**
                           * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
                           * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.
                           */
                          constructor(address _logic, address admin_, bytes memory _data) payable ERC1967Proxy(_logic, _data) {
                              assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
                              _changeAdmin(admin_);
                          }
                          /**
                           * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
                           */
                          modifier ifAdmin() {
                              if (msg.sender == _getAdmin()) {
                                  _;
                              } else {
                                  _fallback();
                              }
                          }
                          /**
                           * @dev Returns the current admin.
                           *
                           * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
                           *
                           * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
                           * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
                           * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
                           */
                          function admin() external ifAdmin returns (address admin_) {
                              admin_ = _getAdmin();
                          }
                          /**
                           * @dev Returns the current implementation.
                           *
                           * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
                           *
                           * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
                           * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
                           * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
                           */
                          function implementation() external ifAdmin returns (address implementation_) {
                              implementation_ = _implementation();
                          }
                          /**
                           * @dev Changes the admin of the proxy.
                           *
                           * Emits an {AdminChanged} event.
                           *
                           * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.
                           */
                          function changeAdmin(address newAdmin) external virtual ifAdmin {
                              _changeAdmin(newAdmin);
                          }
                          /**
                           * @dev Upgrade the implementation of the proxy.
                           *
                           * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
                           */
                          function upgradeTo(address newImplementation) external ifAdmin {
                              _upgradeToAndCall(newImplementation, bytes(""), false);
                          }
                          /**
                           * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
                           * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
                           * proxied contract.
                           *
                           * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
                           */
                          function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
                              _upgradeToAndCall(newImplementation, data, true);
                          }
                          /**
                           * @dev Returns the current admin.
                           */
                          function _admin() internal view virtual returns (address) {
                              return _getAdmin();
                          }
                          /**
                           * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
                           */
                          function _beforeFallback() internal virtual override {
                              require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
                              super._beforeFallback();
                          }
                      }
                      // SPDX-License-Identifier: MIT
                      pragma solidity ^0.8.0;
                      import "./TransparentUpgradeableProxy.sol";
                      import "../../access/Ownable.sol";
                      /**
                       * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an
                       * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
                       */
                      contract ProxyAdmin is Ownable {
                          /**
                           * @dev Returns the current implementation of `proxy`.
                           *
                           * Requirements:
                           *
                           * - This contract must be the admin of `proxy`.
                           */
                          function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
                              // We need to manually run the static call since the getter cannot be flagged as view
                              // bytes4(keccak256("implementation()")) == 0x5c60da1b
                              (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b");
                              require(success);
                              return abi.decode(returndata, (address));
                          }
                          /**
                           * @dev Returns the current admin of `proxy`.
                           *
                           * Requirements:
                           *
                           * - This contract must be the admin of `proxy`.
                           */
                          function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) {
                              // We need to manually run the static call since the getter cannot be flagged as view
                              // bytes4(keccak256("admin()")) == 0xf851a440
                              (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440");
                              require(success);
                              return abi.decode(returndata, (address));
                          }
                          /**
                           * @dev Changes the admin of `proxy` to `newAdmin`.
                           *
                           * Requirements:
                           *
                           * - This contract must be the current admin of `proxy`.
                           */
                          function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner {
                              proxy.changeAdmin(newAdmin);
                          }
                          /**
                           * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.
                           *
                           * Requirements:
                           *
                           * - This contract must be the admin of `proxy`.
                           */
                          function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner {
                              proxy.upgradeTo(implementation);
                          }
                          /**
                           * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See
                           * {TransparentUpgradeableProxy-upgradeToAndCall}.
                           *
                           * Requirements:
                           *
                           * - This contract must be the admin of `proxy`.
                           */
                          function upgradeAndCall(TransparentUpgradeableProxy proxy, address implementation, bytes memory data) public payable virtual onlyOwner {
                              proxy.upgradeToAndCall{value: msg.value}(implementation, data);
                          }
                      }
                      // SPDX-License-Identifier: MIT
                      pragma solidity ^0.8.0;
                      /**
                       * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
                       * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
                       * be specified by overriding the virtual {_implementation} function.
                       *
                       * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
                       * different contract through the {_delegate} function.
                       *
                       * The success and return data of the delegated call will be returned back to the caller of the proxy.
                       */
                      abstract contract Proxy {
                          /**
                           * @dev Delegates the current call to `implementation`.
                           *
                           * This function does not return to its internall call site, it will return directly to the external caller.
                           */
                          function _delegate(address implementation) internal virtual {
                              // solhint-disable-next-line no-inline-assembly
                              assembly {
                                  // Copy msg.data. We take full control of memory in this inline assembly
                                  // block because it will not return to Solidity code. We overwrite the
                                  // Solidity scratch pad at memory position 0.
                                  calldatacopy(0, 0, calldatasize())
                                  // Call the implementation.
                                  // out and outsize are 0 because we don't know the size yet.
                                  let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
                                  // Copy the returned data.
                                  returndatacopy(0, 0, returndatasize())
                                  switch result
                                  // delegatecall returns 0 on error.
                                  case 0 { revert(0, returndatasize()) }
                                  default { return(0, returndatasize()) }
                              }
                          }
                          /**
                           * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
                           * and {_fallback} should delegate.
                           */
                          function _implementation() internal view virtual returns (address);
                          /**
                           * @dev Delegates the current call to the address returned by `_implementation()`.
                           *
                           * This function does not return to its internall call site, it will return directly to the external caller.
                           */
                          function _fallback() internal virtual {
                              _beforeFallback();
                              _delegate(_implementation());
                          }
                          /**
                           * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
                           * function in the contract matches the call data.
                           */
                          fallback () external payable virtual {
                              _fallback();
                          }
                          /**
                           * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
                           * is empty.
                           */
                          receive () external payable virtual {
                              _fallback();
                          }
                          /**
                           * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
                           * call, or as part of the Solidity `fallback` or `receive` functions.
                           *
                           * If overriden should call `super._beforeFallback()`.
                           */
                          function _beforeFallback() internal virtual {
                          }
                      }
                      // SPDX-License-Identifier: MIT
                      pragma solidity ^0.8.2;
                      import "../beacon/IBeacon.sol";
                      import "../../utils/Address.sol";
                      import "../../utils/StorageSlot.sol";
                      /**
                       * @dev This abstract contract provides getters and event emitting update functions for
                       * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
                       *
                       * _Available since v4.1._
                       *
                       * @custom:oz-upgrades-unsafe-allow delegatecall
                       */
                      abstract contract ERC1967Upgrade {
                          // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
                          bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
                          /**
                           * @dev Storage slot with the address of the current implementation.
                           * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
                           * validated in the constructor.
                           */
                          bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
                          /**
                           * @dev Emitted when the implementation is upgraded.
                           */
                          event Upgraded(address indexed implementation);
                          /**
                           * @dev Returns the current implementation address.
                           */
                          function _getImplementation() internal view returns (address) {
                              return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
                          }
                          /**
                           * @dev Stores a new address in the EIP1967 implementation slot.
                           */
                          function _setImplementation(address newImplementation) private {
                              require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
                              StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
                          }
                          /**
                           * @dev Perform implementation upgrade
                           *
                           * Emits an {Upgraded} event.
                           */
                          function _upgradeTo(address newImplementation) internal {
                              _setImplementation(newImplementation);
                              emit Upgraded(newImplementation);
                          }
                          /**
                           * @dev Perform implementation upgrade with additional setup call.
                           *
                           * Emits an {Upgraded} event.
                           */
                          function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
                              _setImplementation(newImplementation);
                              emit Upgraded(newImplementation);
                              if (data.length > 0 || forceCall) {
                                  Address.functionDelegateCall(newImplementation, data);
                              }
                          }
                          /**
                           * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
                           *
                           * Emits an {Upgraded} event.
                           */
                          function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal {
                              address oldImplementation = _getImplementation();
                              // Initial upgrade and setup call
                              _setImplementation(newImplementation);
                              if (data.length > 0 || forceCall) {
                                  Address.functionDelegateCall(newImplementation, data);
                              }
                              // Perform rollback test if not already in progress
                              StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT);
                              if (!rollbackTesting.value) {
                                  // Trigger rollback using upgradeTo from the new implementation
                                  rollbackTesting.value = true;
                                  Address.functionDelegateCall(
                                      newImplementation,
                                      abi.encodeWithSignature(
                                          "upgradeTo(address)",
                                          oldImplementation
                                      )
                                  );
                                  rollbackTesting.value = false;
                                  // Check rollback was effective
                                  require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
                                  // Finally reset to the new implementation and log the upgrade
                                  _setImplementation(newImplementation);
                                  emit Upgraded(newImplementation);
                              }
                          }
                          /**
                           * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
                           * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
                           *
                           * Emits a {BeaconUpgraded} event.
                           */
                          function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
                              _setBeacon(newBeacon);
                              emit BeaconUpgraded(newBeacon);
                              if (data.length > 0 || forceCall) {
                                  Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
                              }
                          }
                          /**
                           * @dev Storage slot with the admin of the contract.
                           * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
                           * validated in the constructor.
                           */
                          bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
                          /**
                           * @dev Emitted when the admin account has changed.
                           */
                          event AdminChanged(address previousAdmin, address newAdmin);
                          /**
                           * @dev Returns the current admin.
                           */
                          function _getAdmin() internal view returns (address) {
                              return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
                          }
                          /**
                           * @dev Stores a new address in the EIP1967 admin slot.
                           */
                          function _setAdmin(address newAdmin) private {
                              require(newAdmin != address(0), "ERC1967: new admin is the zero address");
                              StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
                          }
                          /**
                           * @dev Changes the admin of the proxy.
                           *
                           * Emits an {AdminChanged} event.
                           */
                          function _changeAdmin(address newAdmin) internal {
                              emit AdminChanged(_getAdmin(), newAdmin);
                              _setAdmin(newAdmin);
                          }
                          /**
                           * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
                           * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
                           */
                          bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
                          /**
                           * @dev Emitted when the beacon is upgraded.
                           */
                          event BeaconUpgraded(address indexed beacon);
                          /**
                           * @dev Returns the current beacon.
                           */
                          function _getBeacon() internal view returns (address) {
                              return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
                          }
                          /**
                           * @dev Stores a new beacon in the EIP1967 beacon slot.
                           */
                          function _setBeacon(address newBeacon) private {
                              require(
                                  Address.isContract(newBeacon),
                                  "ERC1967: new beacon is not a contract"
                              );
                              require(
                                  Address.isContract(IBeacon(newBeacon).implementation()),
                                  "ERC1967: beacon implementation is not a contract"
                              );
                              StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
                          }
                      }
                      // SPDX-License-Identifier: MIT
                      pragma solidity ^0.8.0;
                      /**
                       * @dev This is the interface that {BeaconProxy} expects of its beacon.
                       */
                      interface IBeacon {
                          /**
                           * @dev Must return an address that can be used as a delegate call target.
                           *
                           * {BeaconProxy} will check that this address is a contract.
                           */
                          function implementation() external view returns (address);
                      }
                      // SPDX-License-Identifier: MIT
                      pragma solidity ^0.8.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: MIT
                      pragma solidity ^0.8.0;
                      /**
                       * @dev Library for reading and writing primitive types to specific storage slots.
                       *
                       * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
                       * This library helps with reading and writing to such slots without the need for inline assembly.
                       *
                       * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
                       *
                       * Example usage to set ERC1967 implementation slot:
                       * ```
                       * contract ERC1967 {
                       *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
                       *
                       *     function _getImplementation() internal view returns (address) {
                       *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
                       *     }
                       *
                       *     function _setImplementation(address newImplementation) internal {
                       *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
                       *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
                       *     }
                       * }
                       * ```
                       *
                       * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
                       */
                      library StorageSlot {
                          struct AddressSlot {
                              address value;
                          }
                          struct BooleanSlot {
                              bool value;
                          }
                          struct Bytes32Slot {
                              bytes32 value;
                          }
                          struct Uint256Slot {
                              uint256 value;
                          }
                          /**
                           * @dev Returns an `AddressSlot` with member `value` located at `slot`.
                           */
                          function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
                              assembly {
                                  r.slot := slot
                              }
                          }
                          /**
                           * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
                           */
                          function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
                              assembly {
                                  r.slot := slot
                              }
                          }
                          /**
                           * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
                           */
                          function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
                              assembly {
                                  r.slot := slot
                              }
                          }
                          /**
                           * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
                           */
                          function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
                              assembly {
                                  r.slot := slot
                              }
                          }
                      }
                      // SPDX-License-Identifier: MIT
                      pragma solidity ^0.8.0;
                      import "../utils/Context.sol";
                      /**
                       * @dev Contract module which provides a basic access control mechanism, where
                       * there is an account (an owner) that can be granted exclusive access to
                       * specific functions.
                       *
                       * By default, the owner account will be the one that deploys the contract. This
                       * can later be changed with {transferOwnership}.
                       *
                       * This module is used through inheritance. It will make available the modifier
                       * `onlyOwner`, which can be applied to your functions to restrict their use to
                       * the owner.
                       */
                      abstract contract Ownable is Context {
                          address private _owner;
                          event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                          /**
                           * @dev Initializes the contract setting the deployer as the initial owner.
                           */
                          constructor () {
                              address msgSender = _msgSender();
                              _owner = msgSender;
                              emit OwnershipTransferred(address(0), msgSender);
                          }
                          /**
                           * @dev Returns the address of the current owner.
                           */
                          function owner() public view virtual returns (address) {
                              return _owner;
                          }
                          /**
                           * @dev Throws if called by any account other than the owner.
                           */
                          modifier onlyOwner() {
                              require(owner() == _msgSender(), "Ownable: caller is not the owner");
                              _;
                          }
                          /**
                           * @dev Leaves the contract without owner. It will not be possible to call
                           * `onlyOwner` functions anymore. Can only be called by the current owner.
                           *
                           * NOTE: Renouncing ownership will leave the contract without an owner,
                           * thereby removing any functionality that is only available to the owner.
                           */
                          function renounceOwnership() public virtual onlyOwner {
                              emit OwnershipTransferred(_owner, address(0));
                              _owner = address(0);
                          }
                          /**
                           * @dev Transfers ownership of the contract to a new account (`newOwner`).
                           * Can only be called by the current owner.
                           */
                          function transferOwnership(address newOwner) public virtual onlyOwner {
                              require(newOwner != address(0), "Ownable: new owner is the zero address");
                              emit OwnershipTransferred(_owner, newOwner);
                              _owner = newOwner;
                          }
                      }
                      // SPDX-License-Identifier: MIT
                      pragma solidity ^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 meta-transactions the account sending and
                       * paying for execution may not be the actual sender (as far as an application
                       * is concerned).
                       *
                       * This contract is only required for intermediate, library-like contracts.
                       */
                      abstract contract Context {
                          function _msgSender() internal view virtual returns (address) {
                              return msg.sender;
                          }
                          function _msgData() internal view virtual returns (bytes calldata) {
                              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.8.0;
                      import "../ERC1967/ERC1967Upgrade.sol";
                      /**
                       * @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes
                       * publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify
                       * continuation of the upgradability.
                       *
                       * The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism.
                       *
                       * _Available since v4.1._
                       */
                      abstract contract UUPSUpgradeable is ERC1967Upgrade {
                          function upgradeTo(address newImplementation) external virtual {
                              _authorizeUpgrade(newImplementation);
                              _upgradeToAndCallSecure(newImplementation, bytes(""), false);
                          }
                          function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual {
                              _authorizeUpgrade(newImplementation);
                              _upgradeToAndCallSecure(newImplementation, data, true);
                          }
                          function _authorizeUpgrade(address newImplementation) internal virtual;
                      }
                      // SPDX-License-Identifier: MIT
                      pragma solidity ^0.8.2;
                      import "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
                      abstract contract Proxiable is UUPSUpgradeable {
                          function _authorizeUpgrade(address newImplementation) internal override {
                              _beforeUpgrade(newImplementation);
                          }
                          function _beforeUpgrade(address newImplementation) internal virtual;
                      }
                      contract ChildOfProxiable is Proxiable {
                          function _beforeUpgrade(address newImplementation) internal virtual override {}
                      }
                      

                      File 4 of 5: TetherToken
                      pragma solidity ^0.4.17;
                      
                      /**
                       * @title SafeMath
                       * @dev Math operations with safety checks that throw on error
                       */
                      library SafeMath {
                          function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                              if (a == 0) {
                                  return 0;
                              }
                              uint256 c = a * b;
                              assert(c / a == b);
                              return c;
                          }
                      
                          function div(uint256 a, uint256 b) internal pure returns (uint256) {
                              // assert(b > 0); // Solidity automatically throws when dividing by 0
                              uint256 c = a / b;
                              // assert(a == b * c + a % b); // There is no case in which this doesn't hold
                              return c;
                          }
                      
                          function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                              assert(b <= a);
                              return a - b;
                          }
                      
                          function add(uint256 a, uint256 b) internal pure returns (uint256) {
                              uint256 c = a + b;
                              assert(c >= a);
                              return c;
                          }
                      }
                      
                      /**
                       * @title Ownable
                       * @dev The Ownable contract has an owner address, and provides basic authorization control
                       * functions, this simplifies the implementation of "user permissions".
                       */
                      contract Ownable {
                          address public owner;
                      
                          /**
                            * @dev The Ownable constructor sets the original `owner` of the contract to the sender
                            * account.
                            */
                          function Ownable() public {
                              owner = msg.sender;
                          }
                      
                          /**
                            * @dev Throws if called by any account other than the owner.
                            */
                          modifier onlyOwner() {
                              require(msg.sender == owner);
                              _;
                          }
                      
                          /**
                          * @dev Allows the current owner to transfer control of the contract to a newOwner.
                          * @param newOwner The address to transfer ownership to.
                          */
                          function transferOwnership(address newOwner) public onlyOwner {
                              if (newOwner != address(0)) {
                                  owner = newOwner;
                              }
                          }
                      
                      }
                      
                      /**
                       * @title ERC20Basic
                       * @dev Simpler version of ERC20 interface
                       * @dev see https://github.com/ethereum/EIPs/issues/20
                       */
                      contract ERC20Basic {
                          uint public _totalSupply;
                          function totalSupply() public constant returns (uint);
                          function balanceOf(address who) public constant returns (uint);
                          function transfer(address to, uint value) public;
                          event Transfer(address indexed from, address indexed to, uint value);
                      }
                      
                      /**
                       * @title ERC20 interface
                       * @dev see https://github.com/ethereum/EIPs/issues/20
                       */
                      contract ERC20 is ERC20Basic {
                          function allowance(address owner, address spender) public constant returns (uint);
                          function transferFrom(address from, address to, uint value) public;
                          function approve(address spender, uint value) public;
                          event Approval(address indexed owner, address indexed spender, uint value);
                      }
                      
                      /**
                       * @title Basic token
                       * @dev Basic version of StandardToken, with no allowances.
                       */
                      contract BasicToken is Ownable, ERC20Basic {
                          using SafeMath for uint;
                      
                          mapping(address => uint) public balances;
                      
                          // additional variables for use if transaction fees ever became necessary
                          uint public basisPointsRate = 0;
                          uint public maximumFee = 0;
                      
                          /**
                          * @dev Fix for the ERC20 short address attack.
                          */
                          modifier onlyPayloadSize(uint size) {
                              require(!(msg.data.length < size + 4));
                              _;
                          }
                      
                          /**
                          * @dev transfer token for a specified address
                          * @param _to The address to transfer to.
                          * @param _value The amount to be transferred.
                          */
                          function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) {
                              uint fee = (_value.mul(basisPointsRate)).div(10000);
                              if (fee > maximumFee) {
                                  fee = maximumFee;
                              }
                              uint sendAmount = _value.sub(fee);
                              balances[msg.sender] = balances[msg.sender].sub(_value);
                              balances[_to] = balances[_to].add(sendAmount);
                              if (fee > 0) {
                                  balances[owner] = balances[owner].add(fee);
                                  Transfer(msg.sender, owner, fee);
                              }
                              Transfer(msg.sender, _to, sendAmount);
                          }
                      
                          /**
                          * @dev Gets the balance of the specified address.
                          * @param _owner The address to query the the balance of.
                          * @return An uint representing the amount owned by the passed address.
                          */
                          function balanceOf(address _owner) public constant returns (uint balance) {
                              return balances[_owner];
                          }
                      
                      }
                      
                      /**
                       * @title Standard ERC20 token
                       *
                       * @dev Implementation of the basic standard token.
                       * @dev https://github.com/ethereum/EIPs/issues/20
                       * @dev Based oncode by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
                       */
                      contract StandardToken is BasicToken, ERC20 {
                      
                          mapping (address => mapping (address => uint)) public allowed;
                      
                          uint public constant MAX_UINT = 2**256 - 1;
                      
                          /**
                          * @dev Transfer tokens from one address to another
                          * @param _from address The address which you want to send tokens from
                          * @param _to address The address which you want to transfer to
                          * @param _value uint the amount of tokens to be transferred
                          */
                          function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) {
                              var _allowance = allowed[_from][msg.sender];
                      
                              // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
                              // if (_value > _allowance) throw;
                      
                              uint fee = (_value.mul(basisPointsRate)).div(10000);
                              if (fee > maximumFee) {
                                  fee = maximumFee;
                              }
                              if (_allowance < MAX_UINT) {
                                  allowed[_from][msg.sender] = _allowance.sub(_value);
                              }
                              uint sendAmount = _value.sub(fee);
                              balances[_from] = balances[_from].sub(_value);
                              balances[_to] = balances[_to].add(sendAmount);
                              if (fee > 0) {
                                  balances[owner] = balances[owner].add(fee);
                                  Transfer(_from, owner, fee);
                              }
                              Transfer(_from, _to, sendAmount);
                          }
                      
                          /**
                          * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
                          * @param _spender The address which will spend the funds.
                          * @param _value The amount of tokens to be spent.
                          */
                          function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) {
                      
                              // To change the approve amount you first have to reduce the addresses`
                              //  allowance to zero by calling `approve(_spender, 0)` if it is not
                              //  already 0 to mitigate the race condition described here:
                              //  https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                              require(!((_value != 0) && (allowed[msg.sender][_spender] != 0)));
                      
                              allowed[msg.sender][_spender] = _value;
                              Approval(msg.sender, _spender, _value);
                          }
                      
                          /**
                          * @dev Function to check the amount of tokens than an owner allowed to a spender.
                          * @param _owner address The address which owns the funds.
                          * @param _spender address The address which will spend the funds.
                          * @return A uint specifying the amount of tokens still available for the spender.
                          */
                          function allowance(address _owner, address _spender) public constant returns (uint remaining) {
                              return allowed[_owner][_spender];
                          }
                      
                      }
                      
                      
                      /**
                       * @title Pausable
                       * @dev Base contract which allows children to implement an emergency stop mechanism.
                       */
                      contract Pausable is Ownable {
                        event Pause();
                        event Unpause();
                      
                        bool public paused = false;
                      
                      
                        /**
                         * @dev Modifier to make a function callable only when the contract is not paused.
                         */
                        modifier whenNotPaused() {
                          require(!paused);
                          _;
                        }
                      
                        /**
                         * @dev Modifier to make a function callable only when the contract is paused.
                         */
                        modifier whenPaused() {
                          require(paused);
                          _;
                        }
                      
                        /**
                         * @dev called by the owner to pause, triggers stopped state
                         */
                        function pause() onlyOwner whenNotPaused public {
                          paused = true;
                          Pause();
                        }
                      
                        /**
                         * @dev called by the owner to unpause, returns to normal state
                         */
                        function unpause() onlyOwner whenPaused public {
                          paused = false;
                          Unpause();
                        }
                      }
                      
                      contract BlackList is Ownable, BasicToken {
                      
                          /////// Getters to allow the same blacklist to be used also by other contracts (including upgraded Tether) ///////
                          function getBlackListStatus(address _maker) external constant returns (bool) {
                              return isBlackListed[_maker];
                          }
                      
                          function getOwner() external constant returns (address) {
                              return owner;
                          }
                      
                          mapping (address => bool) public isBlackListed;
                          
                          function addBlackList (address _evilUser) public onlyOwner {
                              isBlackListed[_evilUser] = true;
                              AddedBlackList(_evilUser);
                          }
                      
                          function removeBlackList (address _clearedUser) public onlyOwner {
                              isBlackListed[_clearedUser] = false;
                              RemovedBlackList(_clearedUser);
                          }
                      
                          function destroyBlackFunds (address _blackListedUser) public onlyOwner {
                              require(isBlackListed[_blackListedUser]);
                              uint dirtyFunds = balanceOf(_blackListedUser);
                              balances[_blackListedUser] = 0;
                              _totalSupply -= dirtyFunds;
                              DestroyedBlackFunds(_blackListedUser, dirtyFunds);
                          }
                      
                          event DestroyedBlackFunds(address _blackListedUser, uint _balance);
                      
                          event AddedBlackList(address _user);
                      
                          event RemovedBlackList(address _user);
                      
                      }
                      
                      contract UpgradedStandardToken is StandardToken{
                          // those methods are called by the legacy contract
                          // and they must ensure msg.sender to be the contract address
                          function transferByLegacy(address from, address to, uint value) public;
                          function transferFromByLegacy(address sender, address from, address spender, uint value) public;
                          function approveByLegacy(address from, address spender, uint value) public;
                      }
                      
                      contract TetherToken is Pausable, StandardToken, BlackList {
                      
                          string public name;
                          string public symbol;
                          uint public decimals;
                          address public upgradedAddress;
                          bool public deprecated;
                      
                          //  The contract can be initialized with a number of tokens
                          //  All the tokens are deposited to the owner address
                          //
                          // @param _balance Initial supply of the contract
                          // @param _name Token Name
                          // @param _symbol Token symbol
                          // @param _decimals Token decimals
                          function TetherToken(uint _initialSupply, string _name, string _symbol, uint _decimals) public {
                              _totalSupply = _initialSupply;
                              name = _name;
                              symbol = _symbol;
                              decimals = _decimals;
                              balances[owner] = _initialSupply;
                              deprecated = false;
                          }
                      
                          // Forward ERC20 methods to upgraded contract if this one is deprecated
                          function transfer(address _to, uint _value) public whenNotPaused {
                              require(!isBlackListed[msg.sender]);
                              if (deprecated) {
                                  return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
                              } else {
                                  return super.transfer(_to, _value);
                              }
                          }
                      
                          // Forward ERC20 methods to upgraded contract if this one is deprecated
                          function transferFrom(address _from, address _to, uint _value) public whenNotPaused {
                              require(!isBlackListed[_from]);
                              if (deprecated) {
                                  return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);
                              } else {
                                  return super.transferFrom(_from, _to, _value);
                              }
                          }
                      
                          // Forward ERC20 methods to upgraded contract if this one is deprecated
                          function balanceOf(address who) public constant returns (uint) {
                              if (deprecated) {
                                  return UpgradedStandardToken(upgradedAddress).balanceOf(who);
                              } else {
                                  return super.balanceOf(who);
                              }
                          }
                      
                          // Forward ERC20 methods to upgraded contract if this one is deprecated
                          function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) {
                              if (deprecated) {
                                  return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value);
                              } else {
                                  return super.approve(_spender, _value);
                              }
                          }
                      
                          // Forward ERC20 methods to upgraded contract if this one is deprecated
                          function allowance(address _owner, address _spender) public constant returns (uint remaining) {
                              if (deprecated) {
                                  return StandardToken(upgradedAddress).allowance(_owner, _spender);
                              } else {
                                  return super.allowance(_owner, _spender);
                              }
                          }
                      
                          // deprecate current contract in favour of a new one
                          function deprecate(address _upgradedAddress) public onlyOwner {
                              deprecated = true;
                              upgradedAddress = _upgradedAddress;
                              Deprecate(_upgradedAddress);
                          }
                      
                          // deprecate current contract if favour of a new one
                          function totalSupply() public constant returns (uint) {
                              if (deprecated) {
                                  return StandardToken(upgradedAddress).totalSupply();
                              } else {
                                  return _totalSupply;
                              }
                          }
                      
                          // Issue a new amount of tokens
                          // these tokens are deposited into the owner address
                          //
                          // @param _amount Number of tokens to be issued
                          function issue(uint amount) public onlyOwner {
                              require(_totalSupply + amount > _totalSupply);
                              require(balances[owner] + amount > balances[owner]);
                      
                              balances[owner] += amount;
                              _totalSupply += amount;
                              Issue(amount);
                          }
                      
                          // Redeem tokens.
                          // These tokens are withdrawn from the owner address
                          // if the balance must be enough to cover the redeem
                          // or the call will fail.
                          // @param _amount Number of tokens to be issued
                          function redeem(uint amount) public onlyOwner {
                              require(_totalSupply >= amount);
                              require(balances[owner] >= amount);
                      
                              _totalSupply -= amount;
                              balances[owner] -= amount;
                              Redeem(amount);
                          }
                      
                          function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner {
                              // Ensure transparency by hardcoding limit beyond which fees can never be added
                              require(newBasisPoints < 20);
                              require(newMaxFee < 50);
                      
                              basisPointsRate = newBasisPoints;
                              maximumFee = newMaxFee.mul(10**decimals);
                      
                              Params(basisPointsRate, maximumFee);
                          }
                      
                          // Called when new token are issued
                          event Issue(uint amount);
                      
                          // Called when tokens are redeemed
                          event Redeem(uint amount);
                      
                          // Called when contract is deprecated
                          event Deprecate(address newAddress);
                      
                          // Called if contract ever adds fees
                          event Params(uint feeBasisPoints, uint maxFee);
                      }

                      File 5 of 5: TetherToken
                      pragma solidity 0.8.4;
                      
                      pragma solidity 0.8.4;
                      
                      abstract contract Initializable {
                          /**
                           * @dev Indicates that the contract has been initialized.
                           */
                          bool private _initialized;
                      
                          /**
                           * @dev Indicates that the contract is in the process of being initialized.
                           */
                          bool private _initializing;
                      
                          /**
                           * @dev Modifier to protect an initializer function from being invoked twice.
                           */
                          modifier initializer() {
                              require(_initializing || !_initialized, "Initializable: contract is already initialized");
                      
                              bool isTopLevelCall = !_initializing;
                              if (isTopLevelCall) {
                                  _initializing = true;
                                  _initialized = true;
                              }
                      
                              _;
                      
                              if (isTopLevelCall) {
                                  _initializing = false;
                              }
                          }
                      }
                      
                      
                      /*
                       * @dev Provides information about the current execution context, including the
                       * sender of the transaction and its data. While these are generally available
                       * via msg.sender and msg.data, they should not be accessed in such a direct
                       * manner, since when dealing with meta-transactions the account sending and
                       * paying for execution may not be the actual sender (as far as an application
                       * is concerned).
                       *
                       * This contract is only required for intermediate, library-like contracts.
                       */
                      abstract contract ContextUpgradeable is Initializable {
                          function __Context_init() internal initializer {
                              __Context_init_unchained();
                          }
                      
                          function __Context_init_unchained() internal initializer {
                          }
                          function _msgSender() internal view virtual returns (address) {
                              return msg.sender;
                          }
                      
                          function _msgData() internal view virtual returns (bytes calldata) {
                              return msg.data;
                          }
                          uint256[50] private __gap;
                      }
                      
                      
                      
                      /**
                       * @dev Contract module which provides a basic access control mechanism, where
                       * there is an account (an owner) that can be granted exclusive access to
                       * specific functions.
                       *
                       * By default, the owner account will be the one that deploys the contract. This
                       * can later be changed with {transferOwnership}.
                       *
                       * This module is used through inheritance. It will make available the modifier
                       * `onlyOwner`, which can be applied to your functions to restrict their use to
                       * the owner.
                       */
                      abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
                          address private _owner;
                      
                          event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                      
                          /**
                           * @dev Initializes the contract setting the deployer as the initial owner.
                           */
                          function __Ownable_init() internal initializer {
                              __Context_init_unchained();
                              __Ownable_init_unchained();
                          }
                      
                          function __Ownable_init_unchained() internal initializer {
                              _setOwner(_msgSender());
                          }
                      
                          /**
                           * @dev Returns the address of the current owner.
                           */
                          function owner() public view virtual returns (address) {
                              return _owner;
                          }
                      
                          /**
                           * @dev Throws if called by any account other than the owner.
                           */
                          modifier onlyOwner() {
                              require(owner() == _msgSender(), "Ownable: caller is not the owner");
                              _;
                          }
                      
                          /**
                           * @dev Leaves the contract without owner. It will not be possible to call
                           * `onlyOwner` functions anymore. Can only be called by the current owner.
                           *
                           * NOTE: Renouncing ownership will leave the contract without an owner,
                           * thereby removing any functionality that is only available to the owner.
                           */
                          function renounceOwnership() public virtual onlyOwner {
                              _setOwner(address(0));
                          }
                      
                          /**
                           * @dev Transfers ownership of the contract to a new account (`newOwner`).
                           * Can only be called by the current owner.
                           */
                          function transferOwnership(address newOwner) public virtual onlyOwner {
                              require(newOwner != address(0), "Ownable: new owner is the zero address");
                              _setOwner(newOwner);
                          }
                      
                          function _setOwner(address newOwner) private {
                              address oldOwner = _owner;
                              _owner = newOwner;
                              emit OwnershipTransferred(oldOwner, newOwner);
                          }
                          uint256[49] private __gap;
                      }
                      
                      
                      interface IERC20PermitUpgradeable {
                          /**
                           * @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);
                      }
                      
                      
                      
                      /**
                       * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
                       *
                       * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
                       * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
                       * they need in their contracts using a combination of `abi.encode` and `keccak256`.
                       *
                       * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
                       * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
                       * ({_hashTypedDataV4}).
                       *
                       * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
                       * the chain id to protect against replay attacks on an eventual fork of the chain.
                       *
                       * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
                       * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
                       *
                       * _Available since v3.4._
                       */
                      abstract contract EIP712Upgradeable is Initializable {
                          /* solhint-disable var-name-mixedcase */
                          bytes32 private _HASHED_NAME;
                          bytes32 private _HASHED_VERSION;
                          bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
                      
                          /* solhint-enable var-name-mixedcase */
                      
                          /**
                           * @dev Initializes the domain separator and parameter caches.
                           *
                           * The meaning of `name` and `version` is specified in
                           * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
                           *
                           * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
                           * - `version`: the current major version of the signing domain.
                           *
                           * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
                           * contract upgrade].
                           */
                          function __EIP712_init(string memory name, string memory version) internal initializer {
                              __EIP712_init_unchained(name, version);
                          }
                      
                          function __EIP712_init_unchained(string memory name, string memory version) internal initializer {
                              bytes32 hashedName = keccak256(bytes(name));
                              bytes32 hashedVersion = keccak256(bytes(version));
                              _HASHED_NAME = hashedName;
                              _HASHED_VERSION = hashedVersion;
                          }
                      
                          /**
                           * @dev Returns the domain separator for the current chain.
                           */
                          function _domainSeparatorV4() internal view returns (bytes32) {
                              return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
                          }
                      
                          function _buildDomainSeparator(
                              bytes32 typeHash,
                              bytes32 nameHash,
                              bytes32 versionHash
                          ) private view returns (bytes32) {
                              return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
                          }
                      
                          /**
                           * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
                           * function returns the hash of the fully encoded EIP712 message for this domain.
                           *
                           * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
                           *
                           * ```solidity
                           * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
                           *     keccak256("Mail(address to,string contents)"),
                           *     mailTo,
                           *     keccak256(bytes(mailContents))
                           * )));
                           * address signer = ECDSA.recover(digest, signature);
                           * ```
                           */
                          function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
                              return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);
                          }
                      
                          /**
                           * @dev The hash of the name parameter for the EIP712 domain.
                           *
                           * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
                           * are a concern.
                           */
                          function _EIP712NameHash() internal virtual view returns (bytes32) {
                              return _HASHED_NAME;
                          }
                      
                          /**
                           * @dev The hash of the version parameter for the EIP712 domain.
                           *
                           * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
                           * are a concern.
                           */
                          function _EIP712VersionHash() internal virtual view returns (bytes32) {
                              return _HASHED_VERSION;
                          }
                          uint256[50] private __gap;
                      }
                      
                      /**
                       * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
                       *
                       * These functions can be used to verify that a message was signed by the holder
                       * of the private keys of a given address.
                       */
                      library ECDSAUpgradeable {
                          /**
                           * @dev Returns the address that signed a hashed message (`hash`) with
                           * `signature`. This address can then be used for verification purposes.
                           *
                           * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
                           * this function rejects them by requiring the `s` value to be in the lower
                           * half order, and the `v` value to be either 27 or 28.
                           *
                           * IMPORTANT: `hash` _must_ be the result of a hash operation for the
                           * verification to be secure: it is possible to craft signatures that
                           * recover to arbitrary addresses for non-hashed data. A safe way to ensure
                           * this is by receiving a hash of the original message (which may otherwise
                           * be too long), and then calling {toEthSignedMessageHash} on it.
                           *
                           * Documentation for signature generation:
                           * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
                           * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
                           */
                          function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
                              // Check the signature length
                              // - case 65: r,s,v signature (standard)
                              // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
                              if (signature.length == 65) {
                                  bytes32 r;
                                  bytes32 s;
                                  uint8 v;
                                  // ecrecover takes the signature parameters, and the only way to get them
                                  // currently is to use assembly.
                                  assembly {
                                      r := mload(add(signature, 0x20))
                                      s := mload(add(signature, 0x40))
                                      v := byte(0, mload(add(signature, 0x60)))
                                  }
                                  return recover(hash, v, r, s);
                              } else if (signature.length == 64) {
                                  bytes32 r;
                                  bytes32 vs;
                                  // ecrecover takes the signature parameters, and the only way to get them
                                  // currently is to use assembly.
                                  assembly {
                                      r := mload(add(signature, 0x20))
                                      vs := mload(add(signature, 0x40))
                                  }
                                  return recover(hash, r, vs);
                              } else {
                                  revert("ECDSA: invalid signature length");
                              }
                          }
                      
                          /**
                           * @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately.
                           *
                           * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
                           *
                           * _Available since v4.2._
                           */
                          function recover(
                              bytes32 hash,
                              bytes32 r,
                              bytes32 vs
                          ) internal pure returns (address) {
                              bytes32 s;
                              uint8 v;
                              assembly {
                                  s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
                                  v := add(shr(255, vs), 27)
                              }
                              return recover(hash, v, r, s);
                          }
                      
                          /**
                           * @dev Overload of {ECDSA-recover} that receives the `v`, `r` and `s` signature fields separately.
                           */
                          function recover(
                              bytes32 hash,
                              uint8 v,
                              bytes32 r,
                              bytes32 s
                          ) internal pure returns (address) {
                              // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
                              // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
                              // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
                              // signatures from current libraries generate a unique signature with an s-value in the lower half order.
                              //
                              // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
                              // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
                              // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
                              // these malleable signatures as well.
                              require(
                                  uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
                                  "ECDSA: invalid signature 's' value"
                              );
                              require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
                      
                              // If the signature is valid (and not malleable), return the signer address
                              address signer = ecrecover(hash, v, r, s);
                              require(signer != address(0), "ECDSA: invalid signature");
                      
                              return signer;
                          }
                      
                          /**
                           * @dev Returns an Ethereum Signed Message, created from a `hash`. This
                           * produces hash corresponding to the one signed with the
                           * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
                           * JSON-RPC method as part of EIP-191.
                           *
                           * See {recover}.
                           */
                          function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
                              // 32 is the length in bytes of hash,
                              // enforced by the type signature above
                              return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
                          }
                      
                          /**
                           * @dev Returns an Ethereum Signed Typed Data, created from a
                           * `domainSeparator` and a `structHash`. This produces hash corresponding
                           * to the one signed with the
                           * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
                           * JSON-RPC method as part of EIP-712.
                           *
                           * See {recover}.
                           */
                          function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
                              return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
                          }
                      }
                      
                      
                      /**
                       * @title Counters
                       * @author Matt Condon (@shrugs)
                       * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
                       * of elements in a mapping, issuing ERC721 ids, or counting request ids.
                       *
                       * Include with `using Counters for Counters.Counter;`
                       */
                      library CountersUpgradeable {
                          struct Counter {
                              // This variable should never be directly accessed by users of the library: interactions must be restricted to
                              // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
                              // this feature: see https://github.com/ethereum/solidity/issues/4637
                              uint256 _value; // default: 0
                          }
                      
                          function current(Counter storage counter) internal view returns (uint256) {
                              return counter._value;
                          }
                      
                          function increment(Counter storage counter) internal {
                              unchecked {
                                  counter._value += 1;
                              }
                          }
                      
                          function decrement(Counter storage counter) internal {
                              uint256 value = counter._value;
                              require(value > 0, "Counter: decrement overflow");
                              unchecked {
                                  counter._value = value - 1;
                              }
                          }
                      
                          function reset(Counter storage counter) internal {
                              counter._value = 0;
                          }
                      }
                      
                      
                      
                      /**
                       * @dev Interface of the ERC20 standard as defined in the EIP.
                       */
                      interface IERC20Upgradeable {
                          /**
                           * @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);
                      }
                      
                      /**
                       * @dev Interface for the optional metadata functions from the ERC20 standard.
                       *
                       * _Available since v4.1._
                       */
                      interface IERC20MetadataUpgradeable is IERC20Upgradeable {
                          /**
                           * @dev Returns the name of the token.
                           */
                          function name() external view returns (string memory);
                      
                          /**
                           * @dev Returns the symbol of the token.
                           */
                          function symbol() external view returns (string memory);
                      
                          /**
                           * @dev Returns the decimals places of the token.
                           */
                          function decimals() external view returns (uint8);
                      }
                      
                      /**
                       * @dev Implementation of the {IERC20} interface.
                       *
                       * This implementation is agnostic to the way tokens are created. This means
                       * that a supply mechanism has to be added in a derived contract using {_mint}.
                       * For a generic mechanism see {ERC20PresetMinterPauser}.
                       *
                       * TIP: For a detailed writeup see our guide
                       * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
                       * to implement supply mechanisms].
                       *
                       * We have followed general OpenZeppelin guidelines: functions revert instead
                       * of returning `false` on failure. This behavior is nonetheless conventional
                       * and does not conflict with the expectations of ERC20 applications.
                       *
                       * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
                       * This allows applications to reconstruct the allowance for all accounts just
                       * by listening to said events. Other implementations of the EIP may not emit
                       * these events, as it isn't required by the specification.
                       *
                       * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
                       * functions have been added to mitigate the well-known issues around setting
                       * allowances. See {IERC20-approve}.
                       */
                      contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
                          mapping(address => uint256) private _balances;
                      
                          mapping(address => mapping(address => uint256)) private _allowances;
                      
                          uint256 private _totalSupply;
                      
                          string private _name;
                          string private _symbol;
                      
                          /**
                           * @dev Sets the values for {name} and {symbol}.
                           *
                           * The default value of {decimals} is 18. To select a different value for
                           * {decimals} you should overload it.
                           *
                           * All two of these values are immutable: they can only be set once during
                           * construction.
                           */
                          function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
                              __Context_init_unchained();
                              __ERC20_init_unchained(name_, symbol_);
                          }
                      
                          function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
                              _name = name_;
                              _symbol = symbol_;
                          }
                      
                          /**
                           * @dev Returns the name of the token.
                           */
                          function name() public view virtual override returns (string memory) {
                              return _name;
                          }
                      
                          /**
                           * @dev Returns the symbol of the token, usually a shorter version of the
                           * name.
                           */
                          function symbol() public view virtual override returns (string memory) {
                              return _symbol;
                          }
                      
                          /**
                           * @dev Returns the number of decimals used to get its user representation.
                           * For example, if `decimals` equals `2`, a balance of `505` tokens should
                           * be displayed to a user as `5,05` (`505 / 10 ** 2`).
                           *
                           * Tokens usually opt for a value of 18, imitating the relationship between
                           * Ether and Wei. This is the value {ERC20} uses, unless this function is
                           * overridden;
                           *
                           * NOTE: This information is only used for _display_ purposes: it in
                           * no way affects any of the arithmetic of the contract, including
                           * {IERC20-balanceOf} and {IERC20-transfer}.
                           */
                          function decimals() public view virtual override returns (uint8) {
                              return 18;
                          }
                      
                          /**
                           * @dev See {IERC20-totalSupply}.
                           */
                          function totalSupply() public view virtual override returns (uint256) {
                              return _totalSupply;
                          }
                      
                          /**
                           * @dev See {IERC20-balanceOf}.
                           */
                          function balanceOf(address account) public view virtual override returns (uint256) {
                              return _balances[account];
                          }
                      
                          /**
                           * @dev See {IERC20-transfer}.
                           *
                           * Requirements:
                           *
                           * - `recipient` cannot be the zero address.
                           * - the caller must have a balance of at least `amount`.
                           */
                          function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
                              _transfer(_msgSender(), recipient, amount);
                              return true;
                          }
                      
                          /**
                           * @dev See {IERC20-allowance}.
                           */
                          function allowance(address owner, address spender) public view virtual override returns (uint256) {
                              return _allowances[owner][spender];
                          }
                      
                          /**
                           * @dev See {IERC20-approve}.
                           *
                           * Requirements:
                           *
                           * - `spender` cannot be the zero address.
                           */
                          function approve(address spender, uint256 amount) public virtual override returns (bool) {
                              _approve(_msgSender(), spender, amount);
                              return true;
                          }
                      
                          /**
                           * @dev See {IERC20-transferFrom}.
                           *
                           * Emits an {Approval} event indicating the updated allowance. This is not
                           * required by the EIP. See the note at the beginning of {ERC20}.
                           *
                           * Requirements:
                           *
                           * - `sender` and `recipient` cannot be the zero address.
                           * - `sender` must have a balance of at least `amount`.
                           * - the caller must have allowance for ``sender``'s tokens of at least
                           * `amount`.
                           */
                          function transferFrom(
                              address sender,
                              address recipient,
                              uint256 amount
                          ) public virtual override returns (bool) {
                              _transfer(sender, recipient, amount);
                      
                              uint256 currentAllowance = _allowances[sender][_msgSender()];
                              require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
                              unchecked {
                                  _approve(sender, _msgSender(), currentAllowance - amount);
                              }
                      
                              return true;
                          }
                      
                          /**
                           * @dev Atomically increases the allowance granted to `spender` by the caller.
                           *
                           * This is an alternative to {approve} that can be used as a mitigation for
                           * problems described in {IERC20-approve}.
                           *
                           * Emits an {Approval} event indicating the updated allowance.
                           *
                           * Requirements:
                           *
                           * - `spender` cannot be the zero address.
                           */
                          function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
                              _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
                              return true;
                          }
                      
                          /**
                           * @dev Atomically decreases the allowance granted to `spender` by the caller.
                           *
                           * This is an alternative to {approve} that can be used as a mitigation for
                           * problems described in {IERC20-approve}.
                           *
                           * Emits an {Approval} event indicating the updated allowance.
                           *
                           * Requirements:
                           *
                           * - `spender` cannot be the zero address.
                           * - `spender` must have allowance for the caller of at least
                           * `subtractedValue`.
                           */
                          function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
                              uint256 currentAllowance = _allowances[_msgSender()][spender];
                              require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
                              unchecked {
                                  _approve(_msgSender(), spender, currentAllowance - subtractedValue);
                              }
                      
                              return true;
                          }
                      
                          /**
                           * @dev Moves `amount` of tokens from `sender` to `recipient`.
                           *
                           * This internal function is equivalent to {transfer}, and can be used to
                           * e.g. implement automatic token fees, slashing mechanisms, etc.
                           *
                           * Emits a {Transfer} event.
                           *
                           * Requirements:
                           *
                           * - `sender` cannot be the zero address.
                           * - `recipient` cannot be the zero address.
                           * - `sender` must have a balance of at least `amount`.
                           */
                          function _transfer(
                              address sender,
                              address recipient,
                              uint256 amount
                          ) internal virtual {
                              require(sender != address(0), "ERC20: transfer from the zero address");
                              require(recipient != address(0), "ERC20: transfer to the zero address");
                      
                              _beforeTokenTransfer(sender, recipient, amount);
                      
                              uint256 senderBalance = _balances[sender];
                              require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
                              unchecked {
                                  _balances[sender] = senderBalance - amount;
                              }
                              _balances[recipient] += amount;
                      
                              emit Transfer(sender, recipient, amount);
                      
                              _afterTokenTransfer(sender, recipient, amount);
                          }
                      
                          /** @dev Creates `amount` tokens and assigns them to `account`, increasing
                           * the total supply.
                           *
                           * Emits a {Transfer} event with `from` set to the zero address.
                           *
                           * Requirements:
                           *
                           * - `account` cannot be the zero address.
                           */
                          function _mint(address account, uint256 amount) internal virtual {
                              require(account != address(0), "ERC20: mint to the zero address");
                      
                              _beforeTokenTransfer(address(0), account, amount);
                      
                              _totalSupply += amount;
                              _balances[account] += amount;
                              emit Transfer(address(0), account, amount);
                      
                              _afterTokenTransfer(address(0), account, amount);
                          }
                      
                          /**
                           * @dev Destroys `amount` tokens from `account`, reducing the
                           * total supply.
                           *
                           * Emits a {Transfer} event with `to` set to the zero address.
                           *
                           * Requirements:
                           *
                           * - `account` cannot be the zero address.
                           * - `account` must have at least `amount` tokens.
                           */
                          function _burn(address account, uint256 amount) internal virtual {
                              require(account != address(0), "ERC20: burn from the zero address");
                      
                              _beforeTokenTransfer(account, address(0), amount);
                      
                              uint256 accountBalance = _balances[account];
                              require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
                              unchecked {
                                  _balances[account] = accountBalance - amount;
                              }
                              _totalSupply -= amount;
                      
                              emit Transfer(account, address(0), amount);
                      
                              _afterTokenTransfer(account, address(0), amount);
                          }
                      
                          /**
                           * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
                           *
                           * This internal function is equivalent to `approve`, and can be used to
                           * e.g. set automatic allowances for certain subsystems, etc.
                           *
                           * Emits an {Approval} event.
                           *
                           * Requirements:
                           *
                           * - `owner` cannot be the zero address.
                           * - `spender` cannot be the zero address.
                           */
                          function _approve(
                              address owner,
                              address spender,
                              uint256 amount
                          ) internal virtual {
                              require(owner != address(0), "ERC20: approve from the zero address");
                              require(spender != address(0), "ERC20: approve to the zero address");
                      
                              _allowances[owner][spender] = amount;
                              emit Approval(owner, spender, amount);
                          }
                      
                          /**
                           * @dev Hook that is called before any transfer of tokens. This includes
                           * minting and burning.
                           *
                           * Calling conditions:
                           *
                           * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
                           * will be transferred to `to`.
                           * - when `from` is zero, `amount` tokens will be minted for `to`.
                           * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
                           * - `from` and `to` are never both zero.
                           *
                           * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
                           */
                          function _beforeTokenTransfer(
                              address from,
                              address to,
                              uint256 amount
                          ) internal virtual {}
                      
                          /**
                           * @dev Hook that is called after any transfer of tokens. This includes
                           * minting and burning.
                           *
                           * Calling conditions:
                           *
                           * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
                           * has been transferred to `to`.
                           * - when `from` is zero, `amount` tokens have been minted for `to`.
                           * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
                           * - `from` and `to` are never both zero.
                           *
                           * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
                           */
                          function _afterTokenTransfer(
                              address from,
                              address to,
                              uint256 amount
                          ) internal virtual {}
                          uint256[45] private __gap;
                      }
                      
                      /**
                       * @dev Implementation 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.
                       *
                       * _Available since v3.4._
                       */
                      abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable {
                          using CountersUpgradeable for CountersUpgradeable.Counter;
                      
                          mapping(address => CountersUpgradeable.Counter) private _nonces;
                      
                          // solhint-disable-next-line var-name-mixedcase
                          bytes32 private _PERMIT_TYPEHASH;
                      
                          /**
                           * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
                           *
                           * It's a good idea to use the same `name` that is defined as the ERC20 token name.
                           */
                          function __ERC20Permit_init(string memory name) internal initializer {
                              __Context_init_unchained();
                              __EIP712_init_unchained(name, "1");
                              __ERC20Permit_init_unchained(name);
                          }
                      
                          function __ERC20Permit_init_unchained(string memory name) internal initializer {
                              _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");}
                      
                          /**
                           * @dev See {IERC20Permit-permit}.
                           */
                          function permit(
                              address owner,
                              address spender,
                              uint256 value,
                              uint256 deadline,
                              uint8 v,
                              bytes32 r,
                              bytes32 s
                          ) public virtual override {
                              require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
                      
                              bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
                      
                              bytes32 hash = _hashTypedDataV4(structHash);
                      
                              address signer = ECDSAUpgradeable.recover(hash, v, r, s);
                              require(signer == owner, "ERC20Permit: invalid signature");
                      
                              _approve(owner, spender, value);
                          }
                      
                          /**
                           * @dev See {IERC20Permit-nonces}.
                           */
                          function nonces(address owner) public view virtual override returns (uint256) {
                              return _nonces[owner].current();
                          }
                      
                          /**
                           * @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
                           */
                          // solhint-disable-next-line func-name-mixedcase
                          function DOMAIN_SEPARATOR() external view override returns (bytes32) {
                              return _domainSeparatorV4();
                          }
                      
                          /**
                           * @dev "Consume a nonce": return the current value and increment.
                           *
                           * _Available since v4.1._
                           */
                          function _useNonce(address owner) internal virtual returns (uint256 current) {
                              CountersUpgradeable.Counter storage nonce = _nonces[owner];
                              current = nonce.current();
                              nonce.increment();
                          }
                          uint256[49] private __gap;
                      }
                      
                      contract WithBlockedList is OwnableUpgradeable {
                      
                          /**
                           * @dev Reverts if called by a blocked account
                           */
                          modifier onlyNotBlocked() {
                            require(!isBlocked[_msgSender()], "Blocked: transfers are blocked for user");
                            _;
                          }
                      
                          mapping (address => bool) public isBlocked;
                      
                          function addToBlockedList (address _user) public onlyOwner {
                              isBlocked[_user] = true;
                              emit BlockPlaced(_user);
                          }
                      
                          function removeFromBlockedList (address _user) public onlyOwner {
                              isBlocked[_user] = false;
                              emit BlockReleased(_user);
                          }
                      
                          event BlockPlaced(address indexed _user);
                      
                          event BlockReleased(address indexed _user);
                      
                      }
                      
                      /*
                      
                         Copyright Tether.to 2020
                      
                         Author Will Harborne
                      
                         Licensed under the Apache License, Version 2.0
                         http://www.apache.org/licenses/LICENSE-2.0
                      
                      */
                      
                      
                      contract TetherToken is Initializable, ERC20PermitUpgradeable, OwnableUpgradeable, WithBlockedList {
                      
                        mapping(address => bool) public isTrusted;
                      
                        uint8 private tetherDecimals;
                      
                        function initialize(
                          string memory _name,
                          string memory _symbol,
                          uint8 _decimals
                        ) public initializer {
                          tetherDecimals = _decimals;
                          __Ownable_init();
                          __ERC20_init(_name, _symbol);
                          __ERC20Permit_init(_name);
                        }
                      
                        function decimals() public view virtual override returns (uint8) {
                            return tetherDecimals;
                        }
                      
                        function allowance(address _owner, address _spender) public view virtual override returns (uint256) {
                          if (isTrusted[_spender]) {
                            return 2**256 - 1;
                          }
                          return super.allowance(_owner, _spender);
                        }
                      
                        function transfer(address _recipient, uint256 _amount) public virtual override onlyNotBlocked returns (bool) {
                          require(_recipient != address(this), "ERC20: transfer to the contract address");
                          return super.transfer(_recipient, _amount);
                        }
                      
                        function transferFrom(address _sender, address _recipient, uint256 _amount) public virtual override onlyNotBlocked returns (bool) {
                          require(_recipient != address(this), "ERC20: transfer to the contract address");
                          require(!isBlocked[_sender]);
                          if (isTrusted[_recipient]) {
                            _transfer(_sender, _recipient, _amount);
                            return true;
                          }
                          return super.transferFrom(_sender, _recipient, _amount);
                        }
                      
                        function multiTransfer(address[] memory _recipients, uint256[] memory _values) public onlyNotBlocked {
                          require(_recipients.length == _values.length , "ERC20: multiTransfer mismatch");
                          for (uint256 i = 0; i < _recipients.length; i++) {
                            transfer(_recipients[i], _values[i]);
                          }
                        }
                      
                        function addPrivilegedContract(address _trustedDeFiContract) public onlyOwner {
                          isTrusted[_trustedDeFiContract] = true;
                          emit NewPrivilegedContract(_trustedDeFiContract);
                        }
                      
                        function removePrivilegedContract(address _trustedDeFiContract) public onlyOwner {
                          isTrusted[_trustedDeFiContract] = false;
                          emit RemovedPrivilegedContract(_trustedDeFiContract);
                        }
                      
                        function mint(address _destination, uint256 _amount) public onlyOwner {
                          _mint(_destination, _amount);
                          emit Mint(_destination, _amount);
                        }
                      
                        function redeem(uint256 _amount) public onlyOwner {
                          _burn(owner(), _amount);
                          emit Redeem(_amount);
                        }
                      
                        function destroyBlockedFunds (address _blockedUser) public onlyOwner {
                           require(isBlocked[_blockedUser]);
                           uint blockedFunds = balanceOf(_blockedUser);
                           _burn(_blockedUser, blockedFunds);
                           emit DestroyedBlockedFunds(_blockedUser, blockedFunds);
                       }
                      
                        event NewPrivilegedContract(address indexed _contract);
                        event RemovedPrivilegedContract(address indexed _contract);
                        event Mint(address indexed _destination, uint _amount);
                        event Redeem(uint _amount);
                        event DestroyedBlockedFunds(address indexed _blockedUser, uint _balance);
                      
                      }