ETH Price: $2,934.85 (+6.41%)

Transaction Decoder

Block:
17065452 at Apr-17-2023 08:55:35 AM +UTC
Transaction Fee:
0.077624425149789378 ETH $227.82
Gas Used:
2,290,078 Gas / 33.895974351 Gwei

Emitted Events:

30 UniswapV2Factory.PairCreated( token0=WETH9, token1=TransparentUpgradeableProxy, pair=UniswapV2Pair, 3630 )
31 TransparentUpgradeableProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x0000000000000000000000000fc59c9c998537c940a9dfc7dacde533a9c496fe, 0x0000000000000000000000007119602160d2072b6e329d1c1ac93a48ff9e770b, 000000000000000000000000000000000000000000000000002386f26fc10000 )
32 WETH9.Deposit( dst=[Receiver] UniswapV2Router02, wad=10000000000000000 )
33 WETH9.Transfer( src=[Receiver] UniswapV2Router02, dst=UniswapV2Pair, wad=10000000000000000 )
34 UniswapV2Pair.Transfer( from=0x0000000000000000000000000000000000000000, to=0x0000000000000000000000000000000000000000, value=1000 )
35 UniswapV2Pair.Transfer( from=0x0000000000000000000000000000000000000000, to=[Sender] 0x0fc59c9c998537c940a9dfc7dacde533a9c496fe, value=9999999999999000 )
36 UniswapV2Pair.Sync( reserve0=10000000000000000, reserve1=10000000000000000 )
37 UniswapV2Pair.Mint( sender=[Receiver] UniswapV2Router02, amount0=10000000000000000, amount1=10000000000000000 )

Account State Difference:

  Address   Before After State Difference Code
0x0fc59C9C...3a9c496Fe
0.86687940112307195 Eth
Nonce: 25
0.779254975973282572 Eth
Nonce: 26
0.087624425149789378
(Abyss Finance: Eth2 Depositor 214)
232.103161903380901871 Eth232.113238246580901871 Eth0.0100763432
0x71196021...8FF9E770b
0 Eth
Nonce: 0
0 Eth
Nonce: 1
From: 0 To: 970373714831926824185720946407840263919885073365469911651691774426946431665543512266471865775868962627047669120248256871330625770147892446909619397165810409821289694709588701323306867677257649208384978349326387418445535411191118173905878669248600552166591791127934899764776865837522151370137666890102937838273775714968403856071175813256007843767997955403679486028211556891105243817726967350283407681114102132506579105125304277564748167815342846397024705072290664688887558303342418259078870337858807302319256353732814537234856888289613708027399674335981848864884958452594500448750123709185757271799691704594825598460045237586046981286669973607497255811248054916336618770260591883114344560407110384952401173472315603951832690057890728508533745208338355059829327548814715428518717514222047513979665697375218597595236539309508342917627352671706653209120529696995353248818356303163358689521388719239190242456394183021189172097977158907875657912486338605550512879487546676611633302271475230667775383719586180157187006417919294738744302779946465631339458792305308388695808298977436244150528688722984158355049284028840226995683127551502032244556088325501540382610106837793499207544745847718703884658674971349811778799823186899170503086682057503015478989252616739182840170696904121594239897477811643131587177762472373252413961045631116709127211075498543319742453850377373997193487204507937988130627395736990058948639391539526660279803561610920474370751025762940139057313015758758177084944501064026665275431427980754256105434841498616423371358100769582975367394534305839627596757926422255187488652424989920991106699704285218110087276668191579082991838055940384641216906778353396018761511726797808610883741967942439137978054277212926284323547744109748783704275823053134686965394765704525445335194995340096279909491669098968935048953229629943910852066846595255766003226661174563949284052662117683721297660878592752685812469412066226405256310300438123619122828358311956300515948584897168820181311307515960755566624820143581320130400436732430638757868105953235466201800551590642755199648768273840591217733703620122243046325177668875516589566186636552174328659351513829282183884728262737218293545660596090969194471746871639948423418133586283866848948755311858692792320015436705816826440167723594281725277786605652770607698595900860223296437361927414376806437454204221244562486431899121071258780478379713316090152930112403133360327562653887016859083131040153889215211323340813891512208835582785595562532764709571103779102385994607473767759168295977624053955553512127361136426538721787686273453511216321239183520203588811113863626898343603784694118873851299330941956336018763877641535415884115710877740619706271918898464309749601333378501029178035189073363581003538216114898931114069302906737007051217887941611058391704483961983559785678569226084393692748550358504162988262743787900735768854607548925214343876751173683240824537308869801034098086776090912184840943364789608450108459058933828983365323127039638227524786338618000741006805641404819667044578037513628325173792992961824268689937669803599385494531623006692678868266120342454231855367906672560857809652908409078712367240635083658783854998584107465781037693112513504825080582332559347701051998974052053888576433850257906421102691284722864269704993003259908294704731616967666654167264848619972686653049260286109671848420793729709370897804926875423209863906428649310141041420009308127692597213921785490932788250583591674330356319897647747966146273898207930464771640539235830297333795401391504913652002320834613139741729368076652639464809773036076522969727659814124493464736987149809623832179451960770442040089734066312381297621879209022972801995571207352139151813089383646316351003310088139583590200672467808917264244386886686780453034140252637399180853260893922871128134433658609402748592130103963716546418725297520172944253857179183372468597190740759330590535670086374039630566975022955063170235065419296211949925273534052166004931987053298744637680011520831696542439607935300090502442438628514704477777102077986400176928856421605465129904174375972069211884462686883127713983467366860696368293716646956430672441424157258002385728282981306401694519326352934263298910982764980359652051223655655973714964833272423536068705931065645195932747891957766635776607472853023498124125964636568569512510264833392965747882773042738073847722385153647116948377688001424405819072114441606023784819011307292593178371303550296069228919741033823614181671434165165421383404767918836111241485989602761334449249466478212271691824027973863031222508351251598385598912343174008560798462069422639468405381063772605084007897065125907501478031106752086726688148537339128408569442511472471975545649657946884040962639071287276756275296263185109094564560920665709490772570679214129986144483752172595065335376963118597353944360246948948707586104853443176504880336918799957791065013022708627522814449711198702971114199024767133622346271292454993091805558177225768153096898303215097794211384523665473480643159410975016566620094591227052545319983765731532882350692747959420304224788485546890539259456085729469644680536986534637473170030708752822844772728987369817960256444094330702380885247926779415102435230803511443387105218505773040253262681523812180336520174794063087828241652218468762070586639746038321444642339626887634561153005479829608775330513173749405949716488789916381320425408414358752168817056559748812376244000590762854954314312663591755959405349006342640619098860796240062136157017719308399118564718743424013383953737720966358025713878278595430321887831137936259968296108592516513885707646624386380588008284583091803577117355591715374847170183589884461644255753143821210520303003100589083442202872479208287982760509683028047435613917926769745754618786845568335164562199183803448267307125507647424953068096864047151973851978073177428952839368627496204245025512138852305067922475400744111741971427173134495092218577816898603979675657754170230151168303366348265812641753106106772591540444252313523596780852703861172946736140246608460295875532543210426388979849381559833437039563435941549222227434569151633120212031453018819385630747722690813161762643419447206720512857089685827237039229397153740701597393287473724788562809034793328475823300677471937317677691837237894690439996426670181098526505342455729605979013749562452983747978768114552446856852023712514155703336513599427920772230682119186309321861914970213987289588275852035719372336659513573113656877618591862649326611914128580797181101364248322503230781633164186818231899634001311333258722839527336120702530738349212452416436300664085922190387117741793094198905592333357837426362099693208264568304704344967573770233806317187230870419409670937264725195884319274347207104410975884158365820401269043531976282629352504595598126046414093102768964092394311909425922966147107009361287347299428758092883122692136112630686169998346027329153711259532475731043582179362533519845870327551250060165488318315803827996089999110430800065530467920180163722884927674657200276626081910461803269368952628730875439204264162932081120527913006557957744514889818853925809011263078396276018428867706926005115509213333228605275574890553026955179599871709202395034822652888141269309109734322733264506756420204739831230530880327169751198067980692564160862893983370283465694590183203769738224718314349984179540394198676053375664759977675702219997771811838247986690461023015927827429492578944271012650006574408024585377051203614603729660654456777990209191502022990197729818969864410828865017479646361979476453851484691304981448346016038824075560134472665066664491496179478999648935490294701429779929315619388575702574357785786090451257694788109101210639982684833459404824653248740920617108408548887935240960839050302685749957466576524637031585237207339666450432711265151975751341773671998379757237804933942228055834687721941426537564376739573344032146862045259319183351508814511830286739243982365210781714974458897247497697002057154545892946110509547543471449083690747604826499673393514629399722431455689436350763458074168064888197070393968390438977228630761766093119655774395698612836974355327985124028054520638396868898892736959571058738421473425384929489113548813840860074487898330414801765855587748553806713906105440614678759954262871936381480236279852264806909516711341688548750501337587387672360221244371172177671200922024952651391556899415437579417011797401592989444457073058275514205956201848924217964835016415954656336252152856491521595231297454269241938277131439704423551330612117358046164730806832601160288390874769930872202629213600971363540576274141782381535247172155304749605615723096656469063547236276388170374855879792917902148058601928565499982491144692486083511159333922403948467825631315716451899262083934011171848498437165726363619725429738272768068275481148343272357717715150724633570307392266973671384031024725364695855198542436416424360582961266612568697466028541562876786082163927073662080043144889766409119138448855762360858613202880414776752522467635049718129289638698721065221925939135759391754085175391096464080040023095105645093813002457184029379826150339976731647337702786957691568399488647262699092137030247089786860088628392311411861836543300617935577226081902113340564338782783648633548985274420679526628794356405839072220764943487632464344256729379647295745097693846466289646792591875466815860796571268171492137772810924090844967592335574781754716685784691014495046993523459358222061397503969885568467212847294389127064062045960751855865770410518730507699373418760658333677112957244072117879293498465127102270950754390673539046312444324669390947895797211606548479473329353848576117136172619357906471019074036841450925640565889945574682536528223276622784642449667081724706674034033565494717346503769515040472385946502596541182491529408987820922111880322587337440286877512839054470637984159200451631314592617512951699433153475235051530534244418897306687989511134122202108387116023928323393685624348550174007518071030991921987960670005320336877725964006729509639764597879335793850991602353340061558978051791300636366553862753724370623567968749783743310780965036384605460691415194433689969011792973782473666950781224341315781450260035537719069704919720787263675816258532654591347236112761126400845251037826580843692724311711333112779225989883101744757245522183925999092166378829399827665359320744176108182791920430631066099517964732943588800249683483552673364253912775513166306788502375427615776030682207304558057915785891170359083003506646568939144125975464897708668342017234594621007650504231529767738963839937251500725868969894569417717880486314264631787016280709740788000085743995949795467514386081601265876195773210554156664380919010352067746586927874956968642069823898907824505385129849954983593151006664078692024277439343794964900380458144271983561819401740504889542906704033311834295862042680157208880708862945239096085854099675739746647198632047949942242766670969367007119626619843275096008868870903165501506054102277734036597006432439849426382928680483878929115980449437248303103730604604592219926788689799174953705421826252975210132506850942122495828640523632088798819600172273825009705603169474652888941308494136146681775574600873672105369458799174990461031795705196541081814131638647046005745470256316096326843752906192320328546785563701780636829801898881528702809091457681100156525220118941327671513095786900017264775058641975182773252443580703006370973152943735735742285548548294699790631541248592989241957243039395060417242697132769629526041535322521567995031721284554356733693331592393104973550169047476203721814936589454528872745901630224615442989086815050052787690939530838859133503778297474896311126790406655466517562847539984021903454365389210667011353422460804557274316638803784710865430830008710699929583983043198766622348864987925050304298262827118935540356738701427925554624732808712109260530989348886248024089487130530404851035088670778246702210209088813805811907431148698396276997459378045504728422691255167219358992301084830132326603177696930466301600864085761755561999092577471792763261997877124626854601292477204157934995386209866950649217732587631957987512932767561879105467656889358094535660718173509156619154285903745112199448970760461006993780614112378281744018991808106630713891427374272023679690978206418934655911079191164789255422133484034273841768693139752423025910110946595652958417442477329430614244980753983362977720871460234864332771053833672737385209965600946595217766006705509026335509477823549003356986161630450925451471756599928476953844115491317427518347142728294936900654063320919079169285734763420505042430799660052417974812293277574774495634371192624279092678522520750496435533666954262462791923797130294327609327848256088663585250685505553614974996756806161687704484071008834742737611940384249653338719817823413378421369601095501312144948495855539403060945885081617073278655682049319069029345671477101366796090736510647364543619064229138844873187388727093530914503627954549241832721488528113846291486541998769962403140919120192937910762917046598457816085658368084945362999807914843368403160449927534613376645197123266144917645477745760744680788271770438533853528044263031585396537896973379066873050363663459138939627619811565049002466703204632171381254017627402046149919219222020468226407743716190862780972009870633237901970906872167286590335348007321748183330880831894517946593143311518075865318361769843573639749478724865189109381609191603639419492707737523586307085883952245365881699264388059523295084962136196858877919464742499682778558150008055864043696561294304075526720560755837319200301322870360611477376950704864996348223704493049371991873583715766288717661124660410740528994164578954884549269315702207501467717456235970416775885723625865136800179170019783518699285177100551996746978063703196484468562083725332025707044434502088998828479479935003802489408559691117390918028532713442605962854364008870636177674215829292274920743064007902408674319602358727755590116931326808886237063800930049816855086360319557479555013074872388376341102936941754783044200240784242710394470642411624545509452881918665007454852507591464153777301531200239259909053527415489780939592604428584244320185608386164260830273792287943771437987254680616514172054163699428650966604299326846676724140554046037026358221667172911863956259956146392339729150490341959475539432842841141291469534887669781319320656658212488599163215819826442113023979743609333804460131078449584535247009672860018797780828507186528033076747945754492845689280056680647094379994572606617159879968580198913830564139884066633170040829394173706681535220794401477997987297977107820559276833700338101970959709324601486316626605489272080540314560766531860937959035948430083007800045007498518871400943035382833985896842761282512388069238975577827426697859409780907813757482456128103770110049604561331276909028069992448008029939400269044378012410359306419624436057392323165033306556216096491999516197862147320234261339461472875683397169521907905600043631231781545801925083891329614246023591374927606105723616711484545890671142513058556377532998707736458954171149864129939436464074335169248506525066785276675491136322415743917982962584043021663863398460998832644169959399215000217933991974541747409945961883326242580638764259996984016881380781908912159725686109466173134328173490210619158958787033625142640585491171826024862706826915229042224704272380700947928026391349311581425246007287881064209097727176917170386929944486570017097816833310615319893425627747705549542341524222988418400819813694851686348251611424033769185244888235358798548729476924616796051964418542426166888025984387570148732403732506194193958217393623861731246348752581987043707580411196754241659650238869269631716706528956281317686833691822617354461178650995225853844606121132325199558969976375822009166098747524107639013101062599029451378959339390202342582736335599652325505465353986683813946071192018081076312208629765395621209488277395784640860911514039728018066531901659516572197637400575476983162933776715620891736835679339575538095711271758873450076801737906029045336800888123127161425737942261238783698288429238591871878369623243006466420827979809623303915097870501405730419021175864637866787640746589858208013269149415851747981650993140293347620441621505600556855327715304808824122988766738348767312367920204976341982114621575157364390735118188857538091797048990788865248803972209514274999813436635362075827698706353693009242065402727925570603883194574478422993054092064842160983021821541991745086159871539488371195275996694643200450371024090799232120447690997852642261610238429040502221826879328337883986261627726469661275043050945235000486318691012267622286024896456957752092888038622148980772634110200921305608258748205519856430442107346888546461133463542594736137007567199019364607312049451945117486753334499685446808143117559430109302310294457260699168509577665465389348009093500969317952850435509882319600829023179999141813601449202487279621273466315052248272311214774245835781000744915320708917707088419286083855697539420164684989694373887539791225273805431250987945559717884299875590380599141739447481123798946068305286992390176788967266661487863056742269454724613458743877244970441960417040989608269799571037982994082675722414785707995176423374816524171512633509935054437801803310248384314285954281462633920453516986844165643310740186901428295734074251032436825760578410365476902843686484707897486327323001802570292298821730078302732901129606491355573740245413060205772816910805639747087366487474436402913952818642505822608211221231677940391464488526521617830036965405717227879288032834017163260707269715179086414548635459287296187665159532791005266513787039098259163867770236806630346145864154316664216357850431592592359357446437001032934265550512830069601314834263788955728577079168572371414522895094750990390037111638813956940038739336834117961630269344815833094571050603534124731144224664253090404674455179570848947414318901227315544465021017836111627574376422404611915266696378634541371628288275606736107092316640721239149189865613035653407405711253689628930932536948673165561694357200020411829896891576446318915146439820526504623011486554989516165667323335693414934814004410278644054000879039077833478222322272172872756103371354890899347688095119987051466357536009129562866823329151434447032893988942430150070946911349522553627858194947768274263084245629745183222615730004776379639668442725598279874930308244088933008485396959917666681610999955901665756196851949672769851203664125707554741540254559589839455890674210549613366744628250073940092320601238917734706503162753930994533684587838945685931212495222992599246372012582151929497212649486853033780275395201624953847297781180136653199208638796247411753539601271520979109694681051203539727904805097294418844970859034890974420496664672055334861261760577417100136846408252492277891862905518897820428967259414938247580001447414510879102374696398833681566184073453099383668886595163928620965172752288672765029891029325085087456675823219540845532470723299624971609531611152834905485995656999320694510613883917811326120587965945992437257752500815632041698885255900054689108235889290415209428332936722366764889127234155667730465019401160065463007229392807541321336673902417329345781330121820189416588185054182834106503659033695040889811794590145458037336891808190609892824794636329808967954256162631834596750615551750885506661417008739876427848834173792022477826960766473390684073275311664976029919411152403305472706182649305024864582120589644917212074489284683189328610953965037460607871739534360932914668243598486662868330241318289838917701751649537035731801559759342829825067798963468992656715072809773251050799601512114788075674879299224408300911146471181524820624990967218578355354523595632118493281309130872723834470866206629973887965161739406193341212336262793271639852531306838133337615718728319588810050542270596956328567969570294887381238958194557914489771335585918386940508644713954522805652967236056982078861155491811377171122930283117015403615649057864389322174134638420880929447094682133107475402227582325798127425448778476048451495428393366905468431691919308127178234473964052772617886621785434581352325198198055102133905256578806269728104359955638474987554997853220494348754346661779775947650590800195501275865742243509974608314470088293937303056528230079665296631935180049276802937989044278604178623082423213142113594479981759246054400064387201884459817337594764911691628527252625205351851767408034075053271423174343509950819755385274072523521130743043892243679459309153516863691890342691490453628793924053747111342564967146040090893591274974111127466787240729067426868324690634630052613037171225116580863468738108996853020180544491645000100174575664012894587507333228928354119713825262406933537472892720657172973712656680598385724687705359141398533994684371207343695251028367425700446320896600152962617022752618119262643853347831915167751822676880325218838130722794593790105951383826557724427909166920523335397976410875362536439098738683685984789647681920089933271389419332348794542537281522986540989318881267423868328272321517940529382711784095183479130385844905903202668137163485645250252636181922893427516074609054230102691384884727058499011448444251554567015759544508413009302584592842680906254129887071647426059491020839771430126624782157841259965956947711701654222689895616224767511443599054979604607211348567169816537828949827685467972847719691791084849022596830103592906915740960569411166874579067131092771723878155546100222088541325901052260690681040153958893918600970285548717664354906966339614995694273180466886605408349453805523472862965155943740978752213097794321902761534688209534705436678922666950115252179355448276882854139279907243975102208610580905971149150181109773352077055509317246966021606859379181045294031105163315
0xC02aaA39...83C756Cc2 3,769,520.673724051486435374 Eth3,769,520.683724051486435374 Eth0.01
0xC0AEe478...cE9e4f2Ac
(SushiSwap: SushiV2Factory)
0xf951E335...EaC7DEd78

Execution Trace

ETH 0.01 UniswapV2Router02.addLiquidityETH( token=0xf951E335afb289353dc249e82926178EaC7DEd78, amountTokenDesired=10000000000000000, amountTokenMin=10000000000000000, amountETHMin=10000000000000000, to=0x0fc59C9C998537c940a9Dfc7DacDe533a9c496Fe, deadline=1681723511 ) => ( amountToken=10000000000000000, amountETH=10000000000000000, liquidity=9999999999999000 )
  • UniswapV2Factory.getPair( 0xf951E335afb289353dc249e82926178EaC7DEd78, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ) => ( 0x0000000000000000000000000000000000000000 )
  • UniswapV2Factory.createPair( tokenA=0xf951E335afb289353dc249e82926178EaC7DEd78, tokenB=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ) => ( pair=0x7119602160D2072b6e329D1c1ac93a48FF9E770b )
    • UniswapV2Pair.60806040( )
    • UniswapV2Pair.initialize( _token0=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, _token1=0xf951E335afb289353dc249e82926178EaC7DEd78 )
    • UniswapV2Pair.STATICCALL( )
    • TransparentUpgradeableProxy.23b872dd( )
      • swETH.transferFrom( from=0x0fc59C9C998537c940a9Dfc7DacDe533a9c496Fe, to=0x7119602160D2072b6e329D1c1ac93a48FF9E770b, amount=10000000000000000 ) => ( True )
      • ETH 0.01 WETH9.CALL( )
      • WETH9.transfer( dst=0x7119602160D2072b6e329D1c1ac93a48FF9E770b, wad=10000000000000000 ) => ( True )
      • UniswapV2Pair.mint( to=0x0fc59C9C998537c940a9Dfc7DacDe533a9c496Fe ) => ( liquidity=9999999999999000 )
        • WETH9.balanceOf( 0x7119602160D2072b6e329D1c1ac93a48FF9E770b ) => ( 10000000000000000 )
        • TransparentUpgradeableProxy.70a08231( )
          • swETH.balanceOf( account=0x7119602160D2072b6e329D1c1ac93a48FF9E770b ) => ( 10000000000000000 )
          • UniswapV2Factory.STATICCALL( )
          • UniswapV2Factory.STATICCALL( )
            File 1 of 6: UniswapV2Router02
            // File: contracts/uniswapv2/interfaces/IUniswapV2Pair.sol
            
            pragma solidity >=0.5.0;
            
            interface IUniswapV2Pair {
                event Approval(address indexed owner, address indexed spender, uint value);
                event Transfer(address indexed from, address indexed to, uint value);
            
                function name() external pure returns (string memory);
                function symbol() external pure returns (string memory);
                function decimals() external pure returns (uint8);
                function totalSupply() external view returns (uint);
                function balanceOf(address owner) external view returns (uint);
                function allowance(address owner, address spender) external view returns (uint);
            
                function approve(address spender, uint value) external returns (bool);
                function transfer(address to, uint value) external returns (bool);
                function transferFrom(address from, address to, uint value) external returns (bool);
            
                function DOMAIN_SEPARATOR() external view returns (bytes32);
                function PERMIT_TYPEHASH() external pure returns (bytes32);
                function nonces(address owner) external view returns (uint);
            
                function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
            
                event Mint(address indexed sender, uint amount0, uint amount1);
                event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
                event Swap(
                    address indexed sender,
                    uint amount0In,
                    uint amount1In,
                    uint amount0Out,
                    uint amount1Out,
                    address indexed to
                );
                event Sync(uint112 reserve0, uint112 reserve1);
            
                function MINIMUM_LIQUIDITY() external pure returns (uint);
                function factory() external view returns (address);
                function token0() external view returns (address);
                function token1() external view returns (address);
                function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
                function price0CumulativeLast() external view returns (uint);
                function price1CumulativeLast() external view returns (uint);
                function kLast() external view returns (uint);
            
                function mint(address to) external returns (uint liquidity);
                function burn(address to) external returns (uint amount0, uint amount1);
                function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
                function skim(address to) external;
                function sync() external;
            
                function initialize(address, address) external;
            }
            
            // File: contracts/uniswapv2/libraries/SafeMath.sol
            
            pragma solidity =0.6.12;
            
            // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
            
            library SafeMathUniswap {
                function add(uint x, uint y) internal pure returns (uint z) {
                    require((z = x + y) >= x, 'ds-math-add-overflow');
                }
            
                function sub(uint x, uint y) internal pure returns (uint z) {
                    require((z = x - y) <= x, 'ds-math-sub-underflow');
                }
            
                function mul(uint x, uint y) internal pure returns (uint z) {
                    require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
                }
            }
            
            // File: contracts/uniswapv2/libraries/UniswapV2Library.sol
            
            pragma solidity >=0.5.0;
            
            
            
            library UniswapV2Library {
                using SafeMathUniswap for uint;
            
                // returns sorted token addresses, used to handle return values from pairs sorted in this order
                function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
                    require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
                    (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
                    require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
                }
            
                // calculates the CREATE2 address for a pair without making any external calls
                function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
                    (address token0, address token1) = sortTokens(tokenA, tokenB);
                    pair = address(uint(keccak256(abi.encodePacked(
                            hex'ff',
                            factory,
                            keccak256(abi.encodePacked(token0, token1)),
                            hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // init code hash
                        ))));
                }
            
                // fetches and sorts the reserves for a pair
                function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
                    (address token0,) = sortTokens(tokenA, tokenB);
                    (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
                    (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
                }
            
                // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
                function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
                    require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
                    require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
                    amountB = amountA.mul(reserveB) / reserveA;
                }
            
                // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
                function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
                    require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
                    require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
                    uint amountInWithFee = amountIn.mul(997);
                    uint numerator = amountInWithFee.mul(reserveOut);
                    uint denominator = reserveIn.mul(1000).add(amountInWithFee);
                    amountOut = numerator / denominator;
                }
            
                // given an output amount of an asset and pair reserves, returns a required input amount of the other asset
                function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
                    require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
                    require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
                    uint numerator = reserveIn.mul(amountOut).mul(1000);
                    uint denominator = reserveOut.sub(amountOut).mul(997);
                    amountIn = (numerator / denominator).add(1);
                }
            
                // performs chained getAmountOut calculations on any number of pairs
                function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
                    require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
                    amounts = new uint[](path.length);
                    amounts[0] = amountIn;
                    for (uint i; i < path.length - 1; i++) {
                        (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
                        amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
                    }
                }
            
                // performs chained getAmountIn calculations on any number of pairs
                function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
                    require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
                    amounts = new uint[](path.length);
                    amounts[amounts.length - 1] = amountOut;
                    for (uint i = path.length - 1; i > 0; i--) {
                        (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
                        amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
                    }
                }
            }
            
            // File: contracts/uniswapv2/libraries/TransferHelper.sol
            
            // SPDX-License-Identifier: GPL-3.0-or-later
            
            pragma solidity >=0.6.0;
            
            // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
            library TransferHelper {
                function safeApprove(address token, address to, uint value) internal {
                    // bytes4(keccak256(bytes('approve(address,uint256)')));
                    (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
                    require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
                }
            
                function safeTransfer(address token, address to, uint value) internal {
                    // bytes4(keccak256(bytes('transfer(address,uint256)')));
                    (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
                    require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
                }
            
                function safeTransferFrom(address token, address from, address to, uint value) internal {
                    // bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
                    (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
                    require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
                }
            
                function safeTransferETH(address to, uint value) internal {
                    (bool success,) = to.call{value:value}(new bytes(0));
                    require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
                }
            }
            
            // File: contracts/uniswapv2/interfaces/IUniswapV2Router01.sol
            
            pragma solidity >=0.6.2;
            
            interface IUniswapV2Router01 {
                function factory() external pure returns (address);
                function WETH() external pure returns (address);
            
                function addLiquidity(
                    address tokenA,
                    address tokenB,
                    uint amountADesired,
                    uint amountBDesired,
                    uint amountAMin,
                    uint amountBMin,
                    address to,
                    uint deadline
                ) external returns (uint amountA, uint amountB, uint liquidity);
                function addLiquidityETH(
                    address token,
                    uint amountTokenDesired,
                    uint amountTokenMin,
                    uint amountETHMin,
                    address to,
                    uint deadline
                ) external payable returns (uint amountToken, uint amountETH, uint liquidity);
                function removeLiquidity(
                    address tokenA,
                    address tokenB,
                    uint liquidity,
                    uint amountAMin,
                    uint amountBMin,
                    address to,
                    uint deadline
                ) external returns (uint amountA, uint amountB);
                function removeLiquidityETH(
                    address token,
                    uint liquidity,
                    uint amountTokenMin,
                    uint amountETHMin,
                    address to,
                    uint deadline
                ) external returns (uint amountToken, uint amountETH);
                function removeLiquidityWithPermit(
                    address tokenA,
                    address tokenB,
                    uint liquidity,
                    uint amountAMin,
                    uint amountBMin,
                    address to,
                    uint deadline,
                    bool approveMax, uint8 v, bytes32 r, bytes32 s
                ) external returns (uint amountA, uint amountB);
                function removeLiquidityETHWithPermit(
                    address token,
                    uint liquidity,
                    uint amountTokenMin,
                    uint amountETHMin,
                    address to,
                    uint deadline,
                    bool approveMax, uint8 v, bytes32 r, bytes32 s
                ) external returns (uint amountToken, uint amountETH);
                function swapExactTokensForTokens(
                    uint amountIn,
                    uint amountOutMin,
                    address[] calldata path,
                    address to,
                    uint deadline
                ) external returns (uint[] memory amounts);
                function swapTokensForExactTokens(
                    uint amountOut,
                    uint amountInMax,
                    address[] calldata path,
                    address to,
                    uint deadline
                ) external returns (uint[] memory amounts);
                function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
                    external
                    payable
                    returns (uint[] memory amounts);
                function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
                    external
                    returns (uint[] memory amounts);
                function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
                    external
                    returns (uint[] memory amounts);
                function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
                    external
                    payable
                    returns (uint[] memory amounts);
            
                function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
                function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
                function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
                function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
                function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
            }
            
            // File: contracts/uniswapv2/interfaces/IUniswapV2Router02.sol
            
            pragma solidity >=0.6.2;
            
            
            interface IUniswapV2Router02 is IUniswapV2Router01 {
                function removeLiquidityETHSupportingFeeOnTransferTokens(
                    address token,
                    uint liquidity,
                    uint amountTokenMin,
                    uint amountETHMin,
                    address to,
                    uint deadline
                ) external returns (uint amountETH);
                function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
                    address token,
                    uint liquidity,
                    uint amountTokenMin,
                    uint amountETHMin,
                    address to,
                    uint deadline,
                    bool approveMax, uint8 v, bytes32 r, bytes32 s
                ) external returns (uint amountETH);
            
                function swapExactTokensForTokensSupportingFeeOnTransferTokens(
                    uint amountIn,
                    uint amountOutMin,
                    address[] calldata path,
                    address to,
                    uint deadline
                ) external;
                function swapExactETHForTokensSupportingFeeOnTransferTokens(
                    uint amountOutMin,
                    address[] calldata path,
                    address to,
                    uint deadline
                ) external payable;
                function swapExactTokensForETHSupportingFeeOnTransferTokens(
                    uint amountIn,
                    uint amountOutMin,
                    address[] calldata path,
                    address to,
                    uint deadline
                ) external;
            }
            
            // File: contracts/uniswapv2/interfaces/IUniswapV2Factory.sol
            
            pragma solidity >=0.5.0;
            
            interface IUniswapV2Factory {
                event PairCreated(address indexed token0, address indexed token1, address pair, uint);
            
                function feeTo() external view returns (address);
                function feeToSetter() external view returns (address);
                function migrator() external view returns (address);
            
                function getPair(address tokenA, address tokenB) external view returns (address pair);
                function allPairs(uint) external view returns (address pair);
                function allPairsLength() external view returns (uint);
            
                function createPair(address tokenA, address tokenB) external returns (address pair);
            
                function setFeeTo(address) external;
                function setFeeToSetter(address) external;
                function setMigrator(address) external;
            }
            
            // File: contracts/uniswapv2/interfaces/IERC20.sol
            
            pragma solidity >=0.5.0;
            
            interface IERC20Uniswap {
                event Approval(address indexed owner, address indexed spender, uint value);
                event Transfer(address indexed from, address indexed to, uint value);
            
                function name() external view returns (string memory);
                function symbol() external view returns (string memory);
                function decimals() external view returns (uint8);
                function totalSupply() external view returns (uint);
                function balanceOf(address owner) external view returns (uint);
                function allowance(address owner, address spender) external view returns (uint);
            
                function approve(address spender, uint value) external returns (bool);
                function transfer(address to, uint value) external returns (bool);
                function transferFrom(address from, address to, uint value) external returns (bool);
            }
            
            // File: contracts/uniswapv2/interfaces/IWETH.sol
            
            pragma solidity >=0.5.0;
            
            interface IWETH {
                function deposit() external payable;
                function transfer(address to, uint value) external returns (bool);
                function withdraw(uint) external;
            }
            
            // File: contracts/uniswapv2/UniswapV2Router02.sol
            
            pragma solidity =0.6.12;
            
            
            
            
            
            
            
            
            contract UniswapV2Router02 is IUniswapV2Router02 {
                using SafeMathUniswap for uint;
            
                address public immutable override factory;
                address public immutable override WETH;
            
                modifier ensure(uint deadline) {
                    require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED');
                    _;
                }
            
                constructor(address _factory, address _WETH) public {
                    factory = _factory;
                    WETH = _WETH;
                }
            
                receive() external payable {
                    assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
                }
            
                // **** ADD LIQUIDITY ****
                function _addLiquidity(
                    address tokenA,
                    address tokenB,
                    uint amountADesired,
                    uint amountBDesired,
                    uint amountAMin,
                    uint amountBMin
                ) internal virtual returns (uint amountA, uint amountB) {
                    // create the pair if it doesn't exist yet
                    if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {
                        IUniswapV2Factory(factory).createPair(tokenA, tokenB);
                    }
                    (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
                    if (reserveA == 0 && reserveB == 0) {
                        (amountA, amountB) = (amountADesired, amountBDesired);
                    } else {
                        uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);
                        if (amountBOptimal <= amountBDesired) {
                            require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
                            (amountA, amountB) = (amountADesired, amountBOptimal);
                        } else {
                            uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);
                            assert(amountAOptimal <= amountADesired);
                            require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
                            (amountA, amountB) = (amountAOptimal, amountBDesired);
                        }
                    }
                }
                function addLiquidity(
                    address tokenA,
                    address tokenB,
                    uint amountADesired,
                    uint amountBDesired,
                    uint amountAMin,
                    uint amountBMin,
                    address to,
                    uint deadline
                ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
                    (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
                    address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
                    TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
                    TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
                    liquidity = IUniswapV2Pair(pair).mint(to);
                }
                function addLiquidityETH(
                    address token,
                    uint amountTokenDesired,
                    uint amountTokenMin,
                    uint amountETHMin,
                    address to,
                    uint deadline
                ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
                    (amountToken, amountETH) = _addLiquidity(
                        token,
                        WETH,
                        amountTokenDesired,
                        msg.value,
                        amountTokenMin,
                        amountETHMin
                    );
                    address pair = UniswapV2Library.pairFor(factory, token, WETH);
                    TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
                    IWETH(WETH).deposit{value: amountETH}();
                    assert(IWETH(WETH).transfer(pair, amountETH));
                    liquidity = IUniswapV2Pair(pair).mint(to);
                    // refund dust eth, if any
                    if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
                }
            
                // **** REMOVE LIQUIDITY ****
                function removeLiquidity(
                    address tokenA,
                    address tokenB,
                    uint liquidity,
                    uint amountAMin,
                    uint amountBMin,
                    address to,
                    uint deadline
                ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
                    address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
                    IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
                    (uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to);
                    (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB);
                    (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
                    require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
                    require(amountB >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
                }
                function removeLiquidityETH(
                    address token,
                    uint liquidity,
                    uint amountTokenMin,
                    uint amountETHMin,
                    address to,
                    uint deadline
                ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
                    (amountToken, amountETH) = removeLiquidity(
                        token,
                        WETH,
                        liquidity,
                        amountTokenMin,
                        amountETHMin,
                        address(this),
                        deadline
                    );
                    TransferHelper.safeTransfer(token, to, amountToken);
                    IWETH(WETH).withdraw(amountETH);
                    TransferHelper.safeTransferETH(to, amountETH);
                }
                function removeLiquidityWithPermit(
                    address tokenA,
                    address tokenB,
                    uint liquidity,
                    uint amountAMin,
                    uint amountBMin,
                    address to,
                    uint deadline,
                    bool approveMax, uint8 v, bytes32 r, bytes32 s
                ) external virtual override returns (uint amountA, uint amountB) {
                    address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);
                    uint value = approveMax ? uint(-1) : liquidity;
                    IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
                    (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
                }
                function removeLiquidityETHWithPermit(
                    address token,
                    uint liquidity,
                    uint amountTokenMin,
                    uint amountETHMin,
                    address to,
                    uint deadline,
                    bool approveMax, uint8 v, bytes32 r, bytes32 s
                ) external virtual override returns (uint amountToken, uint amountETH) {
                    address pair = UniswapV2Library.pairFor(factory, token, WETH);
                    uint value = approveMax ? uint(-1) : liquidity;
                    IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
                    (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);
                }
            
                // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
                function removeLiquidityETHSupportingFeeOnTransferTokens(
                    address token,
                    uint liquidity,
                    uint amountTokenMin,
                    uint amountETHMin,
                    address to,
                    uint deadline
                ) public virtual override ensure(deadline) returns (uint amountETH) {
                    (, amountETH) = removeLiquidity(
                        token,
                        WETH,
                        liquidity,
                        amountTokenMin,
                        amountETHMin,
                        address(this),
                        deadline
                    );
                    TransferHelper.safeTransfer(token, to, IERC20Uniswap(token).balanceOf(address(this)));
                    IWETH(WETH).withdraw(amountETH);
                    TransferHelper.safeTransferETH(to, amountETH);
                }
                function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
                    address token,
                    uint liquidity,
                    uint amountTokenMin,
                    uint amountETHMin,
                    address to,
                    uint deadline,
                    bool approveMax, uint8 v, bytes32 r, bytes32 s
                ) external virtual override returns (uint amountETH) {
                    address pair = UniswapV2Library.pairFor(factory, token, WETH);
                    uint value = approveMax ? uint(-1) : liquidity;
                    IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
                    amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
                        token, liquidity, amountTokenMin, amountETHMin, to, deadline
                    );
                }
            
                // **** SWAP ****
                // requires the initial amount to have already been sent to the first pair
                function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
                    for (uint i; i < path.length - 1; i++) {
                        (address input, address output) = (path[i], path[i + 1]);
                        (address token0,) = UniswapV2Library.sortTokens(input, output);
                        uint amountOut = amounts[i + 1];
                        (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
                        address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
                        IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output)).swap(
                            amount0Out, amount1Out, to, new bytes(0)
                        );
                    }
                }
                function swapExactTokensForTokens(
                    uint amountIn,
                    uint amountOutMin,
                    address[] calldata path,
                    address to,
                    uint deadline
                ) external virtual override ensure(deadline) returns (uint[] memory amounts) {
                    amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
                    require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
                    TransferHelper.safeTransferFrom(
                        path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
                    );
                    _swap(amounts, path, to);
                }
                function swapTokensForExactTokens(
                    uint amountOut,
                    uint amountInMax,
                    address[] calldata path,
                    address to,
                    uint deadline
                ) external virtual override ensure(deadline) returns (uint[] memory amounts) {
                    amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
                    require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
                    TransferHelper.safeTransferFrom(
                        path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
                    );
                    _swap(amounts, path, to);
                }
                function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
                    external
                    virtual
                    override
                    payable
                    ensure(deadline)
                    returns (uint[] memory amounts)
                {
                    require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
                    amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path);
                    require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
                    IWETH(WETH).deposit{value: amounts[0]}();
                    assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
                    _swap(amounts, path, to);
                }
                function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
                    external
                    virtual
                    override
                    ensure(deadline)
                    returns (uint[] memory amounts)
                {
                    require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
                    amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
                    require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
                    TransferHelper.safeTransferFrom(
                        path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
                    );
                    _swap(amounts, path, address(this));
                    IWETH(WETH).withdraw(amounts[amounts.length - 1]);
                    TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
                }
                function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
                    external
                    virtual
                    override
                    ensure(deadline)
                    returns (uint[] memory amounts)
                {
                    require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
                    amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path);
                    require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
                    TransferHelper.safeTransferFrom(
                        path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
                    );
                    _swap(amounts, path, address(this));
                    IWETH(WETH).withdraw(amounts[amounts.length - 1]);
                    TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
                }
                function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
                    external
                    virtual
                    override
                    payable
                    ensure(deadline)
                    returns (uint[] memory amounts)
                {
                    require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
                    amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
                    require(amounts[0] <= msg.value, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
                    IWETH(WETH).deposit{value: amounts[0]}();
                    assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
                    _swap(amounts, path, to);
                    // refund dust eth, if any
                    if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
                }
            
                // **** SWAP (supporting fee-on-transfer tokens) ****
                // requires the initial amount to have already been sent to the first pair
                function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
                    for (uint i; i < path.length - 1; i++) {
                        (address input, address output) = (path[i], path[i + 1]);
                        (address token0,) = UniswapV2Library.sortTokens(input, output);
                        IUniswapV2Pair pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, input, output));
                        uint amountInput;
                        uint amountOutput;
                        { // scope to avoid stack too deep errors
                        (uint reserve0, uint reserve1,) = pair.getReserves();
                        (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
                        amountInput = IERC20Uniswap(input).balanceOf(address(pair)).sub(reserveInput);
                        amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);
                        }
                        (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
                        address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
                        pair.swap(amount0Out, amount1Out, to, new bytes(0));
                    }
                }
                function swapExactTokensForTokensSupportingFeeOnTransferTokens(
                    uint amountIn,
                    uint amountOutMin,
                    address[] calldata path,
                    address to,
                    uint deadline
                ) external virtual override ensure(deadline) {
                    TransferHelper.safeTransferFrom(
                        path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn
                    );
                    uint balanceBefore = IERC20Uniswap(path[path.length - 1]).balanceOf(to);
                    _swapSupportingFeeOnTransferTokens(path, to);
                    require(
                        IERC20Uniswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
                        'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'
                    );
                }
                function swapExactETHForTokensSupportingFeeOnTransferTokens(
                    uint amountOutMin,
                    address[] calldata path,
                    address to,
                    uint deadline
                )
                    external
                    virtual
                    override
                    payable
                    ensure(deadline)
                {
                    require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
                    uint amountIn = msg.value;
                    IWETH(WETH).deposit{value: amountIn}();
                    assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn));
                    uint balanceBefore = IERC20Uniswap(path[path.length - 1]).balanceOf(to);
                    _swapSupportingFeeOnTransferTokens(path, to);
                    require(
                        IERC20Uniswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
                        'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'
                    );
                }
                function swapExactTokensForETHSupportingFeeOnTransferTokens(
                    uint amountIn,
                    uint amountOutMin,
                    address[] calldata path,
                    address to,
                    uint deadline
                )
                    external
                    virtual
                    override
                    ensure(deadline)
                {
                    require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
                    TransferHelper.safeTransferFrom(
                        path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amountIn
                    );
                    _swapSupportingFeeOnTransferTokens(path, address(this));
                    uint amountOut = IERC20Uniswap(WETH).balanceOf(address(this));
                    require(amountOut >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
                    IWETH(WETH).withdraw(amountOut);
                    TransferHelper.safeTransferETH(to, amountOut);
                }
            
                // **** LIBRARY FUNCTIONS ****
                function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
                    return UniswapV2Library.quote(amountA, reserveA, reserveB);
                }
            
                function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
                    public
                    pure
                    virtual
                    override
                    returns (uint amountOut)
                {
                    return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);
                }
            
                function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
                    public
                    pure
                    virtual
                    override
                    returns (uint amountIn)
                {
                    return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);
                }
            
                function getAmountsOut(uint amountIn, address[] memory path)
                    public
                    view
                    virtual
                    override
                    returns (uint[] memory amounts)
                {
                    return UniswapV2Library.getAmountsOut(factory, amountIn, path);
                }
            
                function getAmountsIn(uint amountOut, address[] memory path)
                    public
                    view
                    virtual
                    override
                    returns (uint[] memory amounts)
                {
                    return UniswapV2Library.getAmountsIn(factory, amountOut, path);
                }
            }

            File 2 of 6: UniswapV2Factory
            // File: contracts/uniswapv2/interfaces/IUniswapV2Factory.sol
            
            pragma solidity >=0.5.0;
            
            interface IUniswapV2Factory {
                event PairCreated(address indexed token0, address indexed token1, address pair, uint);
            
                function feeTo() external view returns (address);
                function feeToSetter() external view returns (address);
                function migrator() external view returns (address);
            
                function getPair(address tokenA, address tokenB) external view returns (address pair);
                function allPairs(uint) external view returns (address pair);
                function allPairsLength() external view returns (uint);
            
                function createPair(address tokenA, address tokenB) external returns (address pair);
            
                function setFeeTo(address) external;
                function setFeeToSetter(address) external;
                function setMigrator(address) external;
            }
            
            // File: contracts/uniswapv2/libraries/SafeMath.sol
            
            pragma solidity =0.6.12;
            
            // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
            
            library SafeMathUniswap {
                function add(uint x, uint y) internal pure returns (uint z) {
                    require((z = x + y) >= x, 'ds-math-add-overflow');
                }
            
                function sub(uint x, uint y) internal pure returns (uint z) {
                    require((z = x - y) <= x, 'ds-math-sub-underflow');
                }
            
                function mul(uint x, uint y) internal pure returns (uint z) {
                    require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
                }
            }
            
            // File: contracts/uniswapv2/UniswapV2ERC20.sol
            
            pragma solidity =0.6.12;
            
            
            contract UniswapV2ERC20 {
                using SafeMathUniswap for uint;
            
                string public constant name = 'SushiSwap LP Token';
                string public constant symbol = 'SLP';
                uint8 public constant decimals = 18;
                uint  public totalSupply;
                mapping(address => uint) public balanceOf;
                mapping(address => mapping(address => uint)) public allowance;
            
                bytes32 public DOMAIN_SEPARATOR;
                // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
                bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
                mapping(address => uint) public nonces;
            
                event Approval(address indexed owner, address indexed spender, uint value);
                event Transfer(address indexed from, address indexed to, uint value);
            
                constructor() public {
                    uint chainId;
                    assembly {
                        chainId := chainid()
                    }
                    DOMAIN_SEPARATOR = keccak256(
                        abi.encode(
                            keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
                            keccak256(bytes(name)),
                            keccak256(bytes('1')),
                            chainId,
                            address(this)
                        )
                    );
                }
            
                function _mint(address to, uint value) internal {
                    totalSupply = totalSupply.add(value);
                    balanceOf[to] = balanceOf[to].add(value);
                    emit Transfer(address(0), to, value);
                }
            
                function _burn(address from, uint value) internal {
                    balanceOf[from] = balanceOf[from].sub(value);
                    totalSupply = totalSupply.sub(value);
                    emit Transfer(from, address(0), value);
                }
            
                function _approve(address owner, address spender, uint value) private {
                    allowance[owner][spender] = value;
                    emit Approval(owner, spender, value);
                }
            
                function _transfer(address from, address to, uint value) private {
                    balanceOf[from] = balanceOf[from].sub(value);
                    balanceOf[to] = balanceOf[to].add(value);
                    emit Transfer(from, to, value);
                }
            
                function approve(address spender, uint value) external returns (bool) {
                    _approve(msg.sender, spender, value);
                    return true;
                }
            
                function transfer(address to, uint value) external returns (bool) {
                    _transfer(msg.sender, to, value);
                    return true;
                }
            
                function transferFrom(address from, address to, uint value) external returns (bool) {
                    if (allowance[from][msg.sender] != uint(-1)) {
                        allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
                    }
                    _transfer(from, to, value);
                    return true;
                }
            
                function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
                    require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
                    bytes32 digest = keccak256(
                        abi.encodePacked(
                            '\x19\x01',
                            DOMAIN_SEPARATOR,
                            keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
                        )
                    );
                    address recoveredAddress = ecrecover(digest, v, r, s);
                    require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
                    _approve(owner, spender, value);
                }
            }
            
            // File: contracts/uniswapv2/libraries/Math.sol
            
            pragma solidity =0.6.12;
            
            // a library for performing various math operations
            
            library Math {
                function min(uint x, uint y) internal pure returns (uint z) {
                    z = x < y ? x : y;
                }
            
                // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
                function sqrt(uint y) internal pure returns (uint z) {
                    if (y > 3) {
                        z = y;
                        uint x = y / 2 + 1;
                        while (x < z) {
                            z = x;
                            x = (y / x + x) / 2;
                        }
                    } else if (y != 0) {
                        z = 1;
                    }
                }
            }
            
            // File: contracts/uniswapv2/libraries/UQ112x112.sol
            
            pragma solidity =0.6.12;
            
            // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
            
            // range: [0, 2**112 - 1]
            // resolution: 1 / 2**112
            
            library UQ112x112 {
                uint224 constant Q112 = 2**112;
            
                // encode a uint112 as a UQ112x112
                function encode(uint112 y) internal pure returns (uint224 z) {
                    z = uint224(y) * Q112; // never overflows
                }
            
                // divide a UQ112x112 by a uint112, returning a UQ112x112
                function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
                    z = x / uint224(y);
                }
            }
            
            // File: contracts/uniswapv2/interfaces/IERC20.sol
            
            pragma solidity >=0.5.0;
            
            interface IERC20Uniswap {
                event Approval(address indexed owner, address indexed spender, uint value);
                event Transfer(address indexed from, address indexed to, uint value);
            
                function name() external view returns (string memory);
                function symbol() external view returns (string memory);
                function decimals() external view returns (uint8);
                function totalSupply() external view returns (uint);
                function balanceOf(address owner) external view returns (uint);
                function allowance(address owner, address spender) external view returns (uint);
            
                function approve(address spender, uint value) external returns (bool);
                function transfer(address to, uint value) external returns (bool);
                function transferFrom(address from, address to, uint value) external returns (bool);
            }
            
            // File: contracts/uniswapv2/interfaces/IUniswapV2Callee.sol
            
            pragma solidity >=0.5.0;
            
            interface IUniswapV2Callee {
                function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
            }
            
            // File: contracts/uniswapv2/UniswapV2Pair.sol
            
            pragma solidity =0.6.12;
            
            
            
            
            
            
            
            
            interface IMigrator {
                // Return the desired amount of liquidity token that the migrator wants.
                function desiredLiquidity() external view returns (uint256);
            }
            
            contract UniswapV2Pair is UniswapV2ERC20 {
                using SafeMathUniswap  for uint;
                using UQ112x112 for uint224;
            
                uint public constant MINIMUM_LIQUIDITY = 10**3;
                bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
            
                address public factory;
                address public token0;
                address public token1;
            
                uint112 private reserve0;           // uses single storage slot, accessible via getReserves
                uint112 private reserve1;           // uses single storage slot, accessible via getReserves
                uint32  private blockTimestampLast; // uses single storage slot, accessible via getReserves
            
                uint public price0CumulativeLast;
                uint public price1CumulativeLast;
                uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
            
                uint private unlocked = 1;
                modifier lock() {
                    require(unlocked == 1, 'UniswapV2: LOCKED');
                    unlocked = 0;
                    _;
                    unlocked = 1;
                }
            
                function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
                    _reserve0 = reserve0;
                    _reserve1 = reserve1;
                    _blockTimestampLast = blockTimestampLast;
                }
            
                function _safeTransfer(address token, address to, uint value) private {
                    (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
                    require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
                }
            
                event Mint(address indexed sender, uint amount0, uint amount1);
                event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
                event Swap(
                    address indexed sender,
                    uint amount0In,
                    uint amount1In,
                    uint amount0Out,
                    uint amount1Out,
                    address indexed to
                );
                event Sync(uint112 reserve0, uint112 reserve1);
            
                constructor() public {
                    factory = msg.sender;
                }
            
                // called once by the factory at time of deployment
                function initialize(address _token0, address _token1) external {
                    require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
                    token0 = _token0;
                    token1 = _token1;
                }
            
                // update reserves and, on the first call per block, price accumulators
                function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
                    require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
                    uint32 blockTimestamp = uint32(block.timestamp % 2**32);
                    uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
                    if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
                        // * never overflows, and + overflow is desired
                        price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
                        price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
                    }
                    reserve0 = uint112(balance0);
                    reserve1 = uint112(balance1);
                    blockTimestampLast = blockTimestamp;
                    emit Sync(reserve0, reserve1);
                }
            
                // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
                function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
                    address feeTo = IUniswapV2Factory(factory).feeTo();
                    feeOn = feeTo != address(0);
                    uint _kLast = kLast; // gas savings
                    if (feeOn) {
                        if (_kLast != 0) {
                            uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
                            uint rootKLast = Math.sqrt(_kLast);
                            if (rootK > rootKLast) {
                                uint numerator = totalSupply.mul(rootK.sub(rootKLast));
                                uint denominator = rootK.mul(5).add(rootKLast);
                                uint liquidity = numerator / denominator;
                                if (liquidity > 0) _mint(feeTo, liquidity);
                            }
                        }
                    } else if (_kLast != 0) {
                        kLast = 0;
                    }
                }
            
                // this low-level function should be called from a contract which performs important safety checks
                function mint(address to) external lock returns (uint liquidity) {
                    (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                    uint balance0 = IERC20Uniswap(token0).balanceOf(address(this));
                    uint balance1 = IERC20Uniswap(token1).balanceOf(address(this));
                    uint amount0 = balance0.sub(_reserve0);
                    uint amount1 = balance1.sub(_reserve1);
            
                    bool feeOn = _mintFee(_reserve0, _reserve1);
                    uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                    if (_totalSupply == 0) {
                        address migrator = IUniswapV2Factory(factory).migrator();
                        if (msg.sender == migrator) {
                            liquidity = IMigrator(migrator).desiredLiquidity();
                            require(liquidity > 0 && liquidity != uint256(-1), "Bad desired liquidity");
                        } else {
                            require(migrator == address(0), "Must not have migrator");
                            liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
                            _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
                        }
                    } else {
                        liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
                    }
                    require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
                    _mint(to, liquidity);
            
                    _update(balance0, balance1, _reserve0, _reserve1);
                    if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
                    emit Mint(msg.sender, amount0, amount1);
                }
            
                // this low-level function should be called from a contract which performs important safety checks
                function burn(address to) external lock returns (uint amount0, uint amount1) {
                    (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                    address _token0 = token0;                                // gas savings
                    address _token1 = token1;                                // gas savings
                    uint balance0 = IERC20Uniswap(_token0).balanceOf(address(this));
                    uint balance1 = IERC20Uniswap(_token1).balanceOf(address(this));
                    uint liquidity = balanceOf[address(this)];
            
                    bool feeOn = _mintFee(_reserve0, _reserve1);
                    uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                    amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
                    amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
                    require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
                    _burn(address(this), liquidity);
                    _safeTransfer(_token0, to, amount0);
                    _safeTransfer(_token1, to, amount1);
                    balance0 = IERC20Uniswap(_token0).balanceOf(address(this));
                    balance1 = IERC20Uniswap(_token1).balanceOf(address(this));
            
                    _update(balance0, balance1, _reserve0, _reserve1);
                    if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
                    emit Burn(msg.sender, amount0, amount1, to);
                }
            
                // this low-level function should be called from a contract which performs important safety checks
                function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
                    require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
                    (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                    require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
            
                    uint balance0;
                    uint balance1;
                    { // scope for _token{0,1}, avoids stack too deep errors
                    address _token0 = token0;
                    address _token1 = token1;
                    require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
                    if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
                    if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
                    if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
                    balance0 = IERC20Uniswap(_token0).balanceOf(address(this));
                    balance1 = IERC20Uniswap(_token1).balanceOf(address(this));
                    }
                    uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
                    uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
                    require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
                    { // scope for reserve{0,1}Adjusted, avoids stack too deep errors
                    uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
                    uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
                    require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
                    }
            
                    _update(balance0, balance1, _reserve0, _reserve1);
                    emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
                }
            
                // force balances to match reserves
                function skim(address to) external lock {
                    address _token0 = token0; // gas savings
                    address _token1 = token1; // gas savings
                    _safeTransfer(_token0, to, IERC20Uniswap(_token0).balanceOf(address(this)).sub(reserve0));
                    _safeTransfer(_token1, to, IERC20Uniswap(_token1).balanceOf(address(this)).sub(reserve1));
                }
            
                // force reserves to match balances
                function sync() external lock {
                    _update(IERC20Uniswap(token0).balanceOf(address(this)), IERC20Uniswap(token1).balanceOf(address(this)), reserve0, reserve1);
                }
            }
            
            // File: contracts/uniswapv2/UniswapV2Factory.sol
            
            pragma solidity =0.6.12;
            
            
            
            contract UniswapV2Factory is IUniswapV2Factory {
                address public override feeTo;
                address public override feeToSetter;
                address public override migrator;
            
                mapping(address => mapping(address => address)) public override getPair;
                address[] public override allPairs;
            
                event PairCreated(address indexed token0, address indexed token1, address pair, uint);
            
                constructor(address _feeToSetter) public {
                    feeToSetter = _feeToSetter;
                }
            
                function allPairsLength() external override view returns (uint) {
                    return allPairs.length;
                }
            
                function pairCodeHash() external pure returns (bytes32) {
                    return keccak256(type(UniswapV2Pair).creationCode);
                }
            
                function createPair(address tokenA, address tokenB) external override returns (address pair) {
                    require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');
                    (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
                    require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');
                    require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
                    bytes memory bytecode = type(UniswapV2Pair).creationCode;
                    bytes32 salt = keccak256(abi.encodePacked(token0, token1));
                    assembly {
                        pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
                    }
                    UniswapV2Pair(pair).initialize(token0, token1);
                    getPair[token0][token1] = pair;
                    getPair[token1][token0] = pair; // populate mapping in the reverse direction
                    allPairs.push(pair);
                    emit PairCreated(token0, token1, pair, allPairs.length);
                }
            
                function setFeeTo(address _feeTo) external override {
                    require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
                    feeTo = _feeTo;
                }
            
                function setMigrator(address _migrator) external override {
                    require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
                    migrator = _migrator;
                }
            
                function setFeeToSetter(address _feeToSetter) external override {
                    require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN');
                    feeToSetter = _feeToSetter;
                }
            
            }

            File 3 of 6: TransparentUpgradeableProxy
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            import "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol";
            import "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol";
            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 "./IBeacon.sol";
            import "../Proxy.sol";
            import "../ERC1967/ERC1967Upgrade.sol";
            /**
             * @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}.
             *
             * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't
             * conflict with the storage layout of the implementation behind the proxy.
             *
             * _Available since v3.4._
             */
            contract BeaconProxy is Proxy, ERC1967Upgrade {
                /**
                 * @dev Initializes the proxy with `beacon`.
                 *
                 * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This
                 * will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity
                 * constructor.
                 *
                 * Requirements:
                 *
                 * - `beacon` must be a contract with the interface {IBeacon}.
                 */
                constructor(address beacon, bytes memory data) payable {
                    assert(_BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1));
                    _upgradeBeaconToAndCall(beacon, data, false);
                }
                /**
                 * @dev Returns the current beacon address.
                 */
                function _beacon() internal view virtual returns (address) {
                    return _getBeacon();
                }
                /**
                 * @dev Returns the current implementation address of the associated beacon.
                 */
                function _implementation() internal view virtual override returns (address) {
                    return IBeacon(_getBeacon()).implementation();
                }
                /**
                 * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}.
                 *
                 * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon.
                 *
                 * Requirements:
                 *
                 * - `beacon` must be a contract.
                 * - The implementation returned by `beacon` must be a contract.
                 */
                function _setBeacon(address beacon, bytes memory data) internal virtual {
                    _upgradeBeaconToAndCall(beacon, data, false);
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity ^0.8.0;
            import "./IBeacon.sol";
            import "../../access/Ownable.sol";
            import "../../utils/Address.sol";
            /**
             * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their
             * implementation contract, which is where they will delegate all function calls.
             *
             * An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon.
             */
            contract UpgradeableBeacon is IBeacon, Ownable {
                address private _implementation;
                /**
                 * @dev Emitted when the implementation returned by the beacon is changed.
                 */
                event Upgraded(address indexed implementation);
                /**
                 * @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the
                 * beacon.
                 */
                constructor(address implementation_) {
                    _setImplementation(implementation_);
                }
                /**
                 * @dev Returns the current implementation address.
                 */
                function implementation() public view virtual override returns (address) {
                    return _implementation;
                }
                /**
                 * @dev Upgrades the beacon to a new implementation.
                 *
                 * Emits an {Upgraded} event.
                 *
                 * Requirements:
                 *
                 * - msg.sender must be the owner of the contract.
                 * - `newImplementation` must be a contract.
                 */
                function upgradeTo(address newImplementation) public virtual onlyOwner {
                    _setImplementation(newImplementation);
                    emit Upgraded(newImplementation);
                }
                /**
                 * @dev Sets the implementation contract address for this beacon
                 *
                 * Requirements:
                 *
                 * - `newImplementation` must be a contract.
                 */
                function _setImplementation(address newImplementation) private {
                    require(Address.isContract(newImplementation), "UpgradeableBeacon: implementation is not a contract");
                    _implementation = newImplementation;
                }
            }
            // 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 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 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 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;
                }
            }
            

            File 4 of 6: WETH9
            // Copyright (C) 2015, 2016, 2017 Dapphub
            
            // This program is free software: you can redistribute it and/or modify
            // it under the terms of the GNU General Public License as published by
            // the Free Software Foundation, either version 3 of the License, or
            // (at your option) any later version.
            
            // This program is distributed in the hope that it will be useful,
            // but WITHOUT ANY WARRANTY; without even the implied warranty of
            // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
            // GNU General Public License for more details.
            
            // You should have received a copy of the GNU General Public License
            // along with this program.  If not, see <http://www.gnu.org/licenses/>.
            
            pragma solidity ^0.4.18;
            
            contract WETH9 {
                string public name     = "Wrapped Ether";
                string public symbol   = "WETH";
                uint8  public decimals = 18;
            
                event  Approval(address indexed src, address indexed guy, uint wad);
                event  Transfer(address indexed src, address indexed dst, uint wad);
                event  Deposit(address indexed dst, uint wad);
                event  Withdrawal(address indexed src, uint wad);
            
                mapping (address => uint)                       public  balanceOf;
                mapping (address => mapping (address => uint))  public  allowance;
            
                function() public payable {
                    deposit();
                }
                function deposit() public payable {
                    balanceOf[msg.sender] += msg.value;
                    Deposit(msg.sender, msg.value);
                }
                function withdraw(uint wad) public {
                    require(balanceOf[msg.sender] >= wad);
                    balanceOf[msg.sender] -= wad;
                    msg.sender.transfer(wad);
                    Withdrawal(msg.sender, wad);
                }
            
                function totalSupply() public view returns (uint) {
                    return this.balance;
                }
            
                function approve(address guy, uint wad) public returns (bool) {
                    allowance[msg.sender][guy] = wad;
                    Approval(msg.sender, guy, wad);
                    return true;
                }
            
                function transfer(address dst, uint wad) public returns (bool) {
                    return transferFrom(msg.sender, dst, wad);
                }
            
                function transferFrom(address src, address dst, uint wad)
                    public
                    returns (bool)
                {
                    require(balanceOf[src] >= wad);
            
                    if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
                        require(allowance[src][msg.sender] >= wad);
                        allowance[src][msg.sender] -= wad;
                    }
            
                    balanceOf[src] -= wad;
                    balanceOf[dst] += wad;
            
                    Transfer(src, dst, wad);
            
                    return true;
                }
            }
            
            
            /*
                                GNU GENERAL PUBLIC LICENSE
                                   Version 3, 29 June 2007
            
             Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
             Everyone is permitted to copy and distribute verbatim copies
             of this license document, but changing it is not allowed.
            
                                        Preamble
            
              The GNU General Public License is a free, copyleft license for
            software and other kinds of works.
            
              The licenses for most software and other practical works are designed
            to take away your freedom to share and change the works.  By contrast,
            the GNU General Public License is intended to guarantee your freedom to
            share and change all versions of a program--to make sure it remains free
            software for all its users.  We, the Free Software Foundation, use the
            GNU General Public License for most of our software; it applies also to
            any other work released this way by its authors.  You can apply it to
            your programs, too.
            
              When we speak of free software, we are referring to freedom, not
            price.  Our General Public Licenses are designed to make sure that you
            have the freedom to distribute copies of free software (and charge for
            them if you wish), that you receive source code or can get it if you
            want it, that you can change the software or use pieces of it in new
            free programs, and that you know you can do these things.
            
              To protect your rights, we need to prevent others from denying you
            these rights or asking you to surrender the rights.  Therefore, you have
            certain responsibilities if you distribute copies of the software, or if
            you modify it: responsibilities to respect the freedom of others.
            
              For example, if you distribute copies of such a program, whether
            gratis or for a fee, you must pass on to the recipients the same
            freedoms that you received.  You must make sure that they, too, receive
            or can get the source code.  And you must show them these terms so they
            know their rights.
            
              Developers that use the GNU GPL protect your rights with two steps:
            (1) assert copyright on the software, and (2) offer you this License
            giving you legal permission to copy, distribute and/or modify it.
            
              For the developers' and authors' protection, the GPL clearly explains
            that there is no warranty for this free software.  For both users' and
            authors' sake, the GPL requires that modified versions be marked as
            changed, so that their problems will not be attributed erroneously to
            authors of previous versions.
            
              Some devices are designed to deny users access to install or run
            modified versions of the software inside them, although the manufacturer
            can do so.  This is fundamentally incompatible with the aim of
            protecting users' freedom to change the software.  The systematic
            pattern of such abuse occurs in the area of products for individuals to
            use, which is precisely where it is most unacceptable.  Therefore, we
            have designed this version of the GPL to prohibit the practice for those
            products.  If such problems arise substantially in other domains, we
            stand ready to extend this provision to those domains in future versions
            of the GPL, as needed to protect the freedom of users.
            
              Finally, every program is threatened constantly by software patents.
            States should not allow patents to restrict development and use of
            software on general-purpose computers, but in those that do, we wish to
            avoid the special danger that patents applied to a free program could
            make it effectively proprietary.  To prevent this, the GPL assures that
            patents cannot be used to render the program non-free.
            
              The precise terms and conditions for copying, distribution and
            modification follow.
            
                                   TERMS AND CONDITIONS
            
              0. Definitions.
            
              "This License" refers to version 3 of the GNU General Public License.
            
              "Copyright" also means copyright-like laws that apply to other kinds of
            works, such as semiconductor masks.
            
              "The Program" refers to any copyrightable work licensed under this
            License.  Each licensee is addressed as "you".  "Licensees" and
            "recipients" may be individuals or organizations.
            
              To "modify" a work means to copy from or adapt all or part of the work
            in a fashion requiring copyright permission, other than the making of an
            exact copy.  The resulting work is called a "modified version" of the
            earlier work or a work "based on" the earlier work.
            
              A "covered work" means either the unmodified Program or a work based
            on the Program.
            
              To "propagate" a work means to do anything with it that, without
            permission, would make you directly or secondarily liable for
            infringement under applicable copyright law, except executing it on a
            computer or modifying a private copy.  Propagation includes copying,
            distribution (with or without modification), making available to the
            public, and in some countries other activities as well.
            
              To "convey" a work means any kind of propagation that enables other
            parties to make or receive copies.  Mere interaction with a user through
            a computer network, with no transfer of a copy, is not conveying.
            
              An interactive user interface displays "Appropriate Legal Notices"
            to the extent that it includes a convenient and prominently visible
            feature that (1) displays an appropriate copyright notice, and (2)
            tells the user that there is no warranty for the work (except to the
            extent that warranties are provided), that licensees may convey the
            work under this License, and how to view a copy of this License.  If
            the interface presents a list of user commands or options, such as a
            menu, a prominent item in the list meets this criterion.
            
              1. Source Code.
            
              The "source code" for a work means the preferred form of the work
            for making modifications to it.  "Object code" means any non-source
            form of a work.
            
              A "Standard Interface" means an interface that either is an official
            standard defined by a recognized standards body, or, in the case of
            interfaces specified for a particular programming language, one that
            is widely used among developers working in that language.
            
              The "System Libraries" of an executable work include anything, other
            than the work as a whole, that (a) is included in the normal form of
            packaging a Major Component, but which is not part of that Major
            Component, and (b) serves only to enable use of the work with that
            Major Component, or to implement a Standard Interface for which an
            implementation is available to the public in source code form.  A
            "Major Component", in this context, means a major essential component
            (kernel, window system, and so on) of the specific operating system
            (if any) on which the executable work runs, or a compiler used to
            produce the work, or an object code interpreter used to run it.
            
              The "Corresponding Source" for a work in object code form means all
            the source code needed to generate, install, and (for an executable
            work) run the object code and to modify the work, including scripts to
            control those activities.  However, it does not include the work's
            System Libraries, or general-purpose tools or generally available free
            programs which are used unmodified in performing those activities but
            which are not part of the work.  For example, Corresponding Source
            includes interface definition files associated with source files for
            the work, and the source code for shared libraries and dynamically
            linked subprograms that the work is specifically designed to require,
            such as by intimate data communication or control flow between those
            subprograms and other parts of the work.
            
              The Corresponding Source need not include anything that users
            can regenerate automatically from other parts of the Corresponding
            Source.
            
              The Corresponding Source for a work in source code form is that
            same work.
            
              2. Basic Permissions.
            
              All rights granted under this License are granted for the term of
            copyright on the Program, and are irrevocable provided the stated
            conditions are met.  This License explicitly affirms your unlimited
            permission to run the unmodified Program.  The output from running a
            covered work is covered by this License only if the output, given its
            content, constitutes a covered work.  This License acknowledges your
            rights of fair use or other equivalent, as provided by copyright law.
            
              You may make, run and propagate covered works that you do not
            convey, without conditions so long as your license otherwise remains
            in force.  You may convey covered works to others for the sole purpose
            of having them make modifications exclusively for you, or provide you
            with facilities for running those works, provided that you comply with
            the terms of this License in conveying all material for which you do
            not control copyright.  Those thus making or running the covered works
            for you must do so exclusively on your behalf, under your direction
            and control, on terms that prohibit them from making any copies of
            your copyrighted material outside their relationship with you.
            
              Conveying under any other circumstances is permitted solely under
            the conditions stated below.  Sublicensing is not allowed; section 10
            makes it unnecessary.
            
              3. Protecting Users' Legal Rights From Anti-Circumvention Law.
            
              No covered work shall be deemed part of an effective technological
            measure under any applicable law fulfilling obligations under article
            11 of the WIPO copyright treaty adopted on 20 December 1996, or
            similar laws prohibiting or restricting circumvention of such
            measures.
            
              When you convey a covered work, you waive any legal power to forbid
            circumvention of technological measures to the extent such circumvention
            is effected by exercising rights under this License with respect to
            the covered work, and you disclaim any intention to limit operation or
            modification of the work as a means of enforcing, against the work's
            users, your or third parties' legal rights to forbid circumvention of
            technological measures.
            
              4. Conveying Verbatim Copies.
            
              You may convey verbatim copies of the Program's source code as you
            receive it, in any medium, provided that you conspicuously and
            appropriately publish on each copy an appropriate copyright notice;
            keep intact all notices stating that this License and any
            non-permissive terms added in accord with section 7 apply to the code;
            keep intact all notices of the absence of any warranty; and give all
            recipients a copy of this License along with the Program.
            
              You may charge any price or no price for each copy that you convey,
            and you may offer support or warranty protection for a fee.
            
              5. Conveying Modified Source Versions.
            
              You may convey a work based on the Program, or the modifications to
            produce it from the Program, in the form of source code under the
            terms of section 4, provided that you also meet all of these conditions:
            
                a) The work must carry prominent notices stating that you modified
                it, and giving a relevant date.
            
                b) The work must carry prominent notices stating that it is
                released under this License and any conditions added under section
                7.  This requirement modifies the requirement in section 4 to
                "keep intact all notices".
            
                c) You must license the entire work, as a whole, under this
                License to anyone who comes into possession of a copy.  This
                License will therefore apply, along with any applicable section 7
                additional terms, to the whole of the work, and all its parts,
                regardless of how they are packaged.  This License gives no
                permission to license the work in any other way, but it does not
                invalidate such permission if you have separately received it.
            
                d) If the work has interactive user interfaces, each must display
                Appropriate Legal Notices; however, if the Program has interactive
                interfaces that do not display Appropriate Legal Notices, your
                work need not make them do so.
            
              A compilation of a covered work with other separate and independent
            works, which are not by their nature extensions of the covered work,
            and which are not combined with it such as to form a larger program,
            in or on a volume of a storage or distribution medium, is called an
            "aggregate" if the compilation and its resulting copyright are not
            used to limit the access or legal rights of the compilation's users
            beyond what the individual works permit.  Inclusion of a covered work
            in an aggregate does not cause this License to apply to the other
            parts of the aggregate.
            
              6. Conveying Non-Source Forms.
            
              You may convey a covered work in object code form under the terms
            of sections 4 and 5, provided that you also convey the
            machine-readable Corresponding Source under the terms of this License,
            in one of these ways:
            
                a) Convey the object code in, or embodied in, a physical product
                (including a physical distribution medium), accompanied by the
                Corresponding Source fixed on a durable physical medium
                customarily used for software interchange.
            
                b) Convey the object code in, or embodied in, a physical product
                (including a physical distribution medium), accompanied by a
                written offer, valid for at least three years and valid for as
                long as you offer spare parts or customer support for that product
                model, to give anyone who possesses the object code either (1) a
                copy of the Corresponding Source for all the software in the
                product that is covered by this License, on a durable physical
                medium customarily used for software interchange, for a price no
                more than your reasonable cost of physically performing this
                conveying of source, or (2) access to copy the
                Corresponding Source from a network server at no charge.
            
                c) Convey individual copies of the object code with a copy of the
                written offer to provide the Corresponding Source.  This
                alternative is allowed only occasionally and noncommercially, and
                only if you received the object code with such an offer, in accord
                with subsection 6b.
            
                d) Convey the object code by offering access from a designated
                place (gratis or for a charge), and offer equivalent access to the
                Corresponding Source in the same way through the same place at no
                further charge.  You need not require recipients to copy the
                Corresponding Source along with the object code.  If the place to
                copy the object code is a network server, the Corresponding Source
                may be on a different server (operated by you or a third party)
                that supports equivalent copying facilities, provided you maintain
                clear directions next to the object code saying where to find the
                Corresponding Source.  Regardless of what server hosts the
                Corresponding Source, you remain obligated to ensure that it is
                available for as long as needed to satisfy these requirements.
            
                e) Convey the object code using peer-to-peer transmission, provided
                you inform other peers where the object code and Corresponding
                Source of the work are being offered to the general public at no
                charge under subsection 6d.
            
              A separable portion of the object code, whose source code is excluded
            from the Corresponding Source as a System Library, need not be
            included in conveying the object code work.
            
              A "User Product" is either (1) a "consumer product", which means any
            tangible personal property which is normally used for personal, family,
            or household purposes, or (2) anything designed or sold for incorporation
            into a dwelling.  In determining whether a product is a consumer product,
            doubtful cases shall be resolved in favor of coverage.  For a particular
            product received by a particular user, "normally used" refers to a
            typical or common use of that class of product, regardless of the status
            of the particular user or of the way in which the particular user
            actually uses, or expects or is expected to use, the product.  A product
            is a consumer product regardless of whether the product has substantial
            commercial, industrial or non-consumer uses, unless such uses represent
            the only significant mode of use of the product.
            
              "Installation Information" for a User Product means any methods,
            procedures, authorization keys, or other information required to install
            and execute modified versions of a covered work in that User Product from
            a modified version of its Corresponding Source.  The information must
            suffice to ensure that the continued functioning of the modified object
            code is in no case prevented or interfered with solely because
            modification has been made.
            
              If you convey an object code work under this section in, or with, or
            specifically for use in, a User Product, and the conveying occurs as
            part of a transaction in which the right of possession and use of the
            User Product is transferred to the recipient in perpetuity or for a
            fixed term (regardless of how the transaction is characterized), the
            Corresponding Source conveyed under this section must be accompanied
            by the Installation Information.  But this requirement does not apply
            if neither you nor any third party retains the ability to install
            modified object code on the User Product (for example, the work has
            been installed in ROM).
            
              The requirement to provide Installation Information does not include a
            requirement to continue to provide support service, warranty, or updates
            for a work that has been modified or installed by the recipient, or for
            the User Product in which it has been modified or installed.  Access to a
            network may be denied when the modification itself materially and
            adversely affects the operation of the network or violates the rules and
            protocols for communication across the network.
            
              Corresponding Source conveyed, and Installation Information provided,
            in accord with this section must be in a format that is publicly
            documented (and with an implementation available to the public in
            source code form), and must require no special password or key for
            unpacking, reading or copying.
            
              7. Additional Terms.
            
              "Additional permissions" are terms that supplement the terms of this
            License by making exceptions from one or more of its conditions.
            Additional permissions that are applicable to the entire Program shall
            be treated as though they were included in this License, to the extent
            that they are valid under applicable law.  If additional permissions
            apply only to part of the Program, that part may be used separately
            under those permissions, but the entire Program remains governed by
            this License without regard to the additional permissions.
            
              When you convey a copy of a covered work, you may at your option
            remove any additional permissions from that copy, or from any part of
            it.  (Additional permissions may be written to require their own
            removal in certain cases when you modify the work.)  You may place
            additional permissions on material, added by you to a covered work,
            for which you have or can give appropriate copyright permission.
            
              Notwithstanding any other provision of this License, for material you
            add to a covered work, you may (if authorized by the copyright holders of
            that material) supplement the terms of this License with terms:
            
                a) Disclaiming warranty or limiting liability differently from the
                terms of sections 15 and 16 of this License; or
            
                b) Requiring preservation of specified reasonable legal notices or
                author attributions in that material or in the Appropriate Legal
                Notices displayed by works containing it; or
            
                c) Prohibiting misrepresentation of the origin of that material, or
                requiring that modified versions of such material be marked in
                reasonable ways as different from the original version; or
            
                d) Limiting the use for publicity purposes of names of licensors or
                authors of the material; or
            
                e) Declining to grant rights under trademark law for use of some
                trade names, trademarks, or service marks; or
            
                f) Requiring indemnification of licensors and authors of that
                material by anyone who conveys the material (or modified versions of
                it) with contractual assumptions of liability to the recipient, for
                any liability that these contractual assumptions directly impose on
                those licensors and authors.
            
              All other non-permissive additional terms are considered "further
            restrictions" within the meaning of section 10.  If the Program as you
            received it, or any part of it, contains a notice stating that it is
            governed by this License along with a term that is a further
            restriction, you may remove that term.  If a license document contains
            a further restriction but permits relicensing or conveying under this
            License, you may add to a covered work material governed by the terms
            of that license document, provided that the further restriction does
            not survive such relicensing or conveying.
            
              If you add terms to a covered work in accord with this section, you
            must place, in the relevant source files, a statement of the
            additional terms that apply to those files, or a notice indicating
            where to find the applicable terms.
            
              Additional terms, permissive or non-permissive, may be stated in the
            form of a separately written license, or stated as exceptions;
            the above requirements apply either way.
            
              8. Termination.
            
              You may not propagate or modify a covered work except as expressly
            provided under this License.  Any attempt otherwise to propagate or
            modify it is void, and will automatically terminate your rights under
            this License (including any patent licenses granted under the third
            paragraph of section 11).
            
              However, if you cease all violation of this License, then your
            license from a particular copyright holder is reinstated (a)
            provisionally, unless and until the copyright holder explicitly and
            finally terminates your license, and (b) permanently, if the copyright
            holder fails to notify you of the violation by some reasonable means
            prior to 60 days after the cessation.
            
              Moreover, your license from a particular copyright holder is
            reinstated permanently if the copyright holder notifies you of the
            violation by some reasonable means, this is the first time you have
            received notice of violation of this License (for any work) from that
            copyright holder, and you cure the violation prior to 30 days after
            your receipt of the notice.
            
              Termination of your rights under this section does not terminate the
            licenses of parties who have received copies or rights from you under
            this License.  If your rights have been terminated and not permanently
            reinstated, you do not qualify to receive new licenses for the same
            material under section 10.
            
              9. Acceptance Not Required for Having Copies.
            
              You are not required to accept this License in order to receive or
            run a copy of the Program.  Ancillary propagation of a covered work
            occurring solely as a consequence of using peer-to-peer transmission
            to receive a copy likewise does not require acceptance.  However,
            nothing other than this License grants you permission to propagate or
            modify any covered work.  These actions infringe copyright if you do
            not accept this License.  Therefore, by modifying or propagating a
            covered work, you indicate your acceptance of this License to do so.
            
              10. Automatic Licensing of Downstream Recipients.
            
              Each time you convey a covered work, the recipient automatically
            receives a license from the original licensors, to run, modify and
            propagate that work, subject to this License.  You are not responsible
            for enforcing compliance by third parties with this License.
            
              An "entity transaction" is a transaction transferring control of an
            organization, or substantially all assets of one, or subdividing an
            organization, or merging organizations.  If propagation of a covered
            work results from an entity transaction, each party to that
            transaction who receives a copy of the work also receives whatever
            licenses to the work the party's predecessor in interest had or could
            give under the previous paragraph, plus a right to possession of the
            Corresponding Source of the work from the predecessor in interest, if
            the predecessor has it or can get it with reasonable efforts.
            
              You may not impose any further restrictions on the exercise of the
            rights granted or affirmed under this License.  For example, you may
            not impose a license fee, royalty, or other charge for exercise of
            rights granted under this License, and you may not initiate litigation
            (including a cross-claim or counterclaim in a lawsuit) alleging that
            any patent claim is infringed by making, using, selling, offering for
            sale, or importing the Program or any portion of it.
            
              11. Patents.
            
              A "contributor" is a copyright holder who authorizes use under this
            License of the Program or a work on which the Program is based.  The
            work thus licensed is called the contributor's "contributor version".
            
              A contributor's "essential patent claims" are all patent claims
            owned or controlled by the contributor, whether already acquired or
            hereafter acquired, that would be infringed by some manner, permitted
            by this License, of making, using, or selling its contributor version,
            but do not include claims that would be infringed only as a
            consequence of further modification of the contributor version.  For
            purposes of this definition, "control" includes the right to grant
            patent sublicenses in a manner consistent with the requirements of
            this License.
            
              Each contributor grants you a non-exclusive, worldwide, royalty-free
            patent license under the contributor's essential patent claims, to
            make, use, sell, offer for sale, import and otherwise run, modify and
            propagate the contents of its contributor version.
            
              In the following three paragraphs, a "patent license" is any express
            agreement or commitment, however denominated, not to enforce a patent
            (such as an express permission to practice a patent or covenant not to
            sue for patent infringement).  To "grant" such a patent license to a
            party means to make such an agreement or commitment not to enforce a
            patent against the party.
            
              If you convey a covered work, knowingly relying on a patent license,
            and the Corresponding Source of the work is not available for anyone
            to copy, free of charge and under the terms of this License, through a
            publicly available network server or other readily accessible means,
            then you must either (1) cause the Corresponding Source to be so
            available, or (2) arrange to deprive yourself of the benefit of the
            patent license for this particular work, or (3) arrange, in a manner
            consistent with the requirements of this License, to extend the patent
            license to downstream recipients.  "Knowingly relying" means you have
            actual knowledge that, but for the patent license, your conveying the
            covered work in a country, or your recipient's use of the covered work
            in a country, would infringe one or more identifiable patents in that
            country that you have reason to believe are valid.
            
              If, pursuant to or in connection with a single transaction or
            arrangement, you convey, or propagate by procuring conveyance of, a
            covered work, and grant a patent license to some of the parties
            receiving the covered work authorizing them to use, propagate, modify
            or convey a specific copy of the covered work, then the patent license
            you grant is automatically extended to all recipients of the covered
            work and works based on it.
            
              A patent license is "discriminatory" if it does not include within
            the scope of its coverage, prohibits the exercise of, or is
            conditioned on the non-exercise of one or more of the rights that are
            specifically granted under this License.  You may not convey a covered
            work if you are a party to an arrangement with a third party that is
            in the business of distributing software, under which you make payment
            to the third party based on the extent of your activity of conveying
            the work, and under which the third party grants, to any of the
            parties who would receive the covered work from you, a discriminatory
            patent license (a) in connection with copies of the covered work
            conveyed by you (or copies made from those copies), or (b) primarily
            for and in connection with specific products or compilations that
            contain the covered work, unless you entered into that arrangement,
            or that patent license was granted, prior to 28 March 2007.
            
              Nothing in this License shall be construed as excluding or limiting
            any implied license or other defenses to infringement that may
            otherwise be available to you under applicable patent law.
            
              12. No Surrender of Others' Freedom.
            
              If conditions are imposed on you (whether by court order, agreement or
            otherwise) that contradict the conditions of this License, they do not
            excuse you from the conditions of this License.  If you cannot convey a
            covered work so as to satisfy simultaneously your obligations under this
            License and any other pertinent obligations, then as a consequence you may
            not convey it at all.  For example, if you agree to terms that obligate you
            to collect a royalty for further conveying from those to whom you convey
            the Program, the only way you could satisfy both those terms and this
            License would be to refrain entirely from conveying the Program.
            
              13. Use with the GNU Affero General Public License.
            
              Notwithstanding any other provision of this License, you have
            permission to link or combine any covered work with a work licensed
            under version 3 of the GNU Affero General Public License into a single
            combined work, and to convey the resulting work.  The terms of this
            License will continue to apply to the part which is the covered work,
            but the special requirements of the GNU Affero General Public License,
            section 13, concerning interaction through a network will apply to the
            combination as such.
            
              14. Revised Versions of this License.
            
              The Free Software Foundation may publish revised and/or new versions of
            the GNU General Public License from time to time.  Such new versions will
            be similar in spirit to the present version, but may differ in detail to
            address new problems or concerns.
            
              Each version is given a distinguishing version number.  If the
            Program specifies that a certain numbered version of the GNU General
            Public License "or any later version" applies to it, you have the
            option of following the terms and conditions either of that numbered
            version or of any later version published by the Free Software
            Foundation.  If the Program does not specify a version number of the
            GNU General Public License, you may choose any version ever published
            by the Free Software Foundation.
            
              If the Program specifies that a proxy can decide which future
            versions of the GNU General Public License can be used, that proxy's
            public statement of acceptance of a version permanently authorizes you
            to choose that version for the Program.
            
              Later license versions may give you additional or different
            permissions.  However, no additional obligations are imposed on any
            author or copyright holder as a result of your choosing to follow a
            later version.
            
              15. Disclaimer of Warranty.
            
              THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
            APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
            HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
            OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
            THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
            PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
            IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
            ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
            
              16. Limitation of Liability.
            
              IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
            WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
            THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
            GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
            USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
            DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
            PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
            EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
            SUCH DAMAGES.
            
              17. Interpretation of Sections 15 and 16.
            
              If the disclaimer of warranty and limitation of liability provided
            above cannot be given local legal effect according to their terms,
            reviewing courts shall apply local law that most closely approximates
            an absolute waiver of all civil liability in connection with the
            Program, unless a warranty or assumption of liability accompanies a
            copy of the Program in return for a fee.
            
                                 END OF TERMS AND CONDITIONS
            
                        How to Apply These Terms to Your New Programs
            
              If you develop a new program, and you want it to be of the greatest
            possible use to the public, the best way to achieve this is to make it
            free software which everyone can redistribute and change under these terms.
            
              To do so, attach the following notices to the program.  It is safest
            to attach them to the start of each source file to most effectively
            state the exclusion of warranty; and each file should have at least
            the "copyright" line and a pointer to where the full notice is found.
            
                <one line to give the program's name and a brief idea of what it does.>
                Copyright (C) <year>  <name of author>
            
                This program is free software: you can redistribute it and/or modify
                it under the terms of the GNU General Public License as published by
                the Free Software Foundation, either version 3 of the License, or
                (at your option) any later version.
            
                This program is distributed in the hope that it will be useful,
                but WITHOUT ANY WARRANTY; without even the implied warranty of
                MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                GNU General Public License for more details.
            
                You should have received a copy of the GNU General Public License
                along with this program.  If not, see <http://www.gnu.org/licenses/>.
            
            Also add information on how to contact you by electronic and paper mail.
            
              If the program does terminal interaction, make it output a short
            notice like this when it starts in an interactive mode:
            
                <program>  Copyright (C) <year>  <name of author>
                This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
                This is free software, and you are welcome to redistribute it
                under certain conditions; type `show c' for details.
            
            The hypothetical commands `show w' and `show c' should show the appropriate
            parts of the General Public License.  Of course, your program's commands
            might be different; for a GUI interface, you would use an "about box".
            
              You should also get your employer (if you work as a programmer) or school,
            if any, to sign a "copyright disclaimer" for the program, if necessary.
            For more information on this, and how to apply and follow the GNU GPL, see
            <http://www.gnu.org/licenses/>.
            
              The GNU General Public License does not permit incorporating your program
            into proprietary programs.  If your program is a subroutine library, you
            may consider it more useful to permit linking proprietary applications with
            the library.  If this is what you want to do, use the GNU Lesser General
            Public License instead of this License.  But first, please read
            <http://www.gnu.org/philosophy/why-not-lgpl.html>.
            
            */

            File 5 of 6: UniswapV2Pair
            // File: contracts/uniswapv2/interfaces/IUniswapV2Factory.sol
            
            pragma solidity >=0.5.0;
            
            interface IUniswapV2Factory {
                event PairCreated(address indexed token0, address indexed token1, address pair, uint);
            
                function feeTo() external view returns (address);
                function feeToSetter() external view returns (address);
                function migrator() external view returns (address);
            
                function getPair(address tokenA, address tokenB) external view returns (address pair);
                function allPairs(uint) external view returns (address pair);
                function allPairsLength() external view returns (uint);
            
                function createPair(address tokenA, address tokenB) external returns (address pair);
            
                function setFeeTo(address) external;
                function setFeeToSetter(address) external;
                function setMigrator(address) external;
            }
            
            // File: contracts/uniswapv2/libraries/SafeMath.sol
            
            pragma solidity =0.6.12;
            
            // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
            
            library SafeMathUniswap {
                function add(uint x, uint y) internal pure returns (uint z) {
                    require((z = x + y) >= x, 'ds-math-add-overflow');
                }
            
                function sub(uint x, uint y) internal pure returns (uint z) {
                    require((z = x - y) <= x, 'ds-math-sub-underflow');
                }
            
                function mul(uint x, uint y) internal pure returns (uint z) {
                    require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
                }
            }
            
            // File: contracts/uniswapv2/UniswapV2ERC20.sol
            
            pragma solidity =0.6.12;
            
            
            contract UniswapV2ERC20 {
                using SafeMathUniswap for uint;
            
                string public constant name = 'SushiSwap LP Token';
                string public constant symbol = 'SLP';
                uint8 public constant decimals = 18;
                uint  public totalSupply;
                mapping(address => uint) public balanceOf;
                mapping(address => mapping(address => uint)) public allowance;
            
                bytes32 public DOMAIN_SEPARATOR;
                // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
                bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
                mapping(address => uint) public nonces;
            
                event Approval(address indexed owner, address indexed spender, uint value);
                event Transfer(address indexed from, address indexed to, uint value);
            
                constructor() public {
                    uint chainId;
                    assembly {
                        chainId := chainid()
                    }
                    DOMAIN_SEPARATOR = keccak256(
                        abi.encode(
                            keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
                            keccak256(bytes(name)),
                            keccak256(bytes('1')),
                            chainId,
                            address(this)
                        )
                    );
                }
            
                function _mint(address to, uint value) internal {
                    totalSupply = totalSupply.add(value);
                    balanceOf[to] = balanceOf[to].add(value);
                    emit Transfer(address(0), to, value);
                }
            
                function _burn(address from, uint value) internal {
                    balanceOf[from] = balanceOf[from].sub(value);
                    totalSupply = totalSupply.sub(value);
                    emit Transfer(from, address(0), value);
                }
            
                function _approve(address owner, address spender, uint value) private {
                    allowance[owner][spender] = value;
                    emit Approval(owner, spender, value);
                }
            
                function _transfer(address from, address to, uint value) private {
                    balanceOf[from] = balanceOf[from].sub(value);
                    balanceOf[to] = balanceOf[to].add(value);
                    emit Transfer(from, to, value);
                }
            
                function approve(address spender, uint value) external returns (bool) {
                    _approve(msg.sender, spender, value);
                    return true;
                }
            
                function transfer(address to, uint value) external returns (bool) {
                    _transfer(msg.sender, to, value);
                    return true;
                }
            
                function transferFrom(address from, address to, uint value) external returns (bool) {
                    if (allowance[from][msg.sender] != uint(-1)) {
                        allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
                    }
                    _transfer(from, to, value);
                    return true;
                }
            
                function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
                    require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
                    bytes32 digest = keccak256(
                        abi.encodePacked(
                            '\x19\x01',
                            DOMAIN_SEPARATOR,
                            keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
                        )
                    );
                    address recoveredAddress = ecrecover(digest, v, r, s);
                    require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
                    _approve(owner, spender, value);
                }
            }
            
            // File: contracts/uniswapv2/libraries/Math.sol
            
            pragma solidity =0.6.12;
            
            // a library for performing various math operations
            
            library Math {
                function min(uint x, uint y) internal pure returns (uint z) {
                    z = x < y ? x : y;
                }
            
                // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
                function sqrt(uint y) internal pure returns (uint z) {
                    if (y > 3) {
                        z = y;
                        uint x = y / 2 + 1;
                        while (x < z) {
                            z = x;
                            x = (y / x + x) / 2;
                        }
                    } else if (y != 0) {
                        z = 1;
                    }
                }
            }
            
            // File: contracts/uniswapv2/libraries/UQ112x112.sol
            
            pragma solidity =0.6.12;
            
            // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
            
            // range: [0, 2**112 - 1]
            // resolution: 1 / 2**112
            
            library UQ112x112 {
                uint224 constant Q112 = 2**112;
            
                // encode a uint112 as a UQ112x112
                function encode(uint112 y) internal pure returns (uint224 z) {
                    z = uint224(y) * Q112; // never overflows
                }
            
                // divide a UQ112x112 by a uint112, returning a UQ112x112
                function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
                    z = x / uint224(y);
                }
            }
            
            // File: contracts/uniswapv2/interfaces/IERC20.sol
            
            pragma solidity >=0.5.0;
            
            interface IERC20Uniswap {
                event Approval(address indexed owner, address indexed spender, uint value);
                event Transfer(address indexed from, address indexed to, uint value);
            
                function name() external view returns (string memory);
                function symbol() external view returns (string memory);
                function decimals() external view returns (uint8);
                function totalSupply() external view returns (uint);
                function balanceOf(address owner) external view returns (uint);
                function allowance(address owner, address spender) external view returns (uint);
            
                function approve(address spender, uint value) external returns (bool);
                function transfer(address to, uint value) external returns (bool);
                function transferFrom(address from, address to, uint value) external returns (bool);
            }
            
            // File: contracts/uniswapv2/interfaces/IUniswapV2Callee.sol
            
            pragma solidity >=0.5.0;
            
            interface IUniswapV2Callee {
                function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
            }
            
            // File: contracts/uniswapv2/UniswapV2Pair.sol
            
            pragma solidity =0.6.12;
            
            
            
            
            
            
            
            
            interface IMigrator {
                // Return the desired amount of liquidity token that the migrator wants.
                function desiredLiquidity() external view returns (uint256);
            }
            
            contract UniswapV2Pair is UniswapV2ERC20 {
                using SafeMathUniswap  for uint;
                using UQ112x112 for uint224;
            
                uint public constant MINIMUM_LIQUIDITY = 10**3;
                bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
            
                address public factory;
                address public token0;
                address public token1;
            
                uint112 private reserve0;           // uses single storage slot, accessible via getReserves
                uint112 private reserve1;           // uses single storage slot, accessible via getReserves
                uint32  private blockTimestampLast; // uses single storage slot, accessible via getReserves
            
                uint public price0CumulativeLast;
                uint public price1CumulativeLast;
                uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
            
                uint private unlocked = 1;
                modifier lock() {
                    require(unlocked == 1, 'UniswapV2: LOCKED');
                    unlocked = 0;
                    _;
                    unlocked = 1;
                }
            
                function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
                    _reserve0 = reserve0;
                    _reserve1 = reserve1;
                    _blockTimestampLast = blockTimestampLast;
                }
            
                function _safeTransfer(address token, address to, uint value) private {
                    (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
                    require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
                }
            
                event Mint(address indexed sender, uint amount0, uint amount1);
                event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
                event Swap(
                    address indexed sender,
                    uint amount0In,
                    uint amount1In,
                    uint amount0Out,
                    uint amount1Out,
                    address indexed to
                );
                event Sync(uint112 reserve0, uint112 reserve1);
            
                constructor() public {
                    factory = msg.sender;
                }
            
                // called once by the factory at time of deployment
                function initialize(address _token0, address _token1) external {
                    require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
                    token0 = _token0;
                    token1 = _token1;
                }
            
                // update reserves and, on the first call per block, price accumulators
                function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
                    require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
                    uint32 blockTimestamp = uint32(block.timestamp % 2**32);
                    uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
                    if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
                        // * never overflows, and + overflow is desired
                        price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
                        price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
                    }
                    reserve0 = uint112(balance0);
                    reserve1 = uint112(balance1);
                    blockTimestampLast = blockTimestamp;
                    emit Sync(reserve0, reserve1);
                }
            
                // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
                function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
                    address feeTo = IUniswapV2Factory(factory).feeTo();
                    feeOn = feeTo != address(0);
                    uint _kLast = kLast; // gas savings
                    if (feeOn) {
                        if (_kLast != 0) {
                            uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
                            uint rootKLast = Math.sqrt(_kLast);
                            if (rootK > rootKLast) {
                                uint numerator = totalSupply.mul(rootK.sub(rootKLast));
                                uint denominator = rootK.mul(5).add(rootKLast);
                                uint liquidity = numerator / denominator;
                                if (liquidity > 0) _mint(feeTo, liquidity);
                            }
                        }
                    } else if (_kLast != 0) {
                        kLast = 0;
                    }
                }
            
                // this low-level function should be called from a contract which performs important safety checks
                function mint(address to) external lock returns (uint liquidity) {
                    (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                    uint balance0 = IERC20Uniswap(token0).balanceOf(address(this));
                    uint balance1 = IERC20Uniswap(token1).balanceOf(address(this));
                    uint amount0 = balance0.sub(_reserve0);
                    uint amount1 = balance1.sub(_reserve1);
            
                    bool feeOn = _mintFee(_reserve0, _reserve1);
                    uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                    if (_totalSupply == 0) {
                        address migrator = IUniswapV2Factory(factory).migrator();
                        if (msg.sender == migrator) {
                            liquidity = IMigrator(migrator).desiredLiquidity();
                            require(liquidity > 0 && liquidity != uint256(-1), "Bad desired liquidity");
                        } else {
                            require(migrator == address(0), "Must not have migrator");
                            liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
                            _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
                        }
                    } else {
                        liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
                    }
                    require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
                    _mint(to, liquidity);
            
                    _update(balance0, balance1, _reserve0, _reserve1);
                    if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
                    emit Mint(msg.sender, amount0, amount1);
                }
            
                // this low-level function should be called from a contract which performs important safety checks
                function burn(address to) external lock returns (uint amount0, uint amount1) {
                    (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                    address _token0 = token0;                                // gas savings
                    address _token1 = token1;                                // gas savings
                    uint balance0 = IERC20Uniswap(_token0).balanceOf(address(this));
                    uint balance1 = IERC20Uniswap(_token1).balanceOf(address(this));
                    uint liquidity = balanceOf[address(this)];
            
                    bool feeOn = _mintFee(_reserve0, _reserve1);
                    uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                    amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
                    amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
                    require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
                    _burn(address(this), liquidity);
                    _safeTransfer(_token0, to, amount0);
                    _safeTransfer(_token1, to, amount1);
                    balance0 = IERC20Uniswap(_token0).balanceOf(address(this));
                    balance1 = IERC20Uniswap(_token1).balanceOf(address(this));
            
                    _update(balance0, balance1, _reserve0, _reserve1);
                    if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
                    emit Burn(msg.sender, amount0, amount1, to);
                }
            
                // this low-level function should be called from a contract which performs important safety checks
                function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
                    require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
                    (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
                    require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
            
                    uint balance0;
                    uint balance1;
                    { // scope for _token{0,1}, avoids stack too deep errors
                    address _token0 = token0;
                    address _token1 = token1;
                    require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
                    if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
                    if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
                    if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
                    balance0 = IERC20Uniswap(_token0).balanceOf(address(this));
                    balance1 = IERC20Uniswap(_token1).balanceOf(address(this));
                    }
                    uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
                    uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
                    require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
                    { // scope for reserve{0,1}Adjusted, avoids stack too deep errors
                    uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
                    uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
                    require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
                    }
            
                    _update(balance0, balance1, _reserve0, _reserve1);
                    emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
                }
            
                // force balances to match reserves
                function skim(address to) external lock {
                    address _token0 = token0; // gas savings
                    address _token1 = token1; // gas savings
                    _safeTransfer(_token0, to, IERC20Uniswap(_token0).balanceOf(address(this)).sub(reserve0));
                    _safeTransfer(_token1, to, IERC20Uniswap(_token1).balanceOf(address(this)).sub(reserve1));
                }
            
                // force reserves to match balances
                function sync() external lock {
                    _update(IERC20Uniswap(token0).balanceOf(address(this)), IERC20Uniswap(token1).balanceOf(address(this)), reserve0, reserve1);
                }
            }

            File 6 of 6: swETH
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
            pragma solidity ^0.8.0;
            import "./IAccessControlUpgradeable.sol";
            /**
             * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
             */
            interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
                /**
                 * @dev Returns one of the accounts that have `role`. `index` must be a
                 * value between 0 and {getRoleMemberCount}, non-inclusive.
                 *
                 * Role bearers are not sorted in any particular way, and their ordering may
                 * change at any point.
                 *
                 * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
                 * you perform all queries on the same block. See the following
                 * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
                 * for more information.
                 */
                function getRoleMember(bytes32 role, uint256 index) external view returns (address);
                /**
                 * @dev Returns the number of accounts that have `role`. Can be used
                 * together with {getRoleMember} to enumerate all bearers of a role.
                 */
                function getRoleMemberCount(bytes32 role) external view returns (uint256);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev External interface of AccessControl declared to support ERC165 detection.
             */
            interface IAccessControlUpgradeable {
                /**
                 * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
                 *
                 * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
                 * {RoleAdminChanged} not being emitted signaling this.
                 *
                 * _Available since v3.1._
                 */
                event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
                /**
                 * @dev Emitted when `account` is granted `role`.
                 *
                 * `sender` is the account that originated the contract call, an admin role
                 * bearer except when using {AccessControl-_setupRole}.
                 */
                event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
                /**
                 * @dev Emitted when `account` is revoked `role`.
                 *
                 * `sender` is the account that originated the contract call:
                 *   - if using `revokeRole`, it is the admin role bearer
                 *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
                 */
                event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
                /**
                 * @dev Returns `true` if `account` has been granted `role`.
                 */
                function hasRole(bytes32 role, address account) external view returns (bool);
                /**
                 * @dev Returns the admin role that controls `role`. See {grantRole} and
                 * {revokeRole}.
                 *
                 * To change a role's admin, use {AccessControl-_setRoleAdmin}.
                 */
                function getRoleAdmin(bytes32 role) external view returns (bytes32);
                /**
                 * @dev Grants `role` to `account`.
                 *
                 * If `account` had not been already granted `role`, emits a {RoleGranted}
                 * event.
                 *
                 * Requirements:
                 *
                 * - the caller must have ``role``'s admin role.
                 */
                function grantRole(bytes32 role, address account) external;
                /**
                 * @dev Revokes `role` from `account`.
                 *
                 * If `account` had been granted `role`, emits a {RoleRevoked} event.
                 *
                 * Requirements:
                 *
                 * - the caller must have ``role``'s admin role.
                 */
                function revokeRole(bytes32 role, address account) external;
                /**
                 * @dev Revokes `role` from the calling account.
                 *
                 * Roles are often managed via {grantRole} and {revokeRole}: this function's
                 * purpose is to provide a mechanism for accounts to lose their privileges
                 * if they are compromised (such as when a trusted device is misplaced).
                 *
                 * If the calling account had been granted `role`, emits a {RoleRevoked}
                 * event.
                 *
                 * Requirements:
                 *
                 * - the caller must be `account`.
                 */
                function renounceRole(bytes32 role, address account) external;
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol)
            pragma solidity ^0.8.2;
            import "../../utils/AddressUpgradeable.sol";
            /**
             * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
             * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
             * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
             * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
             *
             * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
             * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
             * case an upgrade adds a module that needs to be initialized.
             *
             * For example:
             *
             * [.hljs-theme-light.nopadding]
             * ```
             * contract MyToken is ERC20Upgradeable {
             *     function initialize() initializer public {
             *         __ERC20_init("MyToken", "MTK");
             *     }
             * }
             * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
             *     function initializeV2() reinitializer(2) public {
             *         __ERC20Permit_init("MyToken");
             *     }
             * }
             * ```
             *
             * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
             * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
             *
             * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
             * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
             *
             * [CAUTION]
             * ====
             * Avoid leaving a contract uninitialized.
             *
             * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
             * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
             * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
             *
             * [.hljs-theme-light.nopadding]
             * ```
             * /// @custom:oz-upgrades-unsafe-allow constructor
             * constructor() {
             *     _disableInitializers();
             * }
             * ```
             * ====
             */
            abstract contract Initializable {
                /**
                 * @dev Indicates that the contract has been initialized.
                 * @custom:oz-retyped-from bool
                 */
                uint8 private _initialized;
                /**
                 * @dev Indicates that the contract is in the process of being initialized.
                 */
                bool private _initializing;
                /**
                 * @dev Triggered when the contract has been initialized or reinitialized.
                 */
                event Initialized(uint8 version);
                /**
                 * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
                 * `onlyInitializing` functions can be used to initialize parent contracts.
                 *
                 * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
                 * constructor.
                 *
                 * Emits an {Initialized} event.
                 */
                modifier initializer() {
                    bool isTopLevelCall = !_initializing;
                    require(
                        (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
                        "Initializable: contract is already initialized"
                    );
                    _initialized = 1;
                    if (isTopLevelCall) {
                        _initializing = true;
                    }
                    _;
                    if (isTopLevelCall) {
                        _initializing = false;
                        emit Initialized(1);
                    }
                }
                /**
                 * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
                 * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
                 * used to initialize parent contracts.
                 *
                 * A reinitializer may be used after the original initialization step. This is essential to configure modules that
                 * are added through upgrades and that require initialization.
                 *
                 * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
                 * cannot be nested. If one is invoked in the context of another, execution will revert.
                 *
                 * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
                 * a contract, executing them in the right order is up to the developer or operator.
                 *
                 * WARNING: setting the version to 255 will prevent any future reinitialization.
                 *
                 * Emits an {Initialized} event.
                 */
                modifier reinitializer(uint8 version) {
                    require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
                    _initialized = version;
                    _initializing = true;
                    _;
                    _initializing = false;
                    emit Initialized(version);
                }
                /**
                 * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
                 * {initializer} and {reinitializer} modifiers, directly or indirectly.
                 */
                modifier onlyInitializing() {
                    require(_initializing, "Initializable: contract is not initializing");
                    _;
                }
                /**
                 * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
                 * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
                 * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
                 * through proxies.
                 *
                 * Emits an {Initialized} event the first time it is successfully executed.
                 */
                function _disableInitializers() internal virtual {
                    require(!_initializing, "Initializable: contract is initializing");
                    if (_initialized < type(uint8).max) {
                        _initialized = type(uint8).max;
                        emit Initialized(type(uint8).max);
                    }
                }
                /**
                 * @dev Returns the highest version that has been initialized. See {reinitializer}.
                 */
                function _getInitializedVersion() internal view returns (uint8) {
                    return _initialized;
                }
                /**
                 * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
                 */
                function _isInitializing() internal view returns (bool) {
                    return _initializing;
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol)
            pragma solidity ^0.8.0;
            import "./IERC20Upgradeable.sol";
            import "./extensions/IERC20MetadataUpgradeable.sol";
            import "../../utils/ContextUpgradeable.sol";
            import "../../proxy/utils/Initializable.sol";
            /**
             * @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.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
             * to implement supply mechanisms].
             *
             * We have followed general OpenZeppelin Contracts guidelines: functions revert
             * instead 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 onlyInitializing {
                    __ERC20_init_unchained(name_, symbol_);
                }
                function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
                    _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:
                 *
                 * - `to` cannot be the zero address.
                 * - the caller must have a balance of at least `amount`.
                 */
                function transfer(address to, uint256 amount) public virtual override returns (bool) {
                    address owner = _msgSender();
                    _transfer(owner, to, 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}.
                 *
                 * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
                 * `transferFrom`. This is semantically equivalent to an infinite approval.
                 *
                 * Requirements:
                 *
                 * - `spender` cannot be the zero address.
                 */
                function approve(address spender, uint256 amount) public virtual override returns (bool) {
                    address owner = _msgSender();
                    _approve(owner, 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}.
                 *
                 * NOTE: Does not update the allowance if the current allowance
                 * is the maximum `uint256`.
                 *
                 * Requirements:
                 *
                 * - `from` and `to` cannot be the zero address.
                 * - `from` must have a balance of at least `amount`.
                 * - the caller must have allowance for ``from``'s tokens of at least
                 * `amount`.
                 */
                function transferFrom(
                    address from,
                    address to,
                    uint256 amount
                ) public virtual override returns (bool) {
                    address spender = _msgSender();
                    _spendAllowance(from, spender, amount);
                    _transfer(from, to, 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) {
                    address owner = _msgSender();
                    _approve(owner, spender, allowance(owner, 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) {
                    address owner = _msgSender();
                    uint256 currentAllowance = allowance(owner, spender);
                    require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
                    unchecked {
                        _approve(owner, spender, currentAllowance - subtractedValue);
                    }
                    return true;
                }
                /**
                 * @dev Moves `amount` of tokens from `from` to `to`.
                 *
                 * 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:
                 *
                 * - `from` cannot be the zero address.
                 * - `to` cannot be the zero address.
                 * - `from` must have a balance of at least `amount`.
                 */
                function _transfer(
                    address from,
                    address to,
                    uint256 amount
                ) internal virtual {
                    require(from != address(0), "ERC20: transfer from the zero address");
                    require(to != address(0), "ERC20: transfer to the zero address");
                    _beforeTokenTransfer(from, to, amount);
                    uint256 fromBalance = _balances[from];
                    require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
                    unchecked {
                        _balances[from] = fromBalance - amount;
                        // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
                        // decrementing then incrementing.
                        _balances[to] += amount;
                    }
                    emit Transfer(from, to, amount);
                    _afterTokenTransfer(from, to, 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;
                    unchecked {
                        // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
                        _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;
                        // Overflow not possible: amount <= accountBalance <= totalSupply.
                        _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 Updates `owner` s allowance for `spender` based on spent `amount`.
                 *
                 * Does not update the allowance amount in case of infinite allowance.
                 * Revert if not enough allowance is available.
                 *
                 * Might emit an {Approval} event.
                 */
                function _spendAllowance(
                    address owner,
                    address spender,
                    uint256 amount
                ) internal virtual {
                    uint256 currentAllowance = allowance(owner, spender);
                    if (currentAllowance != type(uint256).max) {
                        require(currentAllowance >= amount, "ERC20: insufficient allowance");
                        unchecked {
                            _approve(owner, spender, currentAllowance - 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 {}
                /**
                 * @dev This empty reserved space is put in place to allow future versions to add new
                 * variables without shifting down storage in the inheritance chain.
                 * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
                 */
                uint256[45] private __gap;
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
            pragma solidity ^0.8.0;
            import "../IERC20Upgradeable.sol";
            /**
             * @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);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Interface of the ERC20 standard as defined in the EIP.
             */
            interface IERC20Upgradeable {
                /**
                 * @dev Emitted when `value` tokens are moved from one account (`from`) to
                 * another (`to`).
                 *
                 * Note that `value` may be zero.
                 */
                event Transfer(address indexed from, address indexed to, uint256 value);
                /**
                 * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                 * a call to {approve}. `value` is the new allowance.
                 */
                event Approval(address indexed owner, address indexed spender, uint256 value);
                /**
                 * @dev Returns the 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 `to`.
                 *
                 * Returns a boolean value indicating whether the operation succeeded.
                 *
                 * Emits a {Transfer} event.
                 */
                function transfer(address to, 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 `from` to `to` 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 from,
                    address to,
                    uint256 amount
                ) external returns (bool);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
            pragma solidity ^0.8.1;
            /**
             * @dev Collection of functions related to the address type
             */
            library AddressUpgradeable {
                /**
                 * @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
                 * ====
                 *
                 * [IMPORTANT]
                 * ====
                 * You shouldn't rely on `isContract` to protect against flash loan attacks!
                 *
                 * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
                 * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
                 * constructor.
                 * ====
                 */
                function isContract(address account) internal view returns (bool) {
                    // This method relies on extcodesize/address.code.length, which returns 0
                    // for contracts in construction, since the code is only stored at the end
                    // of the constructor execution.
                    return account.code.length > 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");
                    (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 functionCallWithValue(target, data, 0, "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");
                    (bool success, bytes memory returndata) = target.call{value: value}(data);
                    return verifyCallResultFromTarget(target, 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) {
                    (bool success, bytes memory returndata) = target.staticcall(data);
                    return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                }
                /**
                 * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
                 * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
                 *
                 * _Available since v4.8._
                 */
                function verifyCallResultFromTarget(
                    address target,
                    bool success,
                    bytes memory returndata,
                    string memory errorMessage
                ) internal view returns (bytes memory) {
                    if (success) {
                        if (returndata.length == 0) {
                            // only check isContract if the call was successful and the return data is empty
                            // otherwise we already know that it was a contract
                            require(isContract(target), "Address: call to non-contract");
                        }
                        return returndata;
                    } else {
                        _revert(returndata, errorMessage);
                    }
                }
                /**
                 * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
                 * revert reason or using the provided one.
                 *
                 * _Available since v4.3._
                 */
                function verifyCallResult(
                    bool success,
                    bytes memory returndata,
                    string memory errorMessage
                ) internal pure returns (bytes memory) {
                    if (success) {
                        return returndata;
                    } else {
                        _revert(returndata, errorMessage);
                    }
                }
                function _revert(bytes memory returndata, string memory errorMessage) private pure {
                    // Look for revert reason and bubble it up if present
                    if (returndata.length > 0) {
                        // The easiest way to bubble the revert reason is using memory via assembly
                        /// @solidity memory-safe-assembly
                        assembly {
                            let returndata_size := mload(returndata)
                            revert(add(32, returndata), returndata_size)
                        }
                    } else {
                        revert(errorMessage);
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
            pragma solidity ^0.8.0;
            import "../proxy/utils/Initializable.sol";
            /**
             * @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 onlyInitializing {
                }
                function __Context_init_unchained() internal onlyInitializing {
                }
                function _msgSender() internal view virtual returns (address) {
                    return msg.sender;
                }
                function _msgData() internal view virtual returns (bytes calldata) {
                    return msg.data;
                }
                /**
                 * @dev This empty reserved space is put in place to allow future versions to add new
                 * variables without shifting down storage in the inheritance chain.
                 * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
                 */
                uint256[50] private __gap;
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.8.0) (utils/structs/EnumerableSet.sol)
            // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
            pragma solidity ^0.8.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.
             *
             * [WARNING]
             * ====
             * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
             * unusable.
             * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
             *
             * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
             * array of EnumerableSet.
             * ====
             */
            library EnumerableSetUpgradeable {
                // 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;
                        if (lastIndex != toDeleteIndex) {
                            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] = valueIndex; // Replace lastValue's index to valueIndex
                        }
                        // 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) {
                    return set._values[index];
                }
                /**
                 * @dev Return the entire set in an array
                 *
                 * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                 * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                 * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                 * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                 */
                function _values(Set storage set) private view returns (bytes32[] memory) {
                    return set._values;
                }
                // Bytes32Set
                struct Bytes32Set {
                    Set _inner;
                }
                /**
                 * @dev Add a value to a set. O(1).
                 *
                 * Returns true if the value was added to the set, that is if it was not
                 * already present.
                 */
                function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                    return _add(set._inner, value);
                }
                /**
                 * @dev Removes a value from a set. O(1).
                 *
                 * Returns true if the value was removed from the set, that is if it was
                 * present.
                 */
                function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
                    return _remove(set._inner, value);
                }
                /**
                 * @dev Returns true if the value is in the set. O(1).
                 */
                function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
                    return _contains(set._inner, value);
                }
                /**
                 * @dev Returns the number of values in the set. O(1).
                 */
                function length(Bytes32Set storage set) internal view returns (uint256) {
                    return _length(set._inner);
                }
                /**
                 * @dev Returns the value stored at position `index` in the set. O(1).
                 *
                 * Note that there are no guarantees on the ordering of values inside the
                 * array, and it may change when more values are added or removed.
                 *
                 * Requirements:
                 *
                 * - `index` must be strictly less than {length}.
                 */
                function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
                    return _at(set._inner, index);
                }
                /**
                 * @dev Return the entire set in an array
                 *
                 * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                 * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                 * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                 * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                 */
                function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
                    bytes32[] memory store = _values(set._inner);
                    bytes32[] memory result;
                    /// @solidity memory-safe-assembly
                    assembly {
                        result := store
                    }
                    return result;
                }
                // AddressSet
                struct AddressSet {
                    Set _inner;
                }
                /**
                 * @dev Add a value to a set. O(1).
                 *
                 * Returns true if the value was added to the set, that is if it was not
                 * already present.
                 */
                function add(AddressSet storage set, address value) internal returns (bool) {
                    return _add(set._inner, bytes32(uint256(uint160(value))));
                }
                /**
                 * @dev Removes a value from a set. O(1).
                 *
                 * Returns true if the value was removed from the set, that is if it was
                 * present.
                 */
                function remove(AddressSet storage set, address value) internal returns (bool) {
                    return _remove(set._inner, bytes32(uint256(uint160(value))));
                }
                /**
                 * @dev Returns true if the value is in the set. O(1).
                 */
                function contains(AddressSet storage set, address value) internal view returns (bool) {
                    return _contains(set._inner, bytes32(uint256(uint160(value))));
                }
                /**
                 * @dev Returns the number of values in the set. O(1).
                 */
                function length(AddressSet storage set) internal view returns (uint256) {
                    return _length(set._inner);
                }
                /**
                 * @dev Returns the value stored at position `index` in the set. O(1).
                 *
                 * Note that there are no guarantees on the ordering of values inside the
                 * array, and it may change when more values are added or removed.
                 *
                 * Requirements:
                 *
                 * - `index` must be strictly less than {length}.
                 */
                function at(AddressSet storage set, uint256 index) internal view returns (address) {
                    return address(uint160(uint256(_at(set._inner, index))));
                }
                /**
                 * @dev Return the entire set in an array
                 *
                 * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                 * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                 * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                 * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                 */
                function values(AddressSet storage set) internal view returns (address[] memory) {
                    bytes32[] memory store = _values(set._inner);
                    address[] memory result;
                    /// @solidity memory-safe-assembly
                    assembly {
                        result := store
                    }
                    return result;
                }
                // UintSet
                struct UintSet {
                    Set _inner;
                }
                /**
                 * @dev Add a value to a set. O(1).
                 *
                 * Returns true if the value was added to the set, that is if it was not
                 * already present.
                 */
                function add(UintSet storage set, uint256 value) internal returns (bool) {
                    return _add(set._inner, bytes32(value));
                }
                /**
                 * @dev Removes a value from a set. O(1).
                 *
                 * Returns true if the value was removed from the set, that is if it was
                 * present.
                 */
                function remove(UintSet storage set, uint256 value) internal returns (bool) {
                    return _remove(set._inner, bytes32(value));
                }
                /**
                 * @dev Returns true if the value is in the set. O(1).
                 */
                function contains(UintSet storage set, uint256 value) internal view returns (bool) {
                    return _contains(set._inner, bytes32(value));
                }
                /**
                 * @dev Returns the number of values in the set. O(1).
                 */
                function length(UintSet storage set) internal view returns (uint256) {
                    return _length(set._inner);
                }
                /**
                 * @dev Returns the value stored at position `index` in the set. O(1).
                 *
                 * Note that there are no guarantees on the ordering of values inside the
                 * array, and it may change when more values are added or removed.
                 *
                 * Requirements:
                 *
                 * - `index` must be strictly less than {length}.
                 */
                function at(UintSet storage set, uint256 index) internal view returns (uint256) {
                    return uint256(_at(set._inner, index));
                }
                /**
                 * @dev Return the entire set in an array
                 *
                 * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
                 * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
                 * this function has an unbounded cost, and using it as part of a state-changing function may render the function
                 * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
                 */
                function values(UintSet storage set) internal view returns (uint256[] memory) {
                    bytes32[] memory store = _values(set._inner);
                    uint256[] memory result;
                    /// @solidity memory-safe-assembly
                    assembly {
                        result := store
                    }
                    return result;
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
            pragma solidity ^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: MIT
            // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
            pragma solidity ^0.8.0;
            /**
             * @dev Interface of the ERC20 standard as defined in the EIP.
             */
            interface IERC20 {
                /**
                 * @dev Emitted when `value` tokens are moved from one account (`from`) to
                 * another (`to`).
                 *
                 * Note that `value` may be zero.
                 */
                event Transfer(address indexed from, address indexed to, uint256 value);
                /**
                 * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                 * a call to {approve}. `value` is the new allowance.
                 */
                event Approval(address indexed owner, address indexed spender, uint256 value);
                /**
                 * @dev Returns the 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 `to`.
                 *
                 * Returns a boolean value indicating whether the operation succeeded.
                 *
                 * Emits a {Transfer} event.
                 */
                function transfer(address to, 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 `from` to `to` 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 from,
                    address to,
                    uint256 amount
                ) external returns (bool);
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)
            pragma solidity ^0.8.0;
            import "../IERC20.sol";
            import "../extensions/draft-IERC20Permit.sol";
            import "../../../utils/Address.sol";
            /**
             * @title SafeERC20
             * @dev Wrappers around ERC20 operations that throw on failure (when the token
             * contract returns false). Tokens that return no value (and instead revert or
             * throw on failure) are also supported, non-reverting calls are assumed to be
             * successful.
             * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
             * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
             */
            library SafeERC20 {
                using Address for address;
                function safeTransfer(
                    IERC20 token,
                    address to,
                    uint256 value
                ) internal {
                    _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                }
                function safeTransferFrom(
                    IERC20 token,
                    address from,
                    address to,
                    uint256 value
                ) internal {
                    _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                }
                /**
                 * @dev Deprecated. This function has issues similar to the ones found in
                 * {IERC20-approve}, and its usage is discouraged.
                 *
                 * Whenever possible, use {safeIncreaseAllowance} and
                 * {safeDecreaseAllowance} instead.
                 */
                function safeApprove(
                    IERC20 token,
                    address spender,
                    uint256 value
                ) internal {
                    // safeApprove should only be called when setting an initial allowance,
                    // or when resetting it to zero. To increase and decrease it, use
                    // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                    require(
                        (value == 0) || (token.allowance(address(this), spender) == 0),
                        "SafeERC20: approve from non-zero to non-zero allowance"
                    );
                    _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
                }
                function safeIncreaseAllowance(
                    IERC20 token,
                    address spender,
                    uint256 value
                ) internal {
                    uint256 newAllowance = token.allowance(address(this), spender) + value;
                    _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                }
                function safeDecreaseAllowance(
                    IERC20 token,
                    address spender,
                    uint256 value
                ) internal {
                    unchecked {
                        uint256 oldAllowance = token.allowance(address(this), spender);
                        require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                        uint256 newAllowance = oldAllowance - value;
                        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                    }
                }
                function safePermit(
                    IERC20Permit token,
                    address owner,
                    address spender,
                    uint256 value,
                    uint256 deadline,
                    uint8 v,
                    bytes32 r,
                    bytes32 s
                ) internal {
                    uint256 nonceBefore = token.nonces(owner);
                    token.permit(owner, spender, value, deadline, v, r, s);
                    uint256 nonceAfter = token.nonces(owner);
                    require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
                }
                /**
                 * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                 * on the return value: the return value is optional (but if data is returned, it must not be false).
                 * @param token The token targeted by the call.
                 * @param data The call data (encoded using abi.encode or one of its variants).
                 */
                function _callOptionalReturn(IERC20 token, bytes memory data) private {
                    // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                    // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
                    // the target address contains contract code and also asserts for success in the low-level call.
                    bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                    if (returndata.length > 0) {
                        // Return data is optional
                        require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
            pragma solidity ^0.8.1;
            /**
             * @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
                 * ====
                 *
                 * [IMPORTANT]
                 * ====
                 * You shouldn't rely on `isContract` to protect against flash loan attacks!
                 *
                 * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
                 * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
                 * constructor.
                 * ====
                 */
                function isContract(address account) internal view returns (bool) {
                    // This method relies on extcodesize/address.code.length, which returns 0
                    // for contracts in construction, since the code is only stored at the end
                    // of the constructor execution.
                    return account.code.length > 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");
                    (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 functionCallWithValue(target, data, 0, "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");
                    (bool success, bytes memory returndata) = target.call{value: value}(data);
                    return verifyCallResultFromTarget(target, 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) {
                    (bool success, bytes memory returndata) = target.staticcall(data);
                    return verifyCallResultFromTarget(target, 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) {
                    (bool success, bytes memory returndata) = target.delegatecall(data);
                    return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                }
                /**
                 * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
                 * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
                 *
                 * _Available since v4.8._
                 */
                function verifyCallResultFromTarget(
                    address target,
                    bool success,
                    bytes memory returndata,
                    string memory errorMessage
                ) internal view returns (bytes memory) {
                    if (success) {
                        if (returndata.length == 0) {
                            // only check isContract if the call was successful and the return data is empty
                            // otherwise we already know that it was a contract
                            require(isContract(target), "Address: call to non-contract");
                        }
                        return returndata;
                    } else {
                        _revert(returndata, errorMessage);
                    }
                }
                /**
                 * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
                 * revert reason or using the provided one.
                 *
                 * _Available since v4.3._
                 */
                function verifyCallResult(
                    bool success,
                    bytes memory returndata,
                    string memory errorMessage
                ) internal pure returns (bytes memory) {
                    if (success) {
                        return returndata;
                    } else {
                        _revert(returndata, errorMessage);
                    }
                }
                function _revert(bytes memory returndata, string memory errorMessage) private pure {
                    // Look for revert reason and bubble it up if present
                    if (returndata.length > 0) {
                        // The easiest way to bubble the revert reason is using memory via assembly
                        /// @solidity memory-safe-assembly
                        assembly {
                            let returndata_size := mload(returndata)
                            revert(add(32, returndata), returndata_size)
                        }
                    } else {
                        revert(errorMessage);
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            /// Common mathematical functions used in both SD59x18 and UD60x18. Note that these global functions do not
            /// always operate with SD59x18 and UD60x18 numbers.
            /*//////////////////////////////////////////////////////////////////////////
                                            CUSTOM ERRORS
            //////////////////////////////////////////////////////////////////////////*/
            /// @notice Emitted when the ending result in the fixed-point version of `mulDiv` would overflow uint256.
            error PRBMath_MulDiv18_Overflow(uint256 x, uint256 y);
            /// @notice Emitted when the ending result in `mulDiv` would overflow uint256.
            error PRBMath_MulDiv_Overflow(uint256 x, uint256 y, uint256 denominator);
            /// @notice Emitted when attempting to run `mulDiv` with one of the inputs `type(int256).min`.
            error PRBMath_MulDivSigned_InputTooSmall();
            /// @notice Emitted when the ending result in the signed version of `mulDiv` would overflow int256.
            error PRBMath_MulDivSigned_Overflow(int256 x, int256 y);
            /*//////////////////////////////////////////////////////////////////////////
                                                CONSTANTS
            //////////////////////////////////////////////////////////////////////////*/
            /// @dev The maximum value an uint128 number can have.
            uint128 constant MAX_UINT128 = type(uint128).max;
            /// @dev The maximum value an uint40 number can have.
            uint40 constant MAX_UINT40 = type(uint40).max;
            /// @dev How many trailing decimals can be represented.
            uint256 constant UNIT = 1e18;
            /// @dev Largest power of two that is a divisor of `UNIT`.
            uint256 constant UNIT_LPOTD = 262144;
            /// @dev The `UNIT` number inverted mod 2^256.
            uint256 constant UNIT_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281;
            /*//////////////////////////////////////////////////////////////////////////
                                                FUNCTIONS
            //////////////////////////////////////////////////////////////////////////*/
            /// @notice Finds the zero-based index of the first one in the binary representation of x.
            /// @dev See the note on msb in the "Find First Set" Wikipedia article https://en.wikipedia.org/wiki/Find_first_set
            ///
            /// Each of the steps in this implementation is equivalent to this high-level code:
            ///
            /// ```solidity
            /// if (x >= 2 ** 128) {
            ///     x >>= 128;
            ///     result += 128;
            /// }
            /// ```
            ///
            /// Where 128 is swapped with each respective power of two factor. See the full high-level implementation here:
            /// https://gist.github.com/PaulRBerg/f932f8693f2733e30c4d479e8e980948
            ///
            /// A list of the Yul instructions used below:
            /// - "gt" is "greater than"
            /// - "or" is the OR bitwise operator
            /// - "shl" is "shift left"
            /// - "shr" is "shift right"
            ///
            /// @param x The uint256 number for which to find the index of the most significant bit.
            /// @return result The index of the most significant bit as an uint256.
            function msb(uint256 x) pure returns (uint256 result) {
                // 2^128
                assembly ("memory-safe") {
                    let factor := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
                    x := shr(factor, x)
                    result := or(result, factor)
                }
                // 2^64
                assembly ("memory-safe") {
                    let factor := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF))
                    x := shr(factor, x)
                    result := or(result, factor)
                }
                // 2^32
                assembly ("memory-safe") {
                    let factor := shl(5, gt(x, 0xFFFFFFFF))
                    x := shr(factor, x)
                    result := or(result, factor)
                }
                // 2^16
                assembly ("memory-safe") {
                    let factor := shl(4, gt(x, 0xFFFF))
                    x := shr(factor, x)
                    result := or(result, factor)
                }
                // 2^8
                assembly ("memory-safe") {
                    let factor := shl(3, gt(x, 0xFF))
                    x := shr(factor, x)
                    result := or(result, factor)
                }
                // 2^4
                assembly ("memory-safe") {
                    let factor := shl(2, gt(x, 0xF))
                    x := shr(factor, x)
                    result := or(result, factor)
                }
                // 2^2
                assembly ("memory-safe") {
                    let factor := shl(1, gt(x, 0x3))
                    x := shr(factor, x)
                    result := or(result, factor)
                }
                // 2^1
                // No need to shift x any more.
                assembly ("memory-safe") {
                    let factor := gt(x, 0x1)
                    result := or(result, factor)
                }
            }
            /// @notice Calculates floor(x*y÷denominator) with full precision.
            ///
            /// @dev Credits to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.
            ///
            /// Requirements:
            /// - The denominator cannot be zero.
            /// - The result must fit within uint256.
            ///
            /// Caveats:
            /// - This function does not work with fixed-point numbers.
            ///
            /// @param x The multiplicand as an uint256.
            /// @param y The multiplier as an uint256.
            /// @param denominator The divisor as an uint256.
            /// @return result The result as an uint256.
            function mulDiv(uint256 x, uint256 y, uint256 denominator) pure returns (uint256 result) {
                // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                // variables such that product = prod1 * 2^256 + prod0.
                uint256 prod0; // Least significant 256 bits of the product
                uint256 prod1; // Most significant 256 bits of the product
                assembly ("memory-safe") {
                    let mm := mulmod(x, y, not(0))
                    prod0 := mul(x, y)
                    prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                }
                // Handle non-overflow cases, 256 by 256 division.
                if (prod1 == 0) {
                    unchecked {
                        return prod0 / denominator;
                    }
                }
                // Make sure the result is less than 2^256. Also prevents denominator == 0.
                if (prod1 >= denominator) {
                    revert PRBMath_MulDiv_Overflow(x, y, denominator);
                }
                ///////////////////////////////////////////////
                // 512 by 256 division.
                ///////////////////////////////////////////////
                // Make division exact by subtracting the remainder from [prod1 prod0].
                uint256 remainder;
                assembly ("memory-safe") {
                    // Compute remainder using the mulmod Yul instruction.
                    remainder := mulmod(x, y, denominator)
                    // Subtract 256 bit number from 512 bit number.
                    prod1 := sub(prod1, gt(remainder, prod0))
                    prod0 := sub(prod0, remainder)
                }
                // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
                // See https://cs.stackexchange.com/q/138556/92363.
                unchecked {
                    // Does not overflow because the denominator cannot be zero at this stage in the function.
                    uint256 lpotdod = denominator & (~denominator + 1);
                    assembly ("memory-safe") {
                        // Divide denominator by lpotdod.
                        denominator := div(denominator, lpotdod)
                        // Divide [prod1 prod0] by lpotdod.
                        prod0 := div(prod0, lpotdod)
                        // Flip lpotdod such that it is 2^256 / lpotdod. If lpotdod is zero, then it becomes one.
                        lpotdod := add(div(sub(0, lpotdod), lpotdod), 1)
                    }
                    // Shift in bits from prod1 into prod0.
                    prod0 |= prod1 * lpotdod;
                    // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                    // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                    // four bits. That is, denominator * inv = 1 mod 2^4.
                    uint256 inverse = (3 * denominator) ^ 2;
                    // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
                    // in modular arithmetic, doubling the correct bits in each step.
                    inverse *= 2 - denominator * inverse; // inverse mod 2^8
                    inverse *= 2 - denominator * inverse; // inverse mod 2^16
                    inverse *= 2 - denominator * inverse; // inverse mod 2^32
                    inverse *= 2 - denominator * inverse; // inverse mod 2^64
                    inverse *= 2 - denominator * inverse; // inverse mod 2^128
                    inverse *= 2 - denominator * inverse; // inverse mod 2^256
                    // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                    // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                    // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                    // is no longer required.
                    result = prod0 * inverse;
                }
            }
            /// @notice Calculates floor(x*y÷1e18) with full precision.
            ///
            /// @dev Variant of `mulDiv` with constant folding, i.e. in which the denominator is always 1e18. Before returning the
            /// final result, we add 1 if `(x * y) % UNIT >= HALF_UNIT`. Without this adjustment, 6.6e-19 would be truncated to 0
            /// instead of being rounded to 1e-18. See "Listing 6" and text above it at https://accu.org/index.php/journals/1717.
            ///
            /// Requirements:
            /// - The result must fit within uint256.
            ///
            /// Caveats:
            /// - The body is purposely left uncommented; to understand how this works, see the NatSpec comments in `mulDiv`.
            /// - It is assumed that the result can never be `type(uint256).max` when x and y solve the following two equations:
            ///     1. x * y = type(uint256).max * UNIT
            ///     2. (x * y) % UNIT >= UNIT / 2
            ///
            /// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.
            /// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.
            /// @return result The result as an unsigned 60.18-decimal fixed-point number.
            function mulDiv18(uint256 x, uint256 y) pure returns (uint256 result) {
                uint256 prod0;
                uint256 prod1;
                assembly ("memory-safe") {
                    let mm := mulmod(x, y, not(0))
                    prod0 := mul(x, y)
                    prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                }
                if (prod1 >= UNIT) {
                    revert PRBMath_MulDiv18_Overflow(x, y);
                }
                uint256 remainder;
                assembly ("memory-safe") {
                    remainder := mulmod(x, y, UNIT)
                }
                if (prod1 == 0) {
                    unchecked {
                        return prod0 / UNIT;
                    }
                }
                assembly ("memory-safe") {
                    result := mul(
                        or(
                            div(sub(prod0, remainder), UNIT_LPOTD),
                            mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, UNIT_LPOTD), UNIT_LPOTD), 1))
                        ),
                        UNIT_INVERSE
                    )
                }
            }
            /// @notice Calculates floor(x*y÷denominator) with full precision.
            ///
            /// @dev An extension of `mulDiv` for signed numbers. Works by computing the signs and the absolute values separately.
            ///
            /// Requirements:
            /// - None of the inputs can be `type(int256).min`.
            /// - The result must fit within int256.
            ///
            /// @param x The multiplicand as an int256.
            /// @param y The multiplier as an int256.
            /// @param denominator The divisor as an int256.
            /// @return result The result as an int256.
            function mulDivSigned(int256 x, int256 y, int256 denominator) pure returns (int256 result) {
                if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) {
                    revert PRBMath_MulDivSigned_InputTooSmall();
                }
                // Get hold of the absolute values of x, y and the denominator.
                uint256 absX;
                uint256 absY;
                uint256 absD;
                unchecked {
                    absX = x < 0 ? uint256(-x) : uint256(x);
                    absY = y < 0 ? uint256(-y) : uint256(y);
                    absD = denominator < 0 ? uint256(-denominator) : uint256(denominator);
                }
                // Compute the absolute value of (x*y)÷denominator. The result must fit within int256.
                uint256 rAbs = mulDiv(absX, absY, absD);
                if (rAbs > uint256(type(int256).max)) {
                    revert PRBMath_MulDivSigned_Overflow(x, y);
                }
                // Get the signs of x, y and the denominator.
                uint256 sx;
                uint256 sy;
                uint256 sd;
                assembly ("memory-safe") {
                    // This works thanks to two's complement.
                    // "sgt" stands for "signed greater than" and "sub(0,1)" is max uint256.
                    sx := sgt(x, sub(0, 1))
                    sy := sgt(y, sub(0, 1))
                    sd := sgt(denominator, sub(0, 1))
                }
                // XOR over sx, sy and sd. What this does is to check whether there are 1 or 3 negative signs in the inputs.
                // If there are, the result should be negative. Otherwise, it should be positive.
                unchecked {
                    result = sx ^ sy ^ sd == 0 ? -int256(rAbs) : int256(rAbs);
                }
            }
            /// @notice Calculates the binary exponent of x using the binary fraction method.
            /// @dev Has to use 192.64-bit fixed-point numbers.
            /// See https://ethereum.stackexchange.com/a/96594/24693.
            /// @param x The exponent as an unsigned 192.64-bit fixed-point number.
            /// @return result The result as an unsigned 60.18-decimal fixed-point number.
            function prbExp2(uint256 x) pure returns (uint256 result) {
                unchecked {
                    // Start from 0.5 in the 192.64-bit fixed-point format.
                    result = 0x800000000000000000000000000000000000000000000000;
                    // Multiply the result by root(2, 2^-i) when the bit at position i is 1. None of the intermediary results overflows
                    // because the initial result is 2^191 and all magic factors are less than 2^65.
                    if (x & 0xFF00000000000000 > 0) {
                        if (x & 0x8000000000000000 > 0) {
                            result = (result * 0x16A09E667F3BCC909) >> 64;
                        }
                        if (x & 0x4000000000000000 > 0) {
                            result = (result * 0x1306FE0A31B7152DF) >> 64;
                        }
                        if (x & 0x2000000000000000 > 0) {
                            result = (result * 0x1172B83C7D517ADCE) >> 64;
                        }
                        if (x & 0x1000000000000000 > 0) {
                            result = (result * 0x10B5586CF9890F62A) >> 64;
                        }
                        if (x & 0x800000000000000 > 0) {
                            result = (result * 0x1059B0D31585743AE) >> 64;
                        }
                        if (x & 0x400000000000000 > 0) {
                            result = (result * 0x102C9A3E778060EE7) >> 64;
                        }
                        if (x & 0x200000000000000 > 0) {
                            result = (result * 0x10163DA9FB33356D8) >> 64;
                        }
                        if (x & 0x100000000000000 > 0) {
                            result = (result * 0x100B1AFA5ABCBED61) >> 64;
                        }
                    }
                    if (x & 0xFF000000000000 > 0) {
                        if (x & 0x80000000000000 > 0) {
                            result = (result * 0x10058C86DA1C09EA2) >> 64;
                        }
                        if (x & 0x40000000000000 > 0) {
                            result = (result * 0x1002C605E2E8CEC50) >> 64;
                        }
                        if (x & 0x20000000000000 > 0) {
                            result = (result * 0x100162F3904051FA1) >> 64;
                        }
                        if (x & 0x10000000000000 > 0) {
                            result = (result * 0x1000B175EFFDC76BA) >> 64;
                        }
                        if (x & 0x8000000000000 > 0) {
                            result = (result * 0x100058BA01FB9F96D) >> 64;
                        }
                        if (x & 0x4000000000000 > 0) {
                            result = (result * 0x10002C5CC37DA9492) >> 64;
                        }
                        if (x & 0x2000000000000 > 0) {
                            result = (result * 0x1000162E525EE0547) >> 64;
                        }
                        if (x & 0x1000000000000 > 0) {
                            result = (result * 0x10000B17255775C04) >> 64;
                        }
                    }
                    if (x & 0xFF0000000000 > 0) {
                        if (x & 0x800000000000 > 0) {
                            result = (result * 0x1000058B91B5BC9AE) >> 64;
                        }
                        if (x & 0x400000000000 > 0) {
                            result = (result * 0x100002C5C89D5EC6D) >> 64;
                        }
                        if (x & 0x200000000000 > 0) {
                            result = (result * 0x10000162E43F4F831) >> 64;
                        }
                        if (x & 0x100000000000 > 0) {
                            result = (result * 0x100000B1721BCFC9A) >> 64;
                        }
                        if (x & 0x80000000000 > 0) {
                            result = (result * 0x10000058B90CF1E6E) >> 64;
                        }
                        if (x & 0x40000000000 > 0) {
                            result = (result * 0x1000002C5C863B73F) >> 64;
                        }
                        if (x & 0x20000000000 > 0) {
                            result = (result * 0x100000162E430E5A2) >> 64;
                        }
                        if (x & 0x10000000000 > 0) {
                            result = (result * 0x1000000B172183551) >> 64;
                        }
                    }
                    if (x & 0xFF00000000 > 0) {
                        if (x & 0x8000000000 > 0) {
                            result = (result * 0x100000058B90C0B49) >> 64;
                        }
                        if (x & 0x4000000000 > 0) {
                            result = (result * 0x10000002C5C8601CC) >> 64;
                        }
                        if (x & 0x2000000000 > 0) {
                            result = (result * 0x1000000162E42FFF0) >> 64;
                        }
                        if (x & 0x1000000000 > 0) {
                            result = (result * 0x10000000B17217FBB) >> 64;
                        }
                        if (x & 0x800000000 > 0) {
                            result = (result * 0x1000000058B90BFCE) >> 64;
                        }
                        if (x & 0x400000000 > 0) {
                            result = (result * 0x100000002C5C85FE3) >> 64;
                        }
                        if (x & 0x200000000 > 0) {
                            result = (result * 0x10000000162E42FF1) >> 64;
                        }
                        if (x & 0x100000000 > 0) {
                            result = (result * 0x100000000B17217F8) >> 64;
                        }
                    }
                    if (x & 0xFF00000000 > 0) {
                        if (x & 0x80000000 > 0) {
                            result = (result * 0x10000000058B90BFC) >> 64;
                        }
                        if (x & 0x40000000 > 0) {
                            result = (result * 0x1000000002C5C85FE) >> 64;
                        }
                        if (x & 0x20000000 > 0) {
                            result = (result * 0x100000000162E42FF) >> 64;
                        }
                        if (x & 0x10000000 > 0) {
                            result = (result * 0x1000000000B17217F) >> 64;
                        }
                        if (x & 0x8000000 > 0) {
                            result = (result * 0x100000000058B90C0) >> 64;
                        }
                        if (x & 0x4000000 > 0) {
                            result = (result * 0x10000000002C5C860) >> 64;
                        }
                        if (x & 0x2000000 > 0) {
                            result = (result * 0x1000000000162E430) >> 64;
                        }
                        if (x & 0x1000000 > 0) {
                            result = (result * 0x10000000000B17218) >> 64;
                        }
                    }
                    if (x & 0xFF0000 > 0) {
                        if (x & 0x800000 > 0) {
                            result = (result * 0x1000000000058B90C) >> 64;
                        }
                        if (x & 0x400000 > 0) {
                            result = (result * 0x100000000002C5C86) >> 64;
                        }
                        if (x & 0x200000 > 0) {
                            result = (result * 0x10000000000162E43) >> 64;
                        }
                        if (x & 0x100000 > 0) {
                            result = (result * 0x100000000000B1721) >> 64;
                        }
                        if (x & 0x80000 > 0) {
                            result = (result * 0x10000000000058B91) >> 64;
                        }
                        if (x & 0x40000 > 0) {
                            result = (result * 0x1000000000002C5C8) >> 64;
                        }
                        if (x & 0x20000 > 0) {
                            result = (result * 0x100000000000162E4) >> 64;
                        }
                        if (x & 0x10000 > 0) {
                            result = (result * 0x1000000000000B172) >> 64;
                        }
                    }
                    if (x & 0xFF00 > 0) {
                        if (x & 0x8000 > 0) {
                            result = (result * 0x100000000000058B9) >> 64;
                        }
                        if (x & 0x4000 > 0) {
                            result = (result * 0x10000000000002C5D) >> 64;
                        }
                        if (x & 0x2000 > 0) {
                            result = (result * 0x1000000000000162E) >> 64;
                        }
                        if (x & 0x1000 > 0) {
                            result = (result * 0x10000000000000B17) >> 64;
                        }
                        if (x & 0x800 > 0) {
                            result = (result * 0x1000000000000058C) >> 64;
                        }
                        if (x & 0x400 > 0) {
                            result = (result * 0x100000000000002C6) >> 64;
                        }
                        if (x & 0x200 > 0) {
                            result = (result * 0x10000000000000163) >> 64;
                        }
                        if (x & 0x100 > 0) {
                            result = (result * 0x100000000000000B1) >> 64;
                        }
                    }
                    if (x & 0xFF > 0) {
                        if (x & 0x80 > 0) {
                            result = (result * 0x10000000000000059) >> 64;
                        }
                        if (x & 0x40 > 0) {
                            result = (result * 0x1000000000000002C) >> 64;
                        }
                        if (x & 0x20 > 0) {
                            result = (result * 0x10000000000000016) >> 64;
                        }
                        if (x & 0x10 > 0) {
                            result = (result * 0x1000000000000000B) >> 64;
                        }
                        if (x & 0x8 > 0) {
                            result = (result * 0x10000000000000006) >> 64;
                        }
                        if (x & 0x4 > 0) {
                            result = (result * 0x10000000000000003) >> 64;
                        }
                        if (x & 0x2 > 0) {
                            result = (result * 0x10000000000000001) >> 64;
                        }
                        if (x & 0x1 > 0) {
                            result = (result * 0x10000000000000001) >> 64;
                        }
                    }
                    // We're doing two things at the same time:
                    //
                    //   1. Multiply the result by 2^n + 1, where "2^n" is the integer part and the one is added to account for
                    //      the fact that we initially set the result to 0.5. This is accomplished by subtracting from 191
                    //      rather than 192.
                    //   2. Convert the result to the unsigned 60.18-decimal fixed-point format.
                    //
                    // This works because 2^(191-ip) = 2^ip / 2^191, where "ip" is the integer part "2^n".
                    result *= UNIT;
                    result >>= (191 - (x >> 64));
                }
            }
            /// @notice Calculates the square root of x, rounding down if x is not a perfect square.
            /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
            /// Credits to OpenZeppelin for the explanations in code comments below.
            ///
            /// Caveats:
            /// - This function does not work with fixed-point numbers.
            ///
            /// @param x The uint256 number for which to calculate the square root.
            /// @return result The result as an uint256.
            function prbSqrt(uint256 x) pure returns (uint256 result) {
                if (x == 0) {
                    return 0;
                }
                // For our first guess, we get the biggest power of 2 which is smaller than the square root of x.
                //
                // We know that the "msb" (most significant bit) of x is a power of 2 such that we have:
                //
                // $$
                // msb(x) <= x <= 2*msb(x)$
                // $$
                //
                // We write $msb(x)$ as $2^k$ and we get:
                //
                // $$
                // k = log_2(x)
                // $$
                //
                // Thus we can write the initial inequality as:
                //
                // $$
                // 2^{log_2(x)} <= x <= 2*2^{log_2(x)+1} \\\\
                // sqrt(2^k) <= sqrt(x) < sqrt(2^{k+1}) \\\\
                // 2^{k/2} <= sqrt(x) < 2^{(k+1)/2} <= 2^{(k/2)+1}
                // $$
                //
                // Consequently, $2^{log_2(x) /2}` is a good first approximation of sqrt(x) with at least one correct bit.
                uint256 xAux = uint256(x);
                result = 1;
                if (xAux >= 2 ** 128) {
                    xAux >>= 128;
                    result <<= 64;
                }
                if (xAux >= 2 ** 64) {
                    xAux >>= 64;
                    result <<= 32;
                }
                if (xAux >= 2 ** 32) {
                    xAux >>= 32;
                    result <<= 16;
                }
                if (xAux >= 2 ** 16) {
                    xAux >>= 16;
                    result <<= 8;
                }
                if (xAux >= 2 ** 8) {
                    xAux >>= 8;
                    result <<= 4;
                }
                if (xAux >= 2 ** 4) {
                    xAux >>= 4;
                    result <<= 2;
                }
                if (xAux >= 2 ** 2) {
                    result <<= 1;
                }
                // At this point, `result` is an estimation with at least one bit of precision. We know the true value has at
                // most 128 bits, since  it is the square root of a uint256. Newton's method converges quadratically (precision
                // doubles at every iteration). We thus need at most 7 iteration to turn our partial result with one bit of
                // precision into the expected uint128 result.
                unchecked {
                    result = (result + x / result) >> 1;
                    result = (result + x / result) >> 1;
                    result = (result + x / result) >> 1;
                    result = (result + x / result) >> 1;
                    result = (result + x / result) >> 1;
                    result = (result + x / result) >> 1;
                    result = (result + x / result) >> 1;
                    // Round down the result in case x is not a perfect square.
                    uint256 roundedDownResult = x / result;
                    if (result >= roundedDownResult) {
                        result = roundedDownResult;
                    }
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            import { MAX_UINT40 } from "../Common.sol";
            import { SD59x18 } from "../sd59x18/ValueType.sol";
            import { UD2x18 } from "../ud2x18/ValueType.sol";
            import { UD60x18 } from "../ud60x18/ValueType.sol";
            import {
                PRBMath_SD1x18_ToUD2x18_Underflow,
                PRBMath_SD1x18_ToUD60x18_Underflow,
                PRBMath_SD1x18_ToUint128_Underflow,
                PRBMath_SD1x18_ToUint256_Underflow,
                PRBMath_SD1x18_ToUint40_Overflow,
                PRBMath_SD1x18_ToUint40_Underflow
            } from "./Errors.sol";
            import { SD1x18 } from "./ValueType.sol";
            /// @notice Casts an SD1x18 number into SD59x18.
            /// @dev There is no overflow check because the domain of SD1x18 is a subset of SD59x18.
            function intoSD59x18(SD1x18 x) pure returns (SD59x18 result) {
                result = SD59x18.wrap(int256(SD1x18.unwrap(x)));
            }
            /// @notice Casts an SD1x18 number into UD2x18.
            /// - x must be positive.
            function intoUD2x18(SD1x18 x) pure returns (UD2x18 result) {
                int64 xInt = SD1x18.unwrap(x);
                if (xInt < 0) {
                    revert PRBMath_SD1x18_ToUD2x18_Underflow(x);
                }
                result = UD2x18.wrap(uint64(xInt));
            }
            /// @notice Casts an SD1x18 number into UD60x18.
            /// @dev Requirements:
            /// - x must be positive.
            function intoUD60x18(SD1x18 x) pure returns (UD60x18 result) {
                int64 xInt = SD1x18.unwrap(x);
                if (xInt < 0) {
                    revert PRBMath_SD1x18_ToUD60x18_Underflow(x);
                }
                result = UD60x18.wrap(uint64(xInt));
            }
            /// @notice Casts an SD1x18 number into uint256.
            /// @dev Requirements:
            /// - x must be positive.
            function intoUint256(SD1x18 x) pure returns (uint256 result) {
                int64 xInt = SD1x18.unwrap(x);
                if (xInt < 0) {
                    revert PRBMath_SD1x18_ToUint256_Underflow(x);
                }
                result = uint256(uint64(xInt));
            }
            /// @notice Casts an SD1x18 number into uint128.
            /// @dev Requirements:
            /// - x must be positive.
            function intoUint128(SD1x18 x) pure returns (uint128 result) {
                int64 xInt = SD1x18.unwrap(x);
                if (xInt < 0) {
                    revert PRBMath_SD1x18_ToUint128_Underflow(x);
                }
                result = uint128(uint64(xInt));
            }
            /// @notice Casts an SD1x18 number into uint40.
            /// @dev Requirements:
            /// - x must be positive.
            /// - x must be less than or equal to `MAX_UINT40`.
            function intoUint40(SD1x18 x) pure returns (uint40 result) {
                int64 xInt = SD1x18.unwrap(x);
                if (xInt < 0) {
                    revert PRBMath_SD1x18_ToUint40_Underflow(x);
                }
                if (xInt > int64(uint64(MAX_UINT40))) {
                    revert PRBMath_SD1x18_ToUint40_Overflow(x);
                }
                result = uint40(uint64(xInt));
            }
            /// @notice Alias for the `wrap` function.
            function sd1x18(int64 x) pure returns (SD1x18 result) {
                result = wrap(x);
            }
            /// @notice Unwraps an SD1x18 number into int64.
            function unwrap(SD1x18 x) pure returns (int64 result) {
                result = SD1x18.unwrap(x);
            }
            /// @notice Wraps an int64 number into the SD1x18 value type.
            function wrap(int64 x) pure returns (SD1x18 result) {
                result = SD1x18.wrap(x);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            import { SD1x18 } from "./ValueType.sol";
            /// @dev Euler's number as an SD1x18 number.
            SD1x18 constant E = SD1x18.wrap(2_718281828459045235);
            /// @dev The maximum value an SD1x18 number can have.
            int64 constant uMAX_SD1x18 = 9_223372036854775807;
            SD1x18 constant MAX_SD1x18 = SD1x18.wrap(uMAX_SD1x18);
            /// @dev The maximum value an SD1x18 number can have.
            int64 constant uMIN_SD1x18 = -9_223372036854775808;
            SD1x18 constant MIN_SD1x18 = SD1x18.wrap(uMIN_SD1x18);
            /// @dev PI as an SD1x18 number.
            SD1x18 constant PI = SD1x18.wrap(3_141592653589793238);
            /// @dev The unit amount that implies how many trailing decimals can be represented.
            SD1x18 constant UNIT = SD1x18.wrap(1e18);
            int256 constant uUNIT = 1e18;
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            import { SD1x18 } from "./ValueType.sol";
            /// @notice Emitted when trying to cast a SD1x18 number that doesn't fit in UD2x18.
            error PRBMath_SD1x18_ToUD2x18_Underflow(SD1x18 x);
            /// @notice Emitted when trying to cast a SD1x18 number that doesn't fit in UD60x18.
            error PRBMath_SD1x18_ToUD60x18_Underflow(SD1x18 x);
            /// @notice Emitted when trying to cast a SD1x18 number that doesn't fit in uint128.
            error PRBMath_SD1x18_ToUint128_Underflow(SD1x18 x);
            /// @notice Emitted when trying to cast a SD1x18 number that doesn't fit in uint256.
            error PRBMath_SD1x18_ToUint256_Underflow(SD1x18 x);
            /// @notice Emitted when trying to cast a SD1x18 number that doesn't fit in uint40.
            error PRBMath_SD1x18_ToUint40_Overflow(SD1x18 x);
            /// @notice Emitted when trying to cast a SD1x18 number that doesn't fit in uint40.
            error PRBMath_SD1x18_ToUint40_Underflow(SD1x18 x);
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            import "./Casting.sol" as C;
            /// @notice The signed 1.18-decimal fixed-point number representation, which can have up to 1 digit and up to 18 decimals.
            /// The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity type int64.
            /// This is useful when end users want to use int64 to save gas, e.g. with tight variable packing in contract storage.
            type SD1x18 is int64;
            /*//////////////////////////////////////////////////////////////////////////
                                                CASTING
            //////////////////////////////////////////////////////////////////////////*/
            using { C.intoSD59x18, C.intoUD2x18, C.intoUD60x18, C.intoUint256, C.intoUint128, C.intoUint40, C.unwrap } for SD1x18 global;
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            import { MAX_UINT128, MAX_UINT40 } from "../Common.sol";
            import { uMAX_SD1x18, uMIN_SD1x18 } from "../sd1x18/Constants.sol";
            import { SD1x18 } from "../sd1x18/ValueType.sol";
            import { uMAX_UD2x18 } from "../ud2x18/Constants.sol";
            import { UD2x18 } from "../ud2x18/ValueType.sol";
            import { UD60x18 } from "../ud60x18/ValueType.sol";
            import {
                PRBMath_SD59x18_IntoSD1x18_Overflow,
                PRBMath_SD59x18_IntoSD1x18_Underflow,
                PRBMath_SD59x18_IntoUD2x18_Overflow,
                PRBMath_SD59x18_IntoUD2x18_Underflow,
                PRBMath_SD59x18_IntoUD60x18_Underflow,
                PRBMath_SD59x18_IntoUint128_Overflow,
                PRBMath_SD59x18_IntoUint128_Underflow,
                PRBMath_SD59x18_IntoUint256_Underflow,
                PRBMath_SD59x18_IntoUint40_Overflow,
                PRBMath_SD59x18_IntoUint40_Underflow
            } from "./Errors.sol";
            import { SD59x18 } from "./ValueType.sol";
            /// @notice Casts an SD59x18 number into int256.
            /// @dev This is basically a functional alias for the `unwrap` function.
            function intoInt256(SD59x18 x) pure returns (int256 result) {
                result = SD59x18.unwrap(x);
            }
            /// @notice Casts an SD59x18 number into SD1x18.
            /// @dev Requirements:
            /// - x must be greater than or equal to `uMIN_SD1x18`.
            /// - x must be less than or equal to `uMAX_SD1x18`.
            function intoSD1x18(SD59x18 x) pure returns (SD1x18 result) {
                int256 xInt = SD59x18.unwrap(x);
                if (xInt < uMIN_SD1x18) {
                    revert PRBMath_SD59x18_IntoSD1x18_Underflow(x);
                }
                if (xInt > uMAX_SD1x18) {
                    revert PRBMath_SD59x18_IntoSD1x18_Overflow(x);
                }
                result = SD1x18.wrap(int64(xInt));
            }
            /// @notice Casts an SD59x18 number into UD2x18.
            /// @dev Requirements:
            /// - x must be positive.
            /// - x must be less than or equal to `uMAX_UD2x18`.
            function intoUD2x18(SD59x18 x) pure returns (UD2x18 result) {
                int256 xInt = SD59x18.unwrap(x);
                if (xInt < 0) {
                    revert PRBMath_SD59x18_IntoUD2x18_Underflow(x);
                }
                if (xInt > int256(uint256(uMAX_UD2x18))) {
                    revert PRBMath_SD59x18_IntoUD2x18_Overflow(x);
                }
                result = UD2x18.wrap(uint64(uint256(xInt)));
            }
            /// @notice Casts an SD59x18 number into UD60x18.
            /// @dev Requirements:
            /// - x must be positive.
            function intoUD60x18(SD59x18 x) pure returns (UD60x18 result) {
                int256 xInt = SD59x18.unwrap(x);
                if (xInt < 0) {
                    revert PRBMath_SD59x18_IntoUD60x18_Underflow(x);
                }
                result = UD60x18.wrap(uint256(xInt));
            }
            /// @notice Casts an SD59x18 number into uint256.
            /// @dev Requirements:
            /// - x must be positive.
            function intoUint256(SD59x18 x) pure returns (uint256 result) {
                int256 xInt = SD59x18.unwrap(x);
                if (xInt < 0) {
                    revert PRBMath_SD59x18_IntoUint256_Underflow(x);
                }
                result = uint256(xInt);
            }
            /// @notice Casts an SD59x18 number into uint128.
            /// @dev Requirements:
            /// - x must be positive.
            /// - x must be less than or equal to `uMAX_UINT128`.
            function intoUint128(SD59x18 x) pure returns (uint128 result) {
                int256 xInt = SD59x18.unwrap(x);
                if (xInt < 0) {
                    revert PRBMath_SD59x18_IntoUint128_Underflow(x);
                }
                if (xInt > int256(uint256(MAX_UINT128))) {
                    revert PRBMath_SD59x18_IntoUint128_Overflow(x);
                }
                result = uint128(uint256(xInt));
            }
            /// @notice Casts an SD59x18 number into uint40.
            /// @dev Requirements:
            /// - x must be positive.
            /// - x must be less than or equal to `MAX_UINT40`.
            function intoUint40(SD59x18 x) pure returns (uint40 result) {
                int256 xInt = SD59x18.unwrap(x);
                if (xInt < 0) {
                    revert PRBMath_SD59x18_IntoUint40_Underflow(x);
                }
                if (xInt > int256(uint256(MAX_UINT40))) {
                    revert PRBMath_SD59x18_IntoUint40_Overflow(x);
                }
                result = uint40(uint256(xInt));
            }
            /// @notice Alias for the `wrap` function.
            function sd(int256 x) pure returns (SD59x18 result) {
                result = wrap(x);
            }
            /// @notice Alias for the `wrap` function.
            function sd59x18(int256 x) pure returns (SD59x18 result) {
                result = wrap(x);
            }
            /// @notice Unwraps an SD59x18 number into int256.
            function unwrap(SD59x18 x) pure returns (int256 result) {
                result = SD59x18.unwrap(x);
            }
            /// @notice Wraps an int256 number into the SD59x18 value type.
            function wrap(int256 x) pure returns (SD59x18 result) {
                result = SD59x18.wrap(x);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            import { SD59x18 } from "./ValueType.sol";
            /// NOTICE: the "u" prefix stands for "unwrapped".
            /// @dev Euler's number as an SD59x18 number.
            SD59x18 constant E = SD59x18.wrap(2_718281828459045235);
            /// @dev Half the UNIT number.
            int256 constant uHALF_UNIT = 0.5e18;
            SD59x18 constant HALF_UNIT = SD59x18.wrap(uHALF_UNIT);
            /// @dev log2(10) as an SD59x18 number.
            int256 constant uLOG2_10 = 3_321928094887362347;
            SD59x18 constant LOG2_10 = SD59x18.wrap(uLOG2_10);
            /// @dev log2(e) as an SD59x18 number.
            int256 constant uLOG2_E = 1_442695040888963407;
            SD59x18 constant LOG2_E = SD59x18.wrap(uLOG2_E);
            /// @dev The maximum value an SD59x18 number can have.
            int256 constant uMAX_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_792003956564819967;
            SD59x18 constant MAX_SD59x18 = SD59x18.wrap(uMAX_SD59x18);
            /// @dev The maximum whole value an SD59x18 number can have.
            int256 constant uMAX_WHOLE_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_000000000000000000;
            SD59x18 constant MAX_WHOLE_SD59x18 = SD59x18.wrap(uMAX_WHOLE_SD59x18);
            /// @dev The minimum value an SD59x18 number can have.
            int256 constant uMIN_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_792003956564819968;
            SD59x18 constant MIN_SD59x18 = SD59x18.wrap(uMIN_SD59x18);
            /// @dev The minimum whole value an SD59x18 number can have.
            int256 constant uMIN_WHOLE_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_000000000000000000;
            SD59x18 constant MIN_WHOLE_SD59x18 = SD59x18.wrap(uMIN_WHOLE_SD59x18);
            /// @dev PI as an SD59x18 number.
            SD59x18 constant PI = SD59x18.wrap(3_141592653589793238);
            /// @dev The unit amount that implies how many trailing decimals can be represented.
            int256 constant uUNIT = 1e18;
            SD59x18 constant UNIT = SD59x18.wrap(1e18);
            /// @dev Zero as an SD59x18 number.
            SD59x18 constant ZERO = SD59x18.wrap(0);
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            import { SD59x18 } from "./ValueType.sol";
            /// @notice Emitted when taking the absolute value of `MIN_SD59x18`.
            error PRBMath_SD59x18_Abs_MinSD59x18();
            /// @notice Emitted when ceiling a number overflows SD59x18.
            error PRBMath_SD59x18_Ceil_Overflow(SD59x18 x);
            /// @notice Emitted when converting a basic integer to the fixed-point format overflows SD59x18.
            error PRBMath_SD59x18_Convert_Overflow(int256 x);
            /// @notice Emitted when converting a basic integer to the fixed-point format underflows SD59x18.
            error PRBMath_SD59x18_Convert_Underflow(int256 x);
            /// @notice Emitted when dividing two numbers and one of them is `MIN_SD59x18`.
            error PRBMath_SD59x18_Div_InputTooSmall();
            /// @notice Emitted when dividing two numbers and one of the intermediary unsigned results overflows SD59x18.
            error PRBMath_SD59x18_Div_Overflow(SD59x18 x, SD59x18 y);
            /// @notice Emitted when taking the natural exponent of a base greater than 133.084258667509499441.
            error PRBMath_SD59x18_Exp_InputTooBig(SD59x18 x);
            /// @notice Emitted when taking the binary exponent of a base greater than 192.
            error PRBMath_SD59x18_Exp2_InputTooBig(SD59x18 x);
            /// @notice Emitted when flooring a number underflows SD59x18.
            error PRBMath_SD59x18_Floor_Underflow(SD59x18 x);
            /// @notice Emitted when taking the geometric mean of two numbers and their product is negative.
            error PRBMath_SD59x18_Gm_NegativeProduct(SD59x18 x, SD59x18 y);
            /// @notice Emitted when taking the geometric mean of two numbers and multiplying them overflows SD59x18.
            error PRBMath_SD59x18_Gm_Overflow(SD59x18 x, SD59x18 y);
            /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in SD1x18.
            error PRBMath_SD59x18_IntoSD1x18_Overflow(SD59x18 x);
            /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in SD1x18.
            error PRBMath_SD59x18_IntoSD1x18_Underflow(SD59x18 x);
            /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in UD2x18.
            error PRBMath_SD59x18_IntoUD2x18_Overflow(SD59x18 x);
            /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in UD2x18.
            error PRBMath_SD59x18_IntoUD2x18_Underflow(SD59x18 x);
            /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in UD60x18.
            error PRBMath_SD59x18_IntoUD60x18_Underflow(SD59x18 x);
            /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in uint128.
            error PRBMath_SD59x18_IntoUint128_Overflow(SD59x18 x);
            /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in uint128.
            error PRBMath_SD59x18_IntoUint128_Underflow(SD59x18 x);
            /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in uint256.
            error PRBMath_SD59x18_IntoUint256_Underflow(SD59x18 x);
            /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in uint40.
            error PRBMath_SD59x18_IntoUint40_Overflow(SD59x18 x);
            /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in uint40.
            error PRBMath_SD59x18_IntoUint40_Underflow(SD59x18 x);
            /// @notice Emitted when taking the logarithm of a number less than or equal to zero.
            error PRBMath_SD59x18_Log_InputTooSmall(SD59x18 x);
            /// @notice Emitted when multiplying two numbers and one of the inputs is `MIN_SD59x18`.
            error PRBMath_SD59x18_Mul_InputTooSmall();
            /// @notice Emitted when multiplying two numbers and the intermediary absolute result overflows SD59x18.
            error PRBMath_SD59x18_Mul_Overflow(SD59x18 x, SD59x18 y);
            /// @notice Emitted when raising a number to a power and hte intermediary absolute result overflows SD59x18.
            error PRBMath_SD59x18_Powu_Overflow(SD59x18 x, uint256 y);
            /// @notice Emitted when taking the square root of a negative number.
            error PRBMath_SD59x18_Sqrt_NegativeInput(SD59x18 x);
            /// @notice Emitted when the calculating the square root overflows SD59x18.
            error PRBMath_SD59x18_Sqrt_Overflow(SD59x18 x);
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            import { unwrap, wrap } from "./Casting.sol";
            import { SD59x18 } from "./ValueType.sol";
            /// @notice Implements the checked addition operation (+) in the SD59x18 type.
            function add(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
                return wrap(unwrap(x) + unwrap(y));
            }
            /// @notice Implements the AND (&) bitwise operation in the SD59x18 type.
            function and(SD59x18 x, int256 bits) pure returns (SD59x18 result) {
                return wrap(unwrap(x) & bits);
            }
            /// @notice Implements the equal (=) operation in the SD59x18 type.
            function eq(SD59x18 x, SD59x18 y) pure returns (bool result) {
                result = unwrap(x) == unwrap(y);
            }
            /// @notice Implements the greater than operation (>) in the SD59x18 type.
            function gt(SD59x18 x, SD59x18 y) pure returns (bool result) {
                result = unwrap(x) > unwrap(y);
            }
            /// @notice Implements the greater than or equal to operation (>=) in the SD59x18 type.
            function gte(SD59x18 x, SD59x18 y) pure returns (bool result) {
                result = unwrap(x) >= unwrap(y);
            }
            /// @notice Implements a zero comparison check function in the SD59x18 type.
            function isZero(SD59x18 x) pure returns (bool result) {
                result = unwrap(x) == 0;
            }
            /// @notice Implements the left shift operation (<<) in the SD59x18 type.
            function lshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) {
                result = wrap(unwrap(x) << bits);
            }
            /// @notice Implements the lower than operation (<) in the SD59x18 type.
            function lt(SD59x18 x, SD59x18 y) pure returns (bool result) {
                result = unwrap(x) < unwrap(y);
            }
            /// @notice Implements the lower than or equal to operation (<=) in the SD59x18 type.
            function lte(SD59x18 x, SD59x18 y) pure returns (bool result) {
                result = unwrap(x) <= unwrap(y);
            }
            /// @notice Implements the unchecked modulo operation (%) in the SD59x18 type.
            function mod(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
                result = wrap(unwrap(x) % unwrap(y));
            }
            /// @notice Implements the not equal operation (!=) in the SD59x18 type.
            function neq(SD59x18 x, SD59x18 y) pure returns (bool result) {
                result = unwrap(x) != unwrap(y);
            }
            /// @notice Implements the OR (|) bitwise operation in the SD59x18 type.
            function or(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
                result = wrap(unwrap(x) | unwrap(y));
            }
            /// @notice Implements the right shift operation (>>) in the SD59x18 type.
            function rshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) {
                result = wrap(unwrap(x) >> bits);
            }
            /// @notice Implements the checked subtraction operation (-) in the SD59x18 type.
            function sub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
                result = wrap(unwrap(x) - unwrap(y));
            }
            /// @notice Implements the unchecked addition operation (+) in the SD59x18 type.
            function uncheckedAdd(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
                unchecked {
                    result = wrap(unwrap(x) + unwrap(y));
                }
            }
            /// @notice Implements the unchecked subtraction operation (-) in the SD59x18 type.
            function uncheckedSub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
                unchecked {
                    result = wrap(unwrap(x) - unwrap(y));
                }
            }
            /// @notice Implements the unchecked unary minus operation (-) in the SD59x18 type.
            function uncheckedUnary(SD59x18 x) pure returns (SD59x18 result) {
                unchecked {
                    result = wrap(-unwrap(x));
                }
            }
            /// @notice Implements the XOR (^) bitwise operation in the SD59x18 type.
            function xor(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
                result = wrap(unwrap(x) ^ unwrap(y));
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            import { MAX_UINT128, MAX_UINT40, msb, mulDiv, mulDiv18, prbExp2, prbSqrt } from "../Common.sol";
            import {
                uHALF_UNIT,
                uLOG2_10,
                uLOG2_E,
                uMAX_SD59x18,
                uMAX_WHOLE_SD59x18,
                uMIN_SD59x18,
                uMIN_WHOLE_SD59x18,
                UNIT,
                uUNIT,
                ZERO
            } from "./Constants.sol";
            import {
                PRBMath_SD59x18_Abs_MinSD59x18,
                PRBMath_SD59x18_Ceil_Overflow,
                PRBMath_SD59x18_Div_InputTooSmall,
                PRBMath_SD59x18_Div_Overflow,
                PRBMath_SD59x18_Exp_InputTooBig,
                PRBMath_SD59x18_Exp2_InputTooBig,
                PRBMath_SD59x18_Floor_Underflow,
                PRBMath_SD59x18_Gm_Overflow,
                PRBMath_SD59x18_Gm_NegativeProduct,
                PRBMath_SD59x18_Log_InputTooSmall,
                PRBMath_SD59x18_Mul_InputTooSmall,
                PRBMath_SD59x18_Mul_Overflow,
                PRBMath_SD59x18_Powu_Overflow,
                PRBMath_SD59x18_Sqrt_NegativeInput,
                PRBMath_SD59x18_Sqrt_Overflow
            } from "./Errors.sol";
            import { unwrap, wrap } from "./Helpers.sol";
            import { SD59x18 } from "./ValueType.sol";
            /// @notice Calculate the absolute value of x.
            ///
            /// @dev Requirements:
            /// - x must be greater than `MIN_SD59x18`.
            ///
            /// @param x The SD59x18 number for which to calculate the absolute value.
            /// @param result The absolute value of x as an SD59x18 number.
            function abs(SD59x18 x) pure returns (SD59x18 result) {
                int256 xInt = unwrap(x);
                if (xInt == uMIN_SD59x18) {
                    revert PRBMath_SD59x18_Abs_MinSD59x18();
                }
                result = xInt < 0 ? wrap(-xInt) : x;
            }
            /// @notice Calculates the arithmetic average of x and y, rounding towards zero.
            /// @param x The first operand as an SD59x18 number.
            /// @param y The second operand as an SD59x18 number.
            /// @return result The arithmetic average as an SD59x18 number.
            function avg(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
                int256 xInt = unwrap(x);
                int256 yInt = unwrap(y);
                unchecked {
                    // This is equivalent to "x / 2 +  y / 2" but faster.
                    // This operation can never overflow.
                    int256 sum = (xInt >> 1) + (yInt >> 1);
                    if (sum < 0) {
                        // If at least one of x and y is odd, we add 1 to the result, since shifting negative numbers to the right rounds
                        // down to infinity. The right part is equivalent to "sum + (x % 2 == 1 || y % 2 == 1)" but faster.
                        assembly ("memory-safe") {
                            result := add(sum, and(or(xInt, yInt), 1))
                        }
                    } else {
                        // We need to add 1 if both x and y are odd to account for the double 0.5 remainder that is truncated after shifting.
                        result = wrap(sum + (xInt & yInt & 1));
                    }
                }
            }
            /// @notice Yields the smallest whole SD59x18 number greater than or equal to x.
            ///
            /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.
            /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
            ///
            /// Requirements:
            /// - x must be less than or equal to `MAX_WHOLE_SD59x18`.
            ///
            /// @param x The SD59x18 number to ceil.
            /// @param result The least number greater than or equal to x, as an SD59x18 number.
            function ceil(SD59x18 x) pure returns (SD59x18 result) {
                int256 xInt = unwrap(x);
                if (xInt > uMAX_WHOLE_SD59x18) {
                    revert PRBMath_SD59x18_Ceil_Overflow(x);
                }
                int256 remainder = xInt % uUNIT;
                if (remainder == 0) {
                    result = x;
                } else {
                    unchecked {
                        // Solidity uses C fmod style, which returns a modulus with the same sign as x.
                        int256 resultInt = xInt - remainder;
                        if (xInt > 0) {
                            resultInt += uUNIT;
                        }
                        result = wrap(resultInt);
                    }
                }
            }
            /// @notice Divides two SD59x18 numbers, returning a new SD59x18 number. Rounds towards zero.
            ///
            /// @dev This is a variant of `mulDiv` that works with signed numbers. Works by computing the signs and the absolute values
            /// separately.
            ///
            /// Requirements:
            /// - All from `Common.mulDiv`.
            /// - None of the inputs can be `MIN_SD59x18`.
            /// - The denominator cannot be zero.
            /// - The result must fit within int256.
            ///
            /// Caveats:
            /// - All from `Common.mulDiv`.
            ///
            /// @param x The numerator as an SD59x18 number.
            /// @param y The denominator as an SD59x18 number.
            /// @param result The quotient as an SD59x18 number.
            function div(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
                int256 xInt = unwrap(x);
                int256 yInt = unwrap(y);
                if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) {
                    revert PRBMath_SD59x18_Div_InputTooSmall();
                }
                // Get hold of the absolute values of x and y.
                uint256 xAbs;
                uint256 yAbs;
                unchecked {
                    xAbs = xInt < 0 ? uint256(-xInt) : uint256(xInt);
                    yAbs = yInt < 0 ? uint256(-yInt) : uint256(yInt);
                }
                // Compute the absolute value (x*UNIT)÷y. The resulting value must fit within int256.
                uint256 resultAbs = mulDiv(xAbs, uint256(uUNIT), yAbs);
                if (resultAbs > uint256(uMAX_SD59x18)) {
                    revert PRBMath_SD59x18_Div_Overflow(x, y);
                }
                // Check if x and y have the same sign. This works thanks to two's complement; the left-most bit is the sign bit.
                bool sameSign = (xInt ^ yInt) > -1;
                // If the inputs don't have the same sign, the result should be negative. Otherwise, it should be positive.
                unchecked {
                    result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs));
                }
            }
            /// @notice Calculates the natural exponent of x.
            ///
            /// @dev Based on the formula:
            ///
            /// $$
            /// e^x = 2^{x * log_2{e}}
            /// $$
            ///
            /// Requirements:
            /// - All from `log2`.
            /// - x must be less than 133.084258667509499441.
            ///
            /// Caveats:
            /// - All from `exp2`.
            /// - For any x less than -41.446531673892822322, the result is zero.
            ///
            /// @param x The exponent as an SD59x18 number.
            /// @return result The result as an SD59x18 number.
            function exp(SD59x18 x) pure returns (SD59x18 result) {
                int256 xInt = unwrap(x);
                // Without this check, the value passed to `exp2` would be less than -59.794705707972522261.
                if (xInt < -41_446531673892822322) {
                    return ZERO;
                }
                // Without this check, the value passed to `exp2` would be greater than 192.
                if (xInt >= 133_084258667509499441) {
                    revert PRBMath_SD59x18_Exp_InputTooBig(x);
                }
                unchecked {
                    // Do the fixed-point multiplication inline to save gas.
                    int256 doubleUnitProduct = xInt * uLOG2_E;
                    result = exp2(wrap(doubleUnitProduct / uUNIT));
                }
            }
            /// @notice Calculates the binary exponent of x using the binary fraction method.
            ///
            /// @dev Based on the formula:
            ///
            /// $$
            /// 2^{-x} = \\frac{1}{2^x}
            /// $$
            ///
            /// See https://ethereum.stackexchange.com/q/79903/24693.
            ///
            /// Requirements:
            /// - x must be 192 or less.
            /// - The result must fit within `MAX_SD59x18`.
            ///
            /// Caveats:
            /// - For any x less than -59.794705707972522261, the result is zero.
            ///
            /// @param x The exponent as an SD59x18 number.
            /// @return result The result as an SD59x18 number.
            function exp2(SD59x18 x) pure returns (SD59x18 result) {
                int256 xInt = unwrap(x);
                if (xInt < 0) {
                    // 2^59.794705707972522262 is the maximum number whose inverse does not truncate down to zero.
                    if (xInt < -59_794705707972522261) {
                        return ZERO;
                    }
                    unchecked {
                        // Do the fixed-point inversion $1/2^x$ inline to save gas. 1e36 is UNIT * UNIT.
                        result = wrap(1e36 / unwrap(exp2(wrap(-xInt))));
                    }
                } else {
                    // 2^192 doesn't fit within the 192.64-bit format used internally in this function.
                    if (xInt >= 192e18) {
                        revert PRBMath_SD59x18_Exp2_InputTooBig(x);
                    }
                    unchecked {
                        // Convert x to the 192.64-bit fixed-point format.
                        uint256 x_192x64 = uint256((xInt << 64) / uUNIT);
                        // It is safe to convert the result to int256 with no checks because the maximum input allowed in this function is 192.
                        result = wrap(int256(prbExp2(x_192x64)));
                    }
                }
            }
            /// @notice Yields the greatest whole SD59x18 number less than or equal to x.
            ///
            /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.
            /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
            ///
            /// Requirements:
            /// - x must be greater than or equal to `MIN_WHOLE_SD59x18`.
            ///
            /// @param x The SD59x18 number to floor.
            /// @param result The greatest integer less than or equal to x, as an SD59x18 number.
            function floor(SD59x18 x) pure returns (SD59x18 result) {
                int256 xInt = unwrap(x);
                if (xInt < uMIN_WHOLE_SD59x18) {
                    revert PRBMath_SD59x18_Floor_Underflow(x);
                }
                int256 remainder = xInt % uUNIT;
                if (remainder == 0) {
                    result = x;
                } else {
                    unchecked {
                        // Solidity uses C fmod style, which returns a modulus with the same sign as x.
                        int256 resultInt = xInt - remainder;
                        if (xInt < 0) {
                            resultInt -= uUNIT;
                        }
                        result = wrap(resultInt);
                    }
                }
            }
            /// @notice Yields the excess beyond the floor of x for positive numbers and the part of the number to the right.
            /// of the radix point for negative numbers.
            /// @dev Based on the odd function definition. https://en.wikipedia.org/wiki/Fractional_part
            /// @param x The SD59x18 number to get the fractional part of.
            /// @param result The fractional part of x as an SD59x18 number.
            function frac(SD59x18 x) pure returns (SD59x18 result) {
                result = wrap(unwrap(x) % uUNIT);
            }
            /// @notice Calculates the geometric mean of x and y, i.e. sqrt(x * y), rounding down.
            ///
            /// @dev Requirements:
            /// - x * y must fit within `MAX_SD59x18`, lest it overflows.
            /// - x * y must not be negative, since this library does not handle complex numbers.
            ///
            /// @param x The first operand as an SD59x18 number.
            /// @param y The second operand as an SD59x18 number.
            /// @return result The result as an SD59x18 number.
            function gm(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
                int256 xInt = unwrap(x);
                int256 yInt = unwrap(y);
                if (xInt == 0 || yInt == 0) {
                    return ZERO;
                }
                unchecked {
                    // Equivalent to "xy / x != y". Checking for overflow this way is faster than letting Solidity do it.
                    int256 xyInt = xInt * yInt;
                    if (xyInt / xInt != yInt) {
                        revert PRBMath_SD59x18_Gm_Overflow(x, y);
                    }
                    // The product must not be negative, since this library does not handle complex numbers.
                    if (xyInt < 0) {
                        revert PRBMath_SD59x18_Gm_NegativeProduct(x, y);
                    }
                    // We don't need to multiply the result by `UNIT` here because the x*y product had picked up a factor of `UNIT`
                    // during multiplication. See the comments within the `prbSqrt` function.
                    uint256 resultUint = prbSqrt(uint256(xyInt));
                    result = wrap(int256(resultUint));
                }
            }
            /// @notice Calculates 1 / x, rounding toward zero.
            ///
            /// @dev Requirements:
            /// - x cannot be zero.
            ///
            /// @param x The SD59x18 number for which to calculate the inverse.
            /// @return result The inverse as an SD59x18 number.
            function inv(SD59x18 x) pure returns (SD59x18 result) {
                // 1e36 is UNIT * UNIT.
                result = wrap(1e36 / unwrap(x));
            }
            /// @notice Calculates the natural logarithm of x.
            ///
            /// @dev Based on the formula:
            ///
            /// $$
            /// ln{x} = log_2{x} / log_2{e}$$.
            /// $$
            ///
            /// Requirements:
            /// - All from `log2`.
            ///
            /// Caveats:
            /// - All from `log2`.
            /// - This doesn't return exactly 1 for 2.718281828459045235, for that more fine-grained precision is needed.
            ///
            /// @param x The SD59x18 number for which to calculate the natural logarithm.
            /// @return result The natural logarithm as an SD59x18 number.
            function ln(SD59x18 x) pure returns (SD59x18 result) {
                // Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x)
                // can return is 195.205294292027477728.
                result = wrap((unwrap(log2(x)) * uUNIT) / uLOG2_E);
            }
            /// @notice Calculates the common logarithm of x.
            ///
            /// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common
            /// logarithm based on the formula:
            ///
            /// $$
            /// log_{10}{x} = log_2{x} / log_2{10}
            /// $$
            ///
            /// Requirements:
            /// - All from `log2`.
            ///
            /// Caveats:
            /// - All from `log2`.
            ///
            /// @param x The SD59x18 number for which to calculate the common logarithm.
            /// @return result The common logarithm as an SD59x18 number.
            function log10(SD59x18 x) pure returns (SD59x18 result) {
                int256 xInt = unwrap(x);
                if (xInt < 0) {
                    revert PRBMath_SD59x18_Log_InputTooSmall(x);
                }
                // Note that the `mul` in this block is the assembly mul operation, not the SD59x18 `mul`.
                // prettier-ignore
                assembly ("memory-safe") {
                    switch x
                    case 1 { result := mul(uUNIT, sub(0, 18)) }
                    case 10 { result := mul(uUNIT, sub(1, 18)) }
                    case 100 { result := mul(uUNIT, sub(2, 18)) }
                    case 1000 { result := mul(uUNIT, sub(3, 18)) }
                    case 10000 { result := mul(uUNIT, sub(4, 18)) }
                    case 100000 { result := mul(uUNIT, sub(5, 18)) }
                    case 1000000 { result := mul(uUNIT, sub(6, 18)) }
                    case 10000000 { result := mul(uUNIT, sub(7, 18)) }
                    case 100000000 { result := mul(uUNIT, sub(8, 18)) }
                    case 1000000000 { result := mul(uUNIT, sub(9, 18)) }
                    case 10000000000 { result := mul(uUNIT, sub(10, 18)) }
                    case 100000000000 { result := mul(uUNIT, sub(11, 18)) }
                    case 1000000000000 { result := mul(uUNIT, sub(12, 18)) }
                    case 10000000000000 { result := mul(uUNIT, sub(13, 18)) }
                    case 100000000000000 { result := mul(uUNIT, sub(14, 18)) }
                    case 1000000000000000 { result := mul(uUNIT, sub(15, 18)) }
                    case 10000000000000000 { result := mul(uUNIT, sub(16, 18)) }
                    case 100000000000000000 { result := mul(uUNIT, sub(17, 18)) }
                    case 1000000000000000000 { result := 0 }
                    case 10000000000000000000 { result := uUNIT }
                    case 100000000000000000000 { result := mul(uUNIT, 2) }
                    case 1000000000000000000000 { result := mul(uUNIT, 3) }
                    case 10000000000000000000000 { result := mul(uUNIT, 4) }
                    case 100000000000000000000000 { result := mul(uUNIT, 5) }
                    case 1000000000000000000000000 { result := mul(uUNIT, 6) }
                    case 10000000000000000000000000 { result := mul(uUNIT, 7) }
                    case 100000000000000000000000000 { result := mul(uUNIT, 8) }
                    case 1000000000000000000000000000 { result := mul(uUNIT, 9) }
                    case 10000000000000000000000000000 { result := mul(uUNIT, 10) }
                    case 100000000000000000000000000000 { result := mul(uUNIT, 11) }
                    case 1000000000000000000000000000000 { result := mul(uUNIT, 12) }
                    case 10000000000000000000000000000000 { result := mul(uUNIT, 13) }
                    case 100000000000000000000000000000000 { result := mul(uUNIT, 14) }
                    case 1000000000000000000000000000000000 { result := mul(uUNIT, 15) }
                    case 10000000000000000000000000000000000 { result := mul(uUNIT, 16) }
                    case 100000000000000000000000000000000000 { result := mul(uUNIT, 17) }
                    case 1000000000000000000000000000000000000 { result := mul(uUNIT, 18) }
                    case 10000000000000000000000000000000000000 { result := mul(uUNIT, 19) }
                    case 100000000000000000000000000000000000000 { result := mul(uUNIT, 20) }
                    case 1000000000000000000000000000000000000000 { result := mul(uUNIT, 21) }
                    case 10000000000000000000000000000000000000000 { result := mul(uUNIT, 22) }
                    case 100000000000000000000000000000000000000000 { result := mul(uUNIT, 23) }
                    case 1000000000000000000000000000000000000000000 { result := mul(uUNIT, 24) }
                    case 10000000000000000000000000000000000000000000 { result := mul(uUNIT, 25) }
                    case 100000000000000000000000000000000000000000000 { result := mul(uUNIT, 26) }
                    case 1000000000000000000000000000000000000000000000 { result := mul(uUNIT, 27) }
                    case 10000000000000000000000000000000000000000000000 { result := mul(uUNIT, 28) }
                    case 100000000000000000000000000000000000000000000000 { result := mul(uUNIT, 29) }
                    case 1000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 30) }
                    case 10000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 31) }
                    case 100000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 32) }
                    case 1000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 33) }
                    case 10000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 34) }
                    case 100000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 35) }
                    case 1000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 36) }
                    case 10000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 37) }
                    case 100000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 38) }
                    case 1000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 39) }
                    case 10000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 40) }
                    case 100000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 41) }
                    case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 42) }
                    case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 43) }
                    case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 44) }
                    case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 45) }
                    case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 46) }
                    case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 47) }
                    case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 48) }
                    case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 49) }
                    case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 50) }
                    case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 51) }
                    case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 52) }
                    case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 53) }
                    case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 54) }
                    case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 55) }
                    case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 56) }
                    case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 57) }
                    case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 58) }
                    default {
                        result := uMAX_SD59x18
                    }
                }
                if (unwrap(result) == uMAX_SD59x18) {
                    unchecked {
                        // Do the fixed-point division inline to save gas.
                        result = wrap((unwrap(log2(x)) * uUNIT) / uLOG2_10);
                    }
                }
            }
            /// @notice Calculates the binary logarithm of x.
            ///
            /// @dev Based on the iterative approximation algorithm.
            /// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation
            ///
            /// Requirements:
            /// - x must be greater than zero.
            ///
            /// Caveats:
            /// - The results are not perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation.
            ///
            /// @param x The SD59x18 number for which to calculate the binary logarithm.
            /// @return result The binary logarithm as an SD59x18 number.
            function log2(SD59x18 x) pure returns (SD59x18 result) {
                int256 xInt = unwrap(x);
                if (xInt <= 0) {
                    revert PRBMath_SD59x18_Log_InputTooSmall(x);
                }
                unchecked {
                    // This works because of:
                    //
                    // $$
                    // log_2{x} = -log_2{\\frac{1}{x}}
                    // $$
                    int256 sign;
                    if (xInt >= uUNIT) {
                        sign = 1;
                    } else {
                        sign = -1;
                        // Do the fixed-point inversion inline to save gas. The numerator is UNIT * UNIT.
                        xInt = 1e36 / xInt;
                    }
                    // Calculate the integer part of the logarithm and add it to the result and finally calculate $y = x * 2^(-n)$.
                    uint256 n = msb(uint256(xInt / uUNIT));
                    // This is the integer part of the logarithm as an SD59x18 number. The operation can't overflow
                    // because n is maximum 255, UNIT is 1e18 and sign is either 1 or -1.
                    int256 resultInt = int256(n) * uUNIT;
                    // This is $y = x * 2^{-n}$.
                    int256 y = xInt >> n;
                    // If y is 1, the fractional part is zero.
                    if (y == uUNIT) {
                        return wrap(resultInt * sign);
                    }
                    // Calculate the fractional part via the iterative approximation.
                    // The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster.
                    int256 DOUBLE_UNIT = 2e18;
                    for (int256 delta = uHALF_UNIT; delta > 0; delta >>= 1) {
                        y = (y * y) / uUNIT;
                        // Is $y^2 > 2$ and so in the range [2,4)?
                        if (y >= DOUBLE_UNIT) {
                            // Add the 2^{-m} factor to the logarithm.
                            resultInt = resultInt + delta;
                            // Corresponds to z/2 on Wikipedia.
                            y >>= 1;
                        }
                    }
                    resultInt *= sign;
                    result = wrap(resultInt);
                }
            }
            /// @notice Multiplies two SD59x18 numbers together, returning a new SD59x18 number.
            ///
            /// @dev This is a variant of `mulDiv` that works with signed numbers and employs constant folding, i.e. the denominator
            /// is always 1e18.
            ///
            /// Requirements:
            /// - All from `Common.mulDiv18`.
            /// - None of the inputs can be `MIN_SD59x18`.
            /// - The result must fit within `MAX_SD59x18`.
            ///
            /// Caveats:
            /// - To understand how this works in detail, see the NatSpec comments in `Common.mulDivSigned`.
            ///
            /// @param x The multiplicand as an SD59x18 number.
            /// @param y The multiplier as an SD59x18 number.
            /// @return result The product as an SD59x18 number.
            function mul(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
                int256 xInt = unwrap(x);
                int256 yInt = unwrap(y);
                if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) {
                    revert PRBMath_SD59x18_Mul_InputTooSmall();
                }
                // Get hold of the absolute values of x and y.
                uint256 xAbs;
                uint256 yAbs;
                unchecked {
                    xAbs = xInt < 0 ? uint256(-xInt) : uint256(xInt);
                    yAbs = yInt < 0 ? uint256(-yInt) : uint256(yInt);
                }
                uint256 resultAbs = mulDiv18(xAbs, yAbs);
                if (resultAbs > uint256(uMAX_SD59x18)) {
                    revert PRBMath_SD59x18_Mul_Overflow(x, y);
                }
                // Check if x and y have the same sign. This works thanks to two's complement; the left-most bit is the sign bit.
                bool sameSign = (xInt ^ yInt) > -1;
                // If the inputs have the same sign, the result should be negative. Otherwise, it should be positive.
                unchecked {
                    result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs));
                }
            }
            /// @notice Raises x to the power of y.
            ///
            /// @dev Based on the formula:
            ///
            /// $$
            /// x^y = 2^{log_2{x} * y}
            /// $$
            ///
            /// Requirements:
            /// - All from `exp2`, `log2` and `mul`.
            /// - x cannot be zero.
            ///
            /// Caveats:
            /// - All from `exp2`, `log2` and `mul`.
            /// - Assumes 0^0 is 1.
            ///
            /// @param x Number to raise to given power y, as an SD59x18 number.
            /// @param y Exponent to raise x to, as an SD59x18 number
            /// @return result x raised to power y, as an SD59x18 number.
            function pow(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
                int256 xInt = unwrap(x);
                int256 yInt = unwrap(y);
                if (xInt == 0) {
                    result = yInt == 0 ? UNIT : ZERO;
                } else {
                    if (yInt == uUNIT) {
                        result = x;
                    } else {
                        result = exp2(mul(log2(x), y));
                    }
                }
            }
            /// @notice Raises x (an SD59x18 number) to the power y (unsigned basic integer) using the famous algorithm
            /// algorithm "exponentiation by squaring".
            ///
            /// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring
            ///
            /// Requirements:
            /// - All from `abs` and `Common.mulDiv18`.
            /// - The result must fit within `MAX_SD59x18`.
            ///
            /// Caveats:
            /// - All from `Common.mulDiv18`.
            /// - Assumes 0^0 is 1.
            ///
            /// @param x The base as an SD59x18 number.
            /// @param y The exponent as an uint256.
            /// @return result The result as an SD59x18 number.
            function powu(SD59x18 x, uint256 y) pure returns (SD59x18 result) {
                uint256 xAbs = uint256(unwrap(abs(x)));
                // Calculate the first iteration of the loop in advance.
                uint256 resultAbs = y & 1 > 0 ? xAbs : uint256(uUNIT);
                // Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster.
                uint256 yAux = y;
                for (yAux >>= 1; yAux > 0; yAux >>= 1) {
                    xAbs = mulDiv18(xAbs, xAbs);
                    // Equivalent to "y % 2 == 1" but faster.
                    if (yAux & 1 > 0) {
                        resultAbs = mulDiv18(resultAbs, xAbs);
                    }
                }
                // The result must fit within `MAX_SD59x18`.
                if (resultAbs > uint256(uMAX_SD59x18)) {
                    revert PRBMath_SD59x18_Powu_Overflow(x, y);
                }
                unchecked {
                    // Is the base negative and the exponent an odd number?
                    int256 resultInt = int256(resultAbs);
                    bool isNegative = unwrap(x) < 0 && y & 1 == 1;
                    if (isNegative) {
                        resultInt = -resultInt;
                    }
                    result = wrap(resultInt);
                }
            }
            /// @notice Calculates the square root of x, rounding down. Only the positive root is returned.
            /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
            ///
            /// Requirements:
            /// - x cannot be negative, since this library does not handle complex numbers.
            /// - x must be less than `MAX_SD59x18` divided by `UNIT`.
            ///
            /// @param x The SD59x18 number for which to calculate the square root.
            /// @return result The result as an SD59x18 number.
            function sqrt(SD59x18 x) pure returns (SD59x18 result) {
                int256 xInt = unwrap(x);
                if (xInt < 0) {
                    revert PRBMath_SD59x18_Sqrt_NegativeInput(x);
                }
                if (xInt > uMAX_SD59x18 / uUNIT) {
                    revert PRBMath_SD59x18_Sqrt_Overflow(x);
                }
                unchecked {
                    // Multiply x by `UNIT` to account for the factor of `UNIT` that is picked up when multiplying two SD59x18
                    // numbers together (in this case, the two numbers are both the square root).
                    uint256 resultUint = prbSqrt(uint256(xInt * uUNIT));
                    result = wrap(int256(resultUint));
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            import "./Casting.sol" as C;
            import "./Helpers.sol" as H;
            import "./Math.sol" as M;
            /// @notice The signed 59.18-decimal fixed-point number representation, which can have up to 59 digits and up to 18 decimals.
            /// The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity type int256.
            type SD59x18 is int256;
            /*//////////////////////////////////////////////////////////////////////////
                                                CASTING
            //////////////////////////////////////////////////////////////////////////*/
            using {
                C.intoInt256,
                C.intoSD1x18,
                C.intoUD2x18,
                C.intoUD60x18,
                C.intoUint256,
                C.intoUint128,
                C.intoUint40,
                C.unwrap
            } for SD59x18 global;
            /*//////////////////////////////////////////////////////////////////////////
                                        MATHEMATICAL FUNCTIONS
            //////////////////////////////////////////////////////////////////////////*/
            using {
                M.abs,
                M.avg,
                M.ceil,
                M.div,
                M.exp,
                M.exp2,
                M.floor,
                M.frac,
                M.gm,
                M.inv,
                M.log10,
                M.log2,
                M.ln,
                M.mul,
                M.pow,
                M.powu,
                M.sqrt
            } for SD59x18 global;
            /*//////////////////////////////////////////////////////////////////////////
                                            HELPER FUNCTIONS
            //////////////////////////////////////////////////////////////////////////*/
            using {
                H.add,
                H.and,
                H.eq,
                H.gt,
                H.gte,
                H.isZero,
                H.lshift,
                H.lt,
                H.lte,
                H.mod,
                H.neq,
                H.or,
                H.rshift,
                H.sub,
                H.uncheckedAdd,
                H.uncheckedSub,
                H.uncheckedUnary,
                H.xor
            } for SD59x18 global;
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            import { MAX_UINT40 } from "../Common.sol";
            import { uMAX_SD1x18 } from "../sd1x18/Constants.sol";
            import { SD1x18 } from "../sd1x18/ValueType.sol";
            import { SD59x18 } from "../sd59x18/ValueType.sol";
            import { UD2x18 } from "../ud2x18/ValueType.sol";
            import { UD60x18 } from "../ud60x18/ValueType.sol";
            import { PRBMath_UD2x18_IntoSD1x18_Overflow, PRBMath_UD2x18_IntoUint40_Overflow } from "./Errors.sol";
            import { UD2x18 } from "./ValueType.sol";
            /// @notice Casts an UD2x18 number into SD1x18.
            /// - x must be less than or equal to `uMAX_SD1x18`.
            function intoSD1x18(UD2x18 x) pure returns (SD1x18 result) {
                uint64 xUint = UD2x18.unwrap(x);
                if (xUint > uint64(uMAX_SD1x18)) {
                    revert PRBMath_UD2x18_IntoSD1x18_Overflow(x);
                }
                result = SD1x18.wrap(int64(xUint));
            }
            /// @notice Casts an UD2x18 number into SD59x18.
            /// @dev There is no overflow check because the domain of UD2x18 is a subset of SD59x18.
            function intoSD59x18(UD2x18 x) pure returns (SD59x18 result) {
                result = SD59x18.wrap(int256(uint256(UD2x18.unwrap(x))));
            }
            /// @notice Casts an UD2x18 number into UD60x18.
            /// @dev There is no overflow check because the domain of UD2x18 is a subset of UD60x18.
            function intoUD60x18(UD2x18 x) pure returns (UD60x18 result) {
                result = UD60x18.wrap(UD2x18.unwrap(x));
            }
            /// @notice Casts an UD2x18 number into uint128.
            /// @dev There is no overflow check because the domain of UD2x18 is a subset of uint128.
            function intoUint128(UD2x18 x) pure returns (uint128 result) {
                result = uint128(UD2x18.unwrap(x));
            }
            /// @notice Casts an UD2x18 number into uint256.
            /// @dev There is no overflow check because the domain of UD2x18 is a subset of uint256.
            function intoUint256(UD2x18 x) pure returns (uint256 result) {
                result = uint256(UD2x18.unwrap(x));
            }
            /// @notice Casts an UD2x18 number into uint40.
            /// @dev Requirements:
            /// - x must be less than or equal to `MAX_UINT40`.
            function intoUint40(UD2x18 x) pure returns (uint40 result) {
                uint64 xUint = UD2x18.unwrap(x);
                if (xUint > uint64(MAX_UINT40)) {
                    revert PRBMath_UD2x18_IntoUint40_Overflow(x);
                }
                result = uint40(xUint);
            }
            /// @notice Alias for the `wrap` function.
            function ud2x18(uint64 x) pure returns (UD2x18 result) {
                result = wrap(x);
            }
            /// @notice Unwrap an UD2x18 number into uint64.
            function unwrap(UD2x18 x) pure returns (uint64 result) {
                result = UD2x18.unwrap(x);
            }
            /// @notice Wraps an uint64 number into the UD2x18 value type.
            function wrap(uint64 x) pure returns (UD2x18 result) {
                result = UD2x18.wrap(x);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            import { UD2x18 } from "./ValueType.sol";
            /// @dev Euler's number as an UD2x18 number.
            UD2x18 constant E = UD2x18.wrap(2_718281828459045235);
            /// @dev The maximum value an UD2x18 number can have.
            uint64 constant uMAX_UD2x18 = 18_446744073709551615;
            UD2x18 constant MAX_UD2x18 = UD2x18.wrap(uMAX_UD2x18);
            /// @dev PI as an UD2x18 number.
            UD2x18 constant PI = UD2x18.wrap(3_141592653589793238);
            /// @dev The unit amount that implies how many trailing decimals can be represented.
            uint256 constant uUNIT = 1e18;
            UD2x18 constant UNIT = UD2x18.wrap(1e18);
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            import { UD2x18 } from "./ValueType.sol";
            /// @notice Emitted when trying to cast a UD2x18 number that doesn't fit in SD1x18.
            error PRBMath_UD2x18_IntoSD1x18_Overflow(UD2x18 x);
            /// @notice Emitted when trying to cast a UD2x18 number that doesn't fit in uint40.
            error PRBMath_UD2x18_IntoUint40_Overflow(UD2x18 x);
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            import "./Casting.sol" as C;
            /// @notice The unsigned 2.18-decimal fixed-point number representation, which can have up to 2 digits and up to 18 decimals.
            /// The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity type uint64.
            /// This is useful when end users want to use uint64 to save gas, e.g. with tight variable packing in contract storage.
            type UD2x18 is uint64;
            /*//////////////////////////////////////////////////////////////////////////
                                                CASTING
            //////////////////////////////////////////////////////////////////////////*/
            using { C.intoSD1x18, C.intoSD59x18, C.intoUD60x18, C.intoUint256, C.intoUint128, C.intoUint40, C.unwrap } for UD2x18 global;
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            import "./ud60x18/Casting.sol";
            import "./ud60x18/Constants.sol";
            import "./ud60x18/Conversions.sol";
            import "./ud60x18/Errors.sol";
            import "./ud60x18/Helpers.sol";
            import "./ud60x18/Math.sol";
            import "./ud60x18/ValueType.sol";
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            import { MAX_UINT128, MAX_UINT40 } from "../Common.sol";
            import { uMAX_SD1x18 } from "../sd1x18/Constants.sol";
            import { SD1x18 } from "../sd1x18/ValueType.sol";
            import { uMAX_SD59x18 } from "../sd59x18/Constants.sol";
            import { SD59x18 } from "../sd59x18/ValueType.sol";
            import { uMAX_UD2x18 } from "../ud2x18/Constants.sol";
            import { UD2x18 } from "../ud2x18/ValueType.sol";
            import {
                PRBMath_UD60x18_IntoSD1x18_Overflow,
                PRBMath_UD60x18_IntoUD2x18_Overflow,
                PRBMath_UD60x18_IntoSD59x18_Overflow,
                PRBMath_UD60x18_IntoUint128_Overflow,
                PRBMath_UD60x18_IntoUint40_Overflow
            } from "./Errors.sol";
            import { UD60x18 } from "./ValueType.sol";
            /// @notice Casts an UD60x18 number into SD1x18.
            /// @dev Requirements:
            /// - x must be less than or equal to `uMAX_SD1x18`.
            function intoSD1x18(UD60x18 x) pure returns (SD1x18 result) {
                uint256 xUint = UD60x18.unwrap(x);
                if (xUint > uint256(int256(uMAX_SD1x18))) {
                    revert PRBMath_UD60x18_IntoSD1x18_Overflow(x);
                }
                result = SD1x18.wrap(int64(uint64(xUint)));
            }
            /// @notice Casts an UD60x18 number into UD2x18.
            /// @dev Requirements:
            /// - x must be less than or equal to `uMAX_UD2x18`.
            function intoUD2x18(UD60x18 x) pure returns (UD2x18 result) {
                uint256 xUint = UD60x18.unwrap(x);
                if (xUint > uMAX_UD2x18) {
                    revert PRBMath_UD60x18_IntoUD2x18_Overflow(x);
                }
                result = UD2x18.wrap(uint64(xUint));
            }
            /// @notice Casts an UD60x18 number into SD59x18.
            /// @dev Requirements:
            /// - x must be less than or equal to `uMAX_SD59x18`.
            function intoSD59x18(UD60x18 x) pure returns (SD59x18 result) {
                uint256 xUint = UD60x18.unwrap(x);
                if (xUint > uint256(uMAX_SD59x18)) {
                    revert PRBMath_UD60x18_IntoSD59x18_Overflow(x);
                }
                result = SD59x18.wrap(int256(xUint));
            }
            /// @notice Casts an UD60x18 number into uint128.
            /// @dev This is basically a functional alias for the `unwrap` function.
            function intoUint256(UD60x18 x) pure returns (uint256 result) {
                result = UD60x18.unwrap(x);
            }
            /// @notice Casts an UD60x18 number into uint128.
            /// @dev Requirements:
            /// - x must be less than or equal to `MAX_UINT128`.
            function intoUint128(UD60x18 x) pure returns (uint128 result) {
                uint256 xUint = UD60x18.unwrap(x);
                if (xUint > MAX_UINT128) {
                    revert PRBMath_UD60x18_IntoUint128_Overflow(x);
                }
                result = uint128(xUint);
            }
            /// @notice Casts an UD60x18 number into uint40.
            /// @dev Requirements:
            /// - x must be less than or equal to `MAX_UINT40`.
            function intoUint40(UD60x18 x) pure returns (uint40 result) {
                uint256 xUint = UD60x18.unwrap(x);
                if (xUint > MAX_UINT40) {
                    revert PRBMath_UD60x18_IntoUint40_Overflow(x);
                }
                result = uint40(xUint);
            }
            /// @notice Alias for the `wrap` function.
            function ud(uint256 x) pure returns (UD60x18 result) {
                result = wrap(x);
            }
            /// @notice Alias for the `wrap` function.
            function ud60x18(uint256 x) pure returns (UD60x18 result) {
                result = wrap(x);
            }
            /// @notice Unwraps an UD60x18 number into uint256.
            function unwrap(UD60x18 x) pure returns (uint256 result) {
                result = UD60x18.unwrap(x);
            }
            /// @notice Wraps an uint256 number into the UD60x18 value type.
            function wrap(uint256 x) pure returns (UD60x18 result) {
                result = UD60x18.wrap(x);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            import { UD60x18 } from "./ValueType.sol";
            /// @dev Euler's number as an UD60x18 number.
            UD60x18 constant E = UD60x18.wrap(2_718281828459045235);
            /// @dev Half the UNIT number.
            uint256 constant uHALF_UNIT = 0.5e18;
            UD60x18 constant HALF_UNIT = UD60x18.wrap(uHALF_UNIT);
            /// @dev log2(10) as an UD60x18 number.
            uint256 constant uLOG2_10 = 3_321928094887362347;
            UD60x18 constant LOG2_10 = UD60x18.wrap(uLOG2_10);
            /// @dev log2(e) as an UD60x18 number.
            uint256 constant uLOG2_E = 1_442695040888963407;
            UD60x18 constant LOG2_E = UD60x18.wrap(uLOG2_E);
            /// @dev The maximum value an UD60x18 number can have.
            uint256 constant uMAX_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_584007913129639935;
            UD60x18 constant MAX_UD60x18 = UD60x18.wrap(uMAX_UD60x18);
            /// @dev The maximum whole value an UD60x18 number can have.
            uint256 constant uMAX_WHOLE_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_000000000000000000;
            UD60x18 constant MAX_WHOLE_UD60x18 = UD60x18.wrap(uMAX_WHOLE_UD60x18);
            /// @dev PI as an UD60x18 number.
            UD60x18 constant PI = UD60x18.wrap(3_141592653589793238);
            /// @dev The unit amount that implies how many trailing decimals can be represented.
            uint256 constant uUNIT = 1e18;
            UD60x18 constant UNIT = UD60x18.wrap(uUNIT);
            /// @dev Zero as an UD60x18 number.
            UD60x18 constant ZERO = UD60x18.wrap(0);
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            import { uMAX_UD60x18, uUNIT } from "./Constants.sol";
            import { PRBMath_UD60x18_Convert_Overflow } from "./Errors.sol";
            import { UD60x18 } from "./ValueType.sol";
            /// @notice Converts an UD60x18 number to a simple integer by dividing it by `UNIT`. Rounds towards zero in the process.
            /// @dev Rounds down in the process.
            /// @param x The UD60x18 number to convert.
            /// @return result The same number in basic integer form.
            function convert(UD60x18 x) pure returns (uint256 result) {
                result = UD60x18.unwrap(x) / uUNIT;
            }
            /// @notice Converts a simple integer to UD60x18 by multiplying it by `UNIT`.
            ///
            /// @dev Requirements:
            /// - x must be less than or equal to `MAX_UD60x18` divided by `UNIT`.
            ///
            /// @param x The basic integer to convert.
            /// @param result The same number converted to UD60x18.
            function convert(uint256 x) pure returns (UD60x18 result) {
                if (x > uMAX_UD60x18 / uUNIT) {
                    revert PRBMath_UD60x18_Convert_Overflow(x);
                }
                unchecked {
                    result = UD60x18.wrap(x * uUNIT);
                }
            }
            /// @notice Alias for the `convert` function defined above.
            /// @dev Here for backward compatibility. Will be removed in V4.
            function fromUD60x18(UD60x18 x) pure returns (uint256 result) {
                result = convert(x);
            }
            /// @notice Alias for the `convert` function defined above.
            /// @dev Here for backward compatibility. Will be removed in V4.
            function toUD60x18(uint256 x) pure returns (UD60x18 result) {
                result = convert(x);
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            import { UD60x18 } from "./ValueType.sol";
            /// @notice Emitted when ceiling a number overflows UD60x18.
            error PRBMath_UD60x18_Ceil_Overflow(UD60x18 x);
            /// @notice Emitted when converting a basic integer to the fixed-point format overflows UD60x18.
            error PRBMath_UD60x18_Convert_Overflow(uint256 x);
            /// @notice Emitted when taking the natural exponent of a base greater than 133.084258667509499441.
            error PRBMath_UD60x18_Exp_InputTooBig(UD60x18 x);
            /// @notice Emitted when taking the binary exponent of a base greater than 192.
            error PRBMath_UD60x18_Exp2_InputTooBig(UD60x18 x);
            /// @notice Emitted when taking the geometric mean of two numbers and multiplying them overflows UD60x18.
            error PRBMath_UD60x18_Gm_Overflow(UD60x18 x, UD60x18 y);
            /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in SD1x18.
            error PRBMath_UD60x18_IntoSD1x18_Overflow(UD60x18 x);
            /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in SD59x18.
            error PRBMath_UD60x18_IntoSD59x18_Overflow(UD60x18 x);
            /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in UD2x18.
            error PRBMath_UD60x18_IntoUD2x18_Overflow(UD60x18 x);
            /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in uint128.
            error PRBMath_UD60x18_IntoUint128_Overflow(UD60x18 x);
            /// @notice Emitted when trying to cast an UD60x18 number that doesn't fit in uint40.
            error PRBMath_UD60x18_IntoUint40_Overflow(UD60x18 x);
            /// @notice Emitted when taking the logarithm of a number less than 1.
            error PRBMath_UD60x18_Log_InputTooSmall(UD60x18 x);
            /// @notice Emitted when calculating the square root overflows UD60x18.
            error PRBMath_UD60x18_Sqrt_Overflow(UD60x18 x);
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            import { unwrap, wrap } from "./Casting.sol";
            import { UD60x18 } from "./ValueType.sol";
            /// @notice Implements the checked addition operation (+) in the UD60x18 type.
            function add(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
                result = wrap(unwrap(x) + unwrap(y));
            }
            /// @notice Implements the AND (&) bitwise operation in the UD60x18 type.
            function and(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
                result = wrap(unwrap(x) & bits);
            }
            /// @notice Implements the equal operation (==) in the UD60x18 type.
            function eq(UD60x18 x, UD60x18 y) pure returns (bool result) {
                result = unwrap(x) == unwrap(y);
            }
            /// @notice Implements the greater than operation (>) in the UD60x18 type.
            function gt(UD60x18 x, UD60x18 y) pure returns (bool result) {
                result = unwrap(x) > unwrap(y);
            }
            /// @notice Implements the greater than or equal to operation (>=) in the UD60x18 type.
            function gte(UD60x18 x, UD60x18 y) pure returns (bool result) {
                result = unwrap(x) >= unwrap(y);
            }
            /// @notice Implements a zero comparison check function in the UD60x18 type.
            function isZero(UD60x18 x) pure returns (bool result) {
                // This wouldn't work if x could be negative.
                result = unwrap(x) == 0;
            }
            /// @notice Implements the left shift operation (<<) in the UD60x18 type.
            function lshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
                result = wrap(unwrap(x) << bits);
            }
            /// @notice Implements the lower than operation (<) in the UD60x18 type.
            function lt(UD60x18 x, UD60x18 y) pure returns (bool result) {
                result = unwrap(x) < unwrap(y);
            }
            /// @notice Implements the lower than or equal to operation (<=) in the UD60x18 type.
            function lte(UD60x18 x, UD60x18 y) pure returns (bool result) {
                result = unwrap(x) <= unwrap(y);
            }
            /// @notice Implements the checked modulo operation (%) in the UD60x18 type.
            function mod(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
                result = wrap(unwrap(x) % unwrap(y));
            }
            /// @notice Implements the not equal operation (!=) in the UD60x18 type
            function neq(UD60x18 x, UD60x18 y) pure returns (bool result) {
                result = unwrap(x) != unwrap(y);
            }
            /// @notice Implements the OR (|) bitwise operation in the UD60x18 type.
            function or(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
                result = wrap(unwrap(x) | unwrap(y));
            }
            /// @notice Implements the right shift operation (>>) in the UD60x18 type.
            function rshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
                result = wrap(unwrap(x) >> bits);
            }
            /// @notice Implements the checked subtraction operation (-) in the UD60x18 type.
            function sub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
                result = wrap(unwrap(x) - unwrap(y));
            }
            /// @notice Implements the unchecked addition operation (+) in the UD60x18 type.
            function uncheckedAdd(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
                unchecked {
                    result = wrap(unwrap(x) + unwrap(y));
                }
            }
            /// @notice Implements the unchecked subtraction operation (-) in the UD60x18 type.
            function uncheckedSub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
                unchecked {
                    result = wrap(unwrap(x) - unwrap(y));
                }
            }
            /// @notice Implements the XOR (^) bitwise operation in the UD60x18 type.
            function xor(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
                result = wrap(unwrap(x) ^ unwrap(y));
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            import { msb, mulDiv, mulDiv18, prbExp2, prbSqrt } from "../Common.sol";
            import { unwrap, wrap } from "./Casting.sol";
            import { uHALF_UNIT, uLOG2_10, uLOG2_E, uMAX_UD60x18, uMAX_WHOLE_UD60x18, UNIT, uUNIT, ZERO } from "./Constants.sol";
            import {
                PRBMath_UD60x18_Ceil_Overflow,
                PRBMath_UD60x18_Exp_InputTooBig,
                PRBMath_UD60x18_Exp2_InputTooBig,
                PRBMath_UD60x18_Gm_Overflow,
                PRBMath_UD60x18_Log_InputTooSmall,
                PRBMath_UD60x18_Sqrt_Overflow
            } from "./Errors.sol";
            import { UD60x18 } from "./ValueType.sol";
            /*//////////////////////////////////////////////////////////////////////////
                                        MATHEMATICAL FUNCTIONS
            //////////////////////////////////////////////////////////////////////////*/
            /// @notice Calculates the arithmetic average of x and y, rounding down.
            ///
            /// @dev Based on the formula:
            ///
            /// $$
            /// avg(x, y) = (x & y) + ((xUint ^ yUint) / 2)
            /// $$
            //
            /// In English, what this formula does is:
            ///
            /// 1. AND x and y.
            /// 2. Calculate half of XOR x and y.
            /// 3. Add the two results together.
            ///
            /// This technique is known as SWAR, which stands for "SIMD within a register". You can read more about it here:
            /// https://devblogs.microsoft.com/oldnewthing/20220207-00/?p=106223
            ///
            /// @param x The first operand as an UD60x18 number.
            /// @param y The second operand as an UD60x18 number.
            /// @return result The arithmetic average as an UD60x18 number.
            function avg(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
                uint256 xUint = unwrap(x);
                uint256 yUint = unwrap(y);
                unchecked {
                    result = wrap((xUint & yUint) + ((xUint ^ yUint) >> 1));
                }
            }
            /// @notice Yields the smallest whole UD60x18 number greater than or equal to x.
            ///
            /// @dev This is optimized for fractional value inputs, because for every whole value there are "1e18 - 1" fractional
            /// counterparts. See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
            ///
            /// Requirements:
            /// - x must be less than or equal to `MAX_WHOLE_UD60x18`.
            ///
            /// @param x The UD60x18 number to ceil.
            /// @param result The least number greater than or equal to x, as an UD60x18 number.
            function ceil(UD60x18 x) pure returns (UD60x18 result) {
                uint256 xUint = unwrap(x);
                if (xUint > uMAX_WHOLE_UD60x18) {
                    revert PRBMath_UD60x18_Ceil_Overflow(x);
                }
                assembly ("memory-safe") {
                    // Equivalent to "x % UNIT" but faster.
                    let remainder := mod(x, uUNIT)
                    // Equivalent to "UNIT - remainder" but faster.
                    let delta := sub(uUNIT, remainder)
                    // Equivalent to "x + delta * (remainder > 0 ? 1 : 0)" but faster.
                    result := add(x, mul(delta, gt(remainder, 0)))
                }
            }
            /// @notice Divides two UD60x18 numbers, returning a new UD60x18 number. Rounds towards zero.
            ///
            /// @dev Uses `mulDiv` to enable overflow-safe multiplication and division.
            ///
            /// Requirements:
            /// - The denominator cannot be zero.
            ///
            /// @param x The numerator as an UD60x18 number.
            /// @param y The denominator as an UD60x18 number.
            /// @param result The quotient as an UD60x18 number.
            function div(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
                result = wrap(mulDiv(unwrap(x), uUNIT, unwrap(y)));
            }
            /// @notice Calculates the natural exponent of x.
            ///
            /// @dev Based on the formula:
            ///
            /// $$
            /// e^x = 2^{x * log_2{e}}
            /// $$
            ///
            /// Requirements:
            /// - All from `log2`.
            /// - x must be less than 133.084258667509499441.
            ///
            /// @param x The exponent as an UD60x18 number.
            /// @return result The result as an UD60x18 number.
            function exp(UD60x18 x) pure returns (UD60x18 result) {
                uint256 xUint = unwrap(x);
                // Without this check, the value passed to `exp2` would be greater than 192.
                if (xUint >= 133_084258667509499441) {
                    revert PRBMath_UD60x18_Exp_InputTooBig(x);
                }
                unchecked {
                    // We do the fixed-point multiplication inline rather than via the `mul` function to save gas.
                    uint256 doubleUnitProduct = xUint * uLOG2_E;
                    result = exp2(wrap(doubleUnitProduct / uUNIT));
                }
            }
            /// @notice Calculates the binary exponent of x using the binary fraction method.
            ///
            /// @dev See https://ethereum.stackexchange.com/q/79903/24693.
            ///
            /// Requirements:
            /// - x must be 192 or less.
            /// - The result must fit within `MAX_UD60x18`.
            ///
            /// @param x The exponent as an UD60x18 number.
            /// @return result The result as an UD60x18 number.
            function exp2(UD60x18 x) pure returns (UD60x18 result) {
                uint256 xUint = unwrap(x);
                // Numbers greater than or equal to 2^192 don't fit within the 192.64-bit format.
                if (xUint >= 192e18) {
                    revert PRBMath_UD60x18_Exp2_InputTooBig(x);
                }
                // Convert x to the 192.64-bit fixed-point format.
                uint256 x_192x64 = (xUint << 64) / uUNIT;
                // Pass x to the `prbExp2` function, which uses the 192.64-bit fixed-point number representation.
                result = wrap(prbExp2(x_192x64));
            }
            /// @notice Yields the greatest whole UD60x18 number less than or equal to x.
            /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.
            /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
            /// @param x The UD60x18 number to floor.
            /// @param result The greatest integer less than or equal to x, as an UD60x18 number.
            function floor(UD60x18 x) pure returns (UD60x18 result) {
                assembly ("memory-safe") {
                    // Equivalent to "x % UNIT" but faster.
                    let remainder := mod(x, uUNIT)
                    // Equivalent to "x - remainder * (remainder > 0 ? 1 : 0)" but faster.
                    result := sub(x, mul(remainder, gt(remainder, 0)))
                }
            }
            /// @notice Yields the excess beyond the floor of x.
            /// @dev Based on the odd function definition https://en.wikipedia.org/wiki/Fractional_part.
            /// @param x The UD60x18 number to get the fractional part of.
            /// @param result The fractional part of x as an UD60x18 number.
            function frac(UD60x18 x) pure returns (UD60x18 result) {
                assembly ("memory-safe") {
                    result := mod(x, uUNIT)
                }
            }
            /// @notice Calculates the geometric mean of x and y, i.e. $$sqrt(x * y)$$, rounding down.
            ///
            /// @dev Requirements:
            /// - x * y must fit within `MAX_UD60x18`, lest it overflows.
            ///
            /// @param x The first operand as an UD60x18 number.
            /// @param y The second operand as an UD60x18 number.
            /// @return result The result as an UD60x18 number.
            function gm(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
                uint256 xUint = unwrap(x);
                uint256 yUint = unwrap(y);
                if (xUint == 0 || yUint == 0) {
                    return ZERO;
                }
                unchecked {
                    // Checking for overflow this way is faster than letting Solidity do it.
                    uint256 xyUint = xUint * yUint;
                    if (xyUint / xUint != yUint) {
                        revert PRBMath_UD60x18_Gm_Overflow(x, y);
                    }
                    // We don't need to multiply the result by `UNIT` here because the x*y product had picked up a factor of `UNIT`
                    // during multiplication. See the comments in the `prbSqrt` function.
                    result = wrap(prbSqrt(xyUint));
                }
            }
            /// @notice Calculates 1 / x, rounding toward zero.
            ///
            /// @dev Requirements:
            /// - x cannot be zero.
            ///
            /// @param x The UD60x18 number for which to calculate the inverse.
            /// @return result The inverse as an UD60x18 number.
            function inv(UD60x18 x) pure returns (UD60x18 result) {
                unchecked {
                    // 1e36 is UNIT * UNIT.
                    result = wrap(1e36 / unwrap(x));
                }
            }
            /// @notice Calculates the natural logarithm of x.
            ///
            /// @dev Based on the formula:
            ///
            /// $$
            /// ln{x} = log_2{x} / log_2{e}$$.
            /// $$
            ///
            /// Requirements:
            /// - All from `log2`.
            ///
            /// Caveats:
            /// - All from `log2`.
            /// - This doesn't return exactly 1 for 2.718281828459045235, for that more fine-grained precision is needed.
            ///
            /// @param x The UD60x18 number for which to calculate the natural logarithm.
            /// @return result The natural logarithm as an UD60x18 number.
            function ln(UD60x18 x) pure returns (UD60x18 result) {
                unchecked {
                    // We do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value
                    // that `log2` can return is 196.205294292027477728.
                    result = wrap((unwrap(log2(x)) * uUNIT) / uLOG2_E);
                }
            }
            /// @notice Calculates the common logarithm of x.
            ///
            /// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common
            /// logarithm based on the formula:
            ///
            /// $$
            /// log_{10}{x} = log_2{x} / log_2{10}
            /// $$
            ///
            /// Requirements:
            /// - All from `log2`.
            ///
            /// Caveats:
            /// - All from `log2`.
            ///
            /// @param x The UD60x18 number for which to calculate the common logarithm.
            /// @return result The common logarithm as an UD60x18 number.
            function log10(UD60x18 x) pure returns (UD60x18 result) {
                uint256 xUint = unwrap(x);
                if (xUint < uUNIT) {
                    revert PRBMath_UD60x18_Log_InputTooSmall(x);
                }
                // Note that the `mul` in this assembly block is the assembly multiplication operation, not the UD60x18 `mul`.
                // prettier-ignore
                assembly ("memory-safe") {
                    switch x
                    case 1 { result := mul(uUNIT, sub(0, 18)) }
                    case 10 { result := mul(uUNIT, sub(1, 18)) }
                    case 100 { result := mul(uUNIT, sub(2, 18)) }
                    case 1000 { result := mul(uUNIT, sub(3, 18)) }
                    case 10000 { result := mul(uUNIT, sub(4, 18)) }
                    case 100000 { result := mul(uUNIT, sub(5, 18)) }
                    case 1000000 { result := mul(uUNIT, sub(6, 18)) }
                    case 10000000 { result := mul(uUNIT, sub(7, 18)) }
                    case 100000000 { result := mul(uUNIT, sub(8, 18)) }
                    case 1000000000 { result := mul(uUNIT, sub(9, 18)) }
                    case 10000000000 { result := mul(uUNIT, sub(10, 18)) }
                    case 100000000000 { result := mul(uUNIT, sub(11, 18)) }
                    case 1000000000000 { result := mul(uUNIT, sub(12, 18)) }
                    case 10000000000000 { result := mul(uUNIT, sub(13, 18)) }
                    case 100000000000000 { result := mul(uUNIT, sub(14, 18)) }
                    case 1000000000000000 { result := mul(uUNIT, sub(15, 18)) }
                    case 10000000000000000 { result := mul(uUNIT, sub(16, 18)) }
                    case 100000000000000000 { result := mul(uUNIT, sub(17, 18)) }
                    case 1000000000000000000 { result := 0 }
                    case 10000000000000000000 { result := uUNIT }
                    case 100000000000000000000 { result := mul(uUNIT, 2) }
                    case 1000000000000000000000 { result := mul(uUNIT, 3) }
                    case 10000000000000000000000 { result := mul(uUNIT, 4) }
                    case 100000000000000000000000 { result := mul(uUNIT, 5) }
                    case 1000000000000000000000000 { result := mul(uUNIT, 6) }
                    case 10000000000000000000000000 { result := mul(uUNIT, 7) }
                    case 100000000000000000000000000 { result := mul(uUNIT, 8) }
                    case 1000000000000000000000000000 { result := mul(uUNIT, 9) }
                    case 10000000000000000000000000000 { result := mul(uUNIT, 10) }
                    case 100000000000000000000000000000 { result := mul(uUNIT, 11) }
                    case 1000000000000000000000000000000 { result := mul(uUNIT, 12) }
                    case 10000000000000000000000000000000 { result := mul(uUNIT, 13) }
                    case 100000000000000000000000000000000 { result := mul(uUNIT, 14) }
                    case 1000000000000000000000000000000000 { result := mul(uUNIT, 15) }
                    case 10000000000000000000000000000000000 { result := mul(uUNIT, 16) }
                    case 100000000000000000000000000000000000 { result := mul(uUNIT, 17) }
                    case 1000000000000000000000000000000000000 { result := mul(uUNIT, 18) }
                    case 10000000000000000000000000000000000000 { result := mul(uUNIT, 19) }
                    case 100000000000000000000000000000000000000 { result := mul(uUNIT, 20) }
                    case 1000000000000000000000000000000000000000 { result := mul(uUNIT, 21) }
                    case 10000000000000000000000000000000000000000 { result := mul(uUNIT, 22) }
                    case 100000000000000000000000000000000000000000 { result := mul(uUNIT, 23) }
                    case 1000000000000000000000000000000000000000000 { result := mul(uUNIT, 24) }
                    case 10000000000000000000000000000000000000000000 { result := mul(uUNIT, 25) }
                    case 100000000000000000000000000000000000000000000 { result := mul(uUNIT, 26) }
                    case 1000000000000000000000000000000000000000000000 { result := mul(uUNIT, 27) }
                    case 10000000000000000000000000000000000000000000000 { result := mul(uUNIT, 28) }
                    case 100000000000000000000000000000000000000000000000 { result := mul(uUNIT, 29) }
                    case 1000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 30) }
                    case 10000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 31) }
                    case 100000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 32) }
                    case 1000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 33) }
                    case 10000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 34) }
                    case 100000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 35) }
                    case 1000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 36) }
                    case 10000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 37) }
                    case 100000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 38) }
                    case 1000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 39) }
                    case 10000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 40) }
                    case 100000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 41) }
                    case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 42) }
                    case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 43) }
                    case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 44) }
                    case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 45) }
                    case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 46) }
                    case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 47) }
                    case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 48) }
                    case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 49) }
                    case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 50) }
                    case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 51) }
                    case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 52) }
                    case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 53) }
                    case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 54) }
                    case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 55) }
                    case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 56) }
                    case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 57) }
                    case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 58) }
                    case 100000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 59) }
                    default {
                        result := uMAX_UD60x18
                    }
                }
                if (unwrap(result) == uMAX_UD60x18) {
                    unchecked {
                        // Do the fixed-point division inline to save gas.
                        result = wrap((unwrap(log2(x)) * uUNIT) / uLOG2_10);
                    }
                }
            }
            /// @notice Calculates the binary logarithm of x.
            ///
            /// @dev Based on the iterative approximation algorithm.
            /// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation
            ///
            /// Requirements:
            /// - x must be greater than or equal to UNIT, otherwise the result would be negative.
            ///
            /// Caveats:
            /// - The results are nor perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation.
            ///
            /// @param x The UD60x18 number for which to calculate the binary logarithm.
            /// @return result The binary logarithm as an UD60x18 number.
            function log2(UD60x18 x) pure returns (UD60x18 result) {
                uint256 xUint = unwrap(x);
                if (xUint < uUNIT) {
                    revert PRBMath_UD60x18_Log_InputTooSmall(x);
                }
                unchecked {
                    // Calculate the integer part of the logarithm, add it to the result and finally calculate y = x * 2^(-n).
                    uint256 n = msb(xUint / uUNIT);
                    // This is the integer part of the logarithm as an UD60x18 number. The operation can't overflow because n
                    // n is maximum 255 and UNIT is 1e18.
                    uint256 resultUint = n * uUNIT;
                    // This is $y = x * 2^{-n}$.
                    uint256 y = xUint >> n;
                    // If y is 1, the fractional part is zero.
                    if (y == uUNIT) {
                        return wrap(resultUint);
                    }
                    // Calculate the fractional part via the iterative approximation.
                    // The "delta.rshift(1)" part is equivalent to "delta /= 2", but shifting bits is faster.
                    uint256 DOUBLE_UNIT = 2e18;
                    for (uint256 delta = uHALF_UNIT; delta > 0; delta >>= 1) {
                        y = (y * y) / uUNIT;
                        // Is y^2 > 2 and so in the range [2,4)?
                        if (y >= DOUBLE_UNIT) {
                            // Add the 2^{-m} factor to the logarithm.
                            resultUint += delta;
                            // Corresponds to z/2 on Wikipedia.
                            y >>= 1;
                        }
                    }
                    result = wrap(resultUint);
                }
            }
            /// @notice Multiplies two UD60x18 numbers together, returning a new UD60x18 number.
            /// @dev See the documentation for the `Common.mulDiv18` function.
            /// @param x The multiplicand as an UD60x18 number.
            /// @param y The multiplier as an UD60x18 number.
            /// @return result The product as an UD60x18 number.
            function mul(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
                result = wrap(mulDiv18(unwrap(x), unwrap(y)));
            }
            /// @notice Raises x to the power of y.
            ///
            /// @dev Based on the formula:
            ///
            /// $$
            /// x^y = 2^{log_2{x} * y}
            /// $$
            ///
            /// Requirements:
            /// - All from `exp2`, `log2` and `mul`.
            ///
            /// Caveats:
            /// - All from `exp2`, `log2` and `mul`.
            /// - Assumes 0^0 is 1.
            ///
            /// @param x Number to raise to given power y, as an UD60x18 number.
            /// @param y Exponent to raise x to, as an UD60x18 number.
            /// @return result x raised to power y, as an UD60x18 number.
            function pow(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
                uint256 xUint = unwrap(x);
                uint256 yUint = unwrap(y);
                if (xUint == 0) {
                    result = yUint == 0 ? UNIT : ZERO;
                } else {
                    if (yUint == uUNIT) {
                        result = x;
                    } else {
                        result = exp2(mul(log2(x), y));
                    }
                }
            }
            /// @notice Raises x (an UD60x18 number) to the power y (unsigned basic integer) using the famous algorithm
            /// "exponentiation by squaring".
            ///
            /// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring
            ///
            /// Requirements:
            /// - The result must fit within `MAX_UD60x18`.
            ///
            /// Caveats:
            /// - All from "Common.mulDiv18".
            /// - Assumes 0^0 is 1.
            ///
            /// @param x The base as an UD60x18 number.
            /// @param y The exponent as an uint256.
            /// @return result The result as an UD60x18 number.
            function powu(UD60x18 x, uint256 y) pure returns (UD60x18 result) {
                // Calculate the first iteration of the loop in advance.
                uint256 xUint = unwrap(x);
                uint256 resultUint = y & 1 > 0 ? xUint : uUNIT;
                // Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster.
                for (y >>= 1; y > 0; y >>= 1) {
                    xUint = mulDiv18(xUint, xUint);
                    // Equivalent to "y % 2 == 1" but faster.
                    if (y & 1 > 0) {
                        resultUint = mulDiv18(resultUint, xUint);
                    }
                }
                result = wrap(resultUint);
            }
            /// @notice Calculates the square root of x, rounding down.
            /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
            ///
            /// Requirements:
            /// - x must be less than `MAX_UD60x18` divided by `UNIT`.
            ///
            /// @param x The UD60x18 number for which to calculate the square root.
            /// @return result The result as an UD60x18 number.
            function sqrt(UD60x18 x) pure returns (UD60x18 result) {
                uint256 xUint = unwrap(x);
                unchecked {
                    if (xUint > uMAX_UD60x18 / uUNIT) {
                        revert PRBMath_UD60x18_Sqrt_Overflow(x);
                    }
                    // Multiply x by `UNIT` to account for the factor of `UNIT` that is picked up when multiplying two UD60x18
                    // numbers together (in this case, the two numbers are both the square root).
                    result = wrap(prbSqrt(xUint * uUNIT));
                }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity >=0.8.13;
            import "./Casting.sol" as C;
            import "./Helpers.sol" as H;
            import "./Math.sol" as M;
            /// @notice The unsigned 60.18-decimal fixed-point number representation, which can have up to 60 digits and up to 18 decimals.
            /// The values of this are bound by the minimum and the maximum values permitted by the Solidity type uint256.
            /// @dev The value type is defined here so it can be imported in all other files.
            type UD60x18 is uint256;
            /*//////////////////////////////////////////////////////////////////////////
                                                CASTING
            //////////////////////////////////////////////////////////////////////////*/
            using { C.intoSD1x18, C.intoUD2x18, C.intoSD59x18, C.intoUint128, C.intoUint256, C.intoUint40, C.unwrap } for UD60x18 global;
            /*//////////////////////////////////////////////////////////////////////////
                                        MATHEMATICAL FUNCTIONS
            //////////////////////////////////////////////////////////////////////////*/
            /// The global "using for" directive makes the functions in this library callable on the UD60x18 type.
            using {
                M.avg,
                M.ceil,
                M.div,
                M.exp,
                M.exp2,
                M.floor,
                M.frac,
                M.gm,
                M.inv,
                M.ln,
                M.log10,
                M.log2,
                M.mul,
                M.pow,
                M.powu,
                M.sqrt
            } for UD60x18 global;
            /*//////////////////////////////////////////////////////////////////////////
                                            HELPER FUNCTIONS
            //////////////////////////////////////////////////////////////////////////*/
            /// The global "using for" directive makes the functions in this library callable on the UD60x18 type.
            using {
                H.add,
                H.and,
                H.eq,
                H.gt,
                H.gte,
                H.isZero,
                H.lshift,
                H.lt,
                H.lte,
                H.mod,
                H.neq,
                H.or,
                H.rshift,
                H.sub,
                H.uncheckedAdd,
                H.uncheckedSub,
                H.xor
            } for UD60x18 global;
            // SPDX-License-Identifier: UNLICENSED
            pragma solidity 0.8.16;
            import {UD60x18, wrap} from "@prb/math/src/UD60x18.sol";
            import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
            import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
            import {AddressUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
            import {EnumerableSetUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
            import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
            import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
            import {Whitelist} from "./Whitelist.sol";
            import {SwellLib} from "../libraries/SwellLib.sol";
            import {IswETH} from "../interfaces/IswETH.sol";
            import {IAccessControlManager} from "../interfaces/IAccessControlManager.sol";
            import {INodeOperatorRegistry} from "../interfaces/INodeOperatorRegistry.sol";
            import {IRateProvider} from "../vendors/IRateProvider.sol";
            /**
             * @title swETH
             * @notice Contract for handling user deposits in ETH in exchange for swETH at the stored rate. Also handles the rate updates from the BOT wallet which will occur at a fixed interval.
             * @author https://github.com/max-taylor
             * @dev This contract inherits the Whitelist contract which holds the Access control manager state variable and the checkRole modifier
             */
            contract swETH is
              Initializable,
              Whitelist,
              IswETH,
              IRateProvider,
              ERC20Upgradeable
            {
              using SafeERC20 for IERC20;
              using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
              uint256 public override lastRepriceETHReserves;
              uint256 private swETHToETHRateFixed;
              uint256 public override swellTreasuryRewardPercentage;
              uint256 public override nodeOperatorRewardPercentage;
              uint256 public override lastRepriceUNIX;
              uint256 public override totalETHDeposited;
              uint256 public override minimumRepriceTime;
              uint256 public override maximumRepriceDifferencePercentage;
              uint256 public override maximumRepriceswETHDifferencePercentage;
              /// @custom:oz-upgrades-unsafe-allow constructor
              constructor() {
                _disableInitializers();
              }
              fallback() external {
                revert SwellLib.InvalidMethodCall();
              }
              function initialize(
                IAccessControlManager _accessControlManager
              ) external initializer checkZeroAddress(address(_accessControlManager)) {
                __ERC20_init("swETH", "swETH");
                __Whitelist_init(_accessControlManager);
              }
              // ************************************
              // ***** External methods ******
              function withdrawERC20(
                IERC20 _token
              ) external override checkRole(SwellLib.PLATFORM_ADMIN) {
                uint256 contractBalance = _token.balanceOf(address(this));
                if (contractBalance == 0) {
                  revert SwellLib.NoTokensToWithdraw();
                }
                _token.safeTransfer(msg.sender, contractBalance);
              }
              function setSwellTreasuryRewardPercentage(
                uint256 _newSwellTreasuryRewardPercentage
              ) external override checkRole(SwellLib.PLATFORM_ADMIN) {
                // Joined percentage total cannot exeed 100% (1 ether)
                if (
                  nodeOperatorRewardPercentage + _newSwellTreasuryRewardPercentage > 1 ether
                ) {
                  revert RewardPercentageTotalOverflow();
                }
                emit SwellTreasuryRewardPercentageUpdate(
                  swellTreasuryRewardPercentage,
                  _newSwellTreasuryRewardPercentage
                );
                swellTreasuryRewardPercentage = _newSwellTreasuryRewardPercentage;
              }
              function setNodeOperatorRewardPercentage(
                uint256 _newNodeOperatorRewardPercentage
              ) external override checkRole(SwellLib.PLATFORM_ADMIN) {
                // Joined percentage total cannot exeed 100% (1 ether)
                if (
                  swellTreasuryRewardPercentage + _newNodeOperatorRewardPercentage > 1 ether
                ) {
                  revert RewardPercentageTotalOverflow();
                }
                emit NodeOperatorRewardPercentageUpdate(
                  nodeOperatorRewardPercentage,
                  _newNodeOperatorRewardPercentage
                );
                nodeOperatorRewardPercentage = _newNodeOperatorRewardPercentage;
              }
              function setMinimumRepriceTime(
                uint256 _minimumRepriceTime
              ) external checkRole(SwellLib.PLATFORM_ADMIN) {
                emit MinimumRepriceTimeUpdated(minimumRepriceTime, _minimumRepriceTime);
                minimumRepriceTime = _minimumRepriceTime;
              }
              function setMaximumRepriceswETHDifferencePercentage(
                uint256 _maximumRepriceswETHDifferencePercentage
              ) external checkRole(SwellLib.PLATFORM_ADMIN) {
                emit MaximumRepriceswETHDifferencePercentageUpdated(
                  maximumRepriceswETHDifferencePercentage,
                  _maximumRepriceswETHDifferencePercentage
                );
                maximumRepriceswETHDifferencePercentage = _maximumRepriceswETHDifferencePercentage;
              }
              function setMaximumRepriceDifferencePercentage(
                uint256 _maximumRepriceDifferencePercentage
              ) external checkRole(SwellLib.PLATFORM_ADMIN) {
                emit MaximumRepriceDifferencePercentageUpdated(
                  maximumRepriceDifferencePercentage,
                  _maximumRepriceDifferencePercentage
                );
                maximumRepriceDifferencePercentage = _maximumRepriceDifferencePercentage;
              }
              function swETHToETHRate() external view override returns (uint256) {
                return _swETHToETHRate().unwrap();
              }
              function ethToSwETHRate() external view override returns (uint256) {
                return _ethToSwETHRate().unwrap();
              }
              function getRate() external view override returns (uint256) {
                // This method is identical to swETHToETHRate but is required for the Balancer Metastable pools. Keeping this and the swETHToETHRate method because the swETHToETHRate method is more readable for integrations.
                return _swETHToETHRate().unwrap();
              }
              function deposit() external payable override checkWhitelist(msg.sender) {
                if (AccessControlManager.coreMethodsPaused()) {
                  revert SwellLib.CoreMethodsPaused();
                }
                if (msg.value == 0) {
                  revert SwellLib.InvalidETHDeposit();
                }
                uint256 swETHAmount = wrap(msg.value).mul(_ethToSwETHRate()).unwrap();
                _mint(msg.sender, swETHAmount);
                totalETHDeposited += msg.value;
                AddressUpgradeable.sendValue(
                  payable(address(AccessControlManager.DepositManager())),
                  msg.value
                );
                emit ETHDepositReceived(
                  msg.sender,
                  msg.value,
                  swETHAmount,
                  totalETHDeposited
                );
              }
              function reprice(
                uint256 _preRewardETHReserves,
                uint256 _newETHRewards,
                uint256 _swETHTotalSupply
              ) external override checkRole(SwellLib.BOT) {
                if (AccessControlManager.botMethodsPaused()) {
                  revert SwellLib.BotMethodsPaused();
                }
                uint256 currSupply = totalSupply();
                if (_swETHTotalSupply == 0 || currSupply == 0) {
                  revert CannotRepriceWithZeroSwETHSupply();
                }
                if (_preRewardETHReserves == 0) {
                  revert InvalidPreRewardETHReserves();
                }
                uint256 timeSinceLastReprice = block.timestamp - lastRepriceUNIX;
                if (timeSinceLastReprice < minimumRepriceTime) {
                  revert NotEnoughTimeElapsedForReprice(
                    minimumRepriceTime - timeSinceLastReprice
                  );
                }
                uint256 totalReserves = _preRewardETHReserves + _newETHRewards;
                uint256 rewardPercentageTotal = swellTreasuryRewardPercentage +
                  nodeOperatorRewardPercentage;
                UD60x18 rewardsInETH = wrap(_newETHRewards).mul(
                  wrap(rewardPercentageTotal)
                );
                UD60x18 rewardsInSwETH = wrap(_swETHTotalSupply).mul(rewardsInETH).div(
                  wrap(_preRewardETHReserves - rewardsInETH.unwrap() + _newETHRewards)
                );
                // Also including the amount of new swETH that was minted alongside the provided swETH total supply
                uint256 updatedSwETHToETHRateFixed = wrap(totalReserves)
                  .div(wrap(_swETHTotalSupply + rewardsInSwETH.unwrap()))
                  .unwrap();
                // Ensure that the reprice differences are within expected ranges, only if the reprice method has been called before
                if (lastRepriceUNIX != 0) {
                  // Check repricing rate difference
                  uint256 repriceDiff = _absolute(
                    updatedSwETHToETHRateFixed,
                    swETHToETHRateFixed
                  );
                  uint256 maximumRepriceDiff = wrap(swETHToETHRateFixed)
                    .mul(wrap(maximumRepriceDifferencePercentage))
                    .unwrap();
                  if (repriceDiff > maximumRepriceDiff) {
                    revert RepriceDifferenceTooLarge(repriceDiff, maximumRepriceDiff);
                  }
                }
                // Check swETH supply provided with actual current supply
                uint256 swETHSupplyDiff = _absolute(currSupply, _swETHTotalSupply);
                uint256 maximumswETHDiff = (currSupply *
                  maximumRepriceswETHDifferencePercentage) / 1 ether;
                if (swETHSupplyDiff > maximumswETHDiff) {
                  revert RepriceswETHDifferenceTooLarge(swETHSupplyDiff, maximumswETHDiff);
                }
                uint256 nodeOperatorRewards;
                uint256 swellTreasuryRewards;
                if (rewardsInSwETH.unwrap() != 0) {
                  _mint(address(this), rewardsInSwETH.unwrap());
                  UD60x18 nodeOperatorRewardPortion = wrap(nodeOperatorRewardPercentage)
                    .div(wrap(rewardPercentageTotal));
                  nodeOperatorRewards = nodeOperatorRewardPortion
                    .mul(rewardsInSwETH)
                    .unwrap();
                  if (nodeOperatorRewards != 0) {
                    INodeOperatorRegistry nodeOperatorRegistry = AccessControlManager
                      .NodeOperatorRegistry();
                    uint128 totalOperators = nodeOperatorRegistry.numOperators();
                    UD60x18 totalActiveValidators = wrap(
                      nodeOperatorRegistry.getPoRAddressListLength()
                    );
                    if (totalActiveValidators.unwrap() == 0) {
                      revert NoActiveValidators();
                    }
                    // Operator Id's start at 1
                    for (uint128 i = 1; i <= totalOperators; ) {
                      (
                        address rewardAddress,
                        uint256 operatorActiveValidators
                      ) = nodeOperatorRegistry.getRewardDetailsForOperatorId(i);
                      if (operatorActiveValidators != 0) {
                        uint256 operatorsRewardShare = wrap(operatorActiveValidators)
                          .div(totalActiveValidators)
                          .mul(wrap(nodeOperatorRewards))
                          .unwrap();
                        _transfer(address(this), rewardAddress, operatorsRewardShare);
                      }
                      // Will never overflow as the total operators are capped at uint128
                      unchecked {
                        ++i;
                      }
                    }
                  }
                  // Transfer the remaining tokens to the treasury, this includes the swell treasury percentage and if there are any remainder tokens after NO distribution
                  swellTreasuryRewards = balanceOf(address(this));
                  if (swellTreasuryRewards != 0) {
                    _transfer(
                      address(this),
                      AccessControlManager.SwellTreasury(),
                      swellTreasuryRewards
                    );
                  }
                }
                lastRepriceETHReserves = totalReserves;
                lastRepriceUNIX = block.timestamp;
                swETHToETHRateFixed = updatedSwETHToETHRateFixed;
                emit Reprice(
                  lastRepriceETHReserves,
                  swETHToETHRateFixed,
                  nodeOperatorRewards,
                  swellTreasuryRewards,
                  totalETHDeposited
                );
              }
              // ************************************
              // ***** Internal methods ******
              /**
               * @dev Returns the ETH -> swETH rate, if no PoR reading has come through the rate is 1:1
               * @return The rate as a fixed-point type
               */
              function _ethToSwETHRate() internal view returns (UD60x18) {
                return wrap(1 ether).div(_swETHToETHRate());
              }
              /**
               * @dev Returns the swETH -> ETH rate, if no PoR reading has come in the rate is 1:1
               * @return The rate as a fixed-point type
               */
              function _swETHToETHRate() internal view returns (UD60x18) {
                if (swETHToETHRateFixed == 0) {
                  return wrap(1 ether);
                }
                return wrap(swETHToETHRateFixed);
              }
              /**
               * @dev Returns the absolute difference between two uint256 values
               */
              function _absolute(uint256 _a, uint256 _b) internal pure returns (uint256) {
                if (_a < _b) {
                  return _b - _a;
                }
                return _a - _b;
              }
            }
            // SPDX-License-Identifier: UNLICENSED
            pragma solidity 0.8.16;
            import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
            import {IAccessControlManager} from "../interfaces/IAccessControlManager.sol";
            import {IWhitelist} from "../interfaces/IWhitelist.sol";
            import {SwellLib} from "../libraries/SwellLib.sol";
            /**
              @title Whitelist
              @author https://github.com/max-taylor 
              @dev Contract to manage a whitelist, used in the swETH contract to handle allowed depositors
            */
            contract Whitelist is Initializable, IWhitelist {
              IAccessControlManager public AccessControlManager;
              mapping(address => bool) public override whitelistedAddresses;
              bool public override whitelistEnabled;
              /// @custom:oz-upgrades-unsafe-allow constructor
              constructor() {
                _disableInitializers();
              }
              /**
               * @dev Modifier to check for empty addresses
               * @param _address The address to check
               */
              modifier checkZeroAddress(address _address) {
                SwellLib._checkZeroAddress(_address);
                _;
              }
              /**
               * Helper to check the sender against the given role
               * @param role The role to check for the msg.sender
               */
              modifier checkRole(bytes32 role) {
                AccessControlManager.checkRole(role, msg.sender);
                _;
              }
              /**
               * @dev Method checks if the whitelist is enabled and also whether the address is in the whitelist, reverting if true.
               * @param _address The address to check in the whitelist
               */
              modifier checkWhitelist(address _address) {
                if (whitelistEnabled && !whitelistedAddresses[_address]) {
                  revert NotInWhitelist();
                }
                _;
              }
              /**
               * @dev This contract is intended to be inherited from a parent contract, so using an onlyInitializing modifier to allow that.
               * @param _accessControlManager The access control manager to use for role management
               */
              function __Whitelist_init(
                IAccessControlManager _accessControlManager
              ) internal onlyInitializing checkZeroAddress(address(_accessControlManager)) {
                AccessControlManager = _accessControlManager;
                whitelistEnabled = true;
              }
              // ************************************
              // ***** External methods ******
              function addToWhitelist(
                address _address
              ) external override checkRole(SwellLib.PLATFORM_ADMIN) {
                _checkAndAddToWhitelist(_address);
              }
              function batchAddToWhitelist(
                address[] calldata _addresses
              ) external checkRole(SwellLib.PLATFORM_ADMIN) {
                for (uint256 i; i < _addresses.length; ) {
                  _checkAndAddToWhitelist(_addresses[i]);
                  unchecked {
                    ++i;
                  }
                }
              }
              function removeFromWhitelist(
                address _address
              ) external override checkRole(SwellLib.PLATFORM_ADMIN) {
                _checkAndRemoveFromWhitelist(_address);
              }
              function batchRemoveFromWhitelist(
                address[] calldata _addresses
              ) external checkRole(SwellLib.PLATFORM_ADMIN) {
                for (uint256 i; i < _addresses.length; ) {
                  _checkAndRemoveFromWhitelist(_addresses[i]);
                  unchecked {
                    ++i;
                  }
                }
              }
              function enableWhitelist()
                external
                override
                checkRole(SwellLib.PLATFORM_ADMIN)
              {
                if (whitelistEnabled) {
                  revert WhitelistAlreadyEnabled();
                }
                whitelistEnabled = true;
                emit WhitelistEnabled();
              }
              function disableWhitelist()
                external
                override
                checkRole(SwellLib.PLATFORM_ADMIN)
              {
                if (!whitelistEnabled) {
                  revert WhitelistAlreadyDisabled();
                }
                whitelistEnabled = false;
                emit WhitelistDisabled();
              }
              // ************************************
              // ***** Internal methods ******
              /**
               * @dev This method checks if the given address is the zero address or is in the whitelist already, reverting if true; otherwise the address is added and an event is emitted
               * @param _address The address to check and add to the whitelist
               */
              function _checkAndAddToWhitelist(address _address) internal {
                SwellLib._checkZeroAddress(_address);
                if (whitelistedAddresses[_address]) {
                  revert AddressAlreadyInWhitelist(_address);
                }
                whitelistedAddresses[_address] = true;
                emit AddedToWhitelist(_address);
              }
              /**
               * @dev This method checks if the address doesn't exist within the whitelist and reverts if true, otherwise the address is removed from the whitelist and an event is emitted
               * @param _address The address to check and remove from the whitelist
               */
              function _checkAndRemoveFromWhitelist(address _address) internal {
                if (!whitelistedAddresses[_address]) {
                  revert AddressMissingFromWhitelist(_address);
                }
                whitelistedAddresses[_address] = false;
                emit RemovedFromWhitelist(_address);
              }
              /**
               * @dev Gap for upgrades
               */
              uint256[45] private __gap;
            }
            // SPDX-License-Identifier: UNLICENSED
            pragma solidity 0.8.16;
            import {IAccessControlEnumerableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/IAccessControlEnumerableUpgradeable.sol";
            import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
            import {IDepositManager} from "./IDepositManager.sol";
            import {IswETH} from "./IswETH.sol";
            import {INodeOperatorRegistry} from "./INodeOperatorRegistry.sol";
            /**
              @title IAccessControlManager
              @author https://github.com/max-taylor 
              @dev The interface for the Access Control Manager, which manages roles and permissions for contracts within the Swell ecosystem
            */
            interface IAccessControlManager is IAccessControlEnumerableUpgradeable {
              // ***** Structs ******
              /**
                @dev Parameters for initializing the contract.
                @param admin The admin address
                @param swellTreasury The swell treasury address
              */
              struct InitializeParams {
                address admin;
                address swellTreasury;
              }
              // ***** Errors ******
              /**
                @dev Error thrown when attempting to pause an already-paused boolean
              */
              error AlreadyPaused();
              /**
                @dev Error thrown when attempting to unpause an already-unpaused boolean
              */
              error AlreadyUnpaused();
              // ***** Events ******
              /**
                @dev Emitted when a new DepositManager contract address is set.
                @param newAddress The new DepositManager contract address.
                @param oldAddress The old DepositManager contract address.
              */
              event UpdatedDepositManager(address newAddress, address oldAddress);
              /**
                @dev Emitted when a new NodeOperatorRegistry contract address is set.
                @param newAddress The new NodeOperatorRegistry contract address.
                @param oldAddress The old NodeOperatorRegistry contract address.
              */
              event UpdatedNodeOperatorRegistry(address newAddress, address oldAddress);
              /**
                @dev Emitted when a new SwellTreasury contract address is set.
                @param newAddress The new SwellTreasury contract address.
                @param oldAddress The old SwellTreasury contract address.
              */
              event UpdatedSwellTreasury(address newAddress, address oldAddress);
              /**
                @dev Emitted when a new SwETH contract address is set.
                @param newAddress The new SwETH contract address.
                @param oldAddress The old SwETH contract address.
              */
              event UpdatedSwETH(address newAddress, address oldAddress);
              /**
                @dev Emitted when core methods functionality is paused or unpaused.
                @param newPausedStatus The new paused status.
              */
              event CoreMethodsPause(bool newPausedStatus);
              /**
                @dev Emitted when bot methods functionality is paused or unpaused.
                @param newPausedStatus The new paused status.
              */
              event BotMethodsPause(bool newPausedStatus);
              /**
                @dev Emitted when operator methods functionality is paused or unpaused.
                @param newPausedStatus The new paused status.
              */
              event OperatorMethodsPause(bool newPausedStatus);
              /**
                @dev Emitted when withdrawals functionality is paused or unpaused.
                @param newPausedStatus The new paused status.
              */
              event WithdrawalsPause(bool newPausedStatus);
              // ************************************
              // ***** External Methods ******
              /**
               * @dev Pass-through method to call the _checkRole method on the inherited access control contract. This method is to be used by external contracts that are using this centralised access control manager, this ensures that if the check fails it reverts with the correct access control error message
               * @param role The role to check
               * @param account The account to check for
               */
              function checkRole(bytes32 role, address account) external view;
              // ***** Setters ******
              /**
               * @notice Sets the `swETH` address to `_swETH`.
               * @dev This function is only callable by the `PLATFORM_ADMIN` role.
               * @param _swETH The address of the `swETH` contract.
               */
              function setSwETH(IswETH _swETH) external;
              /**
               * @notice Sets the `DepositManager` address to `_depositManager`.
               * @dev This function is only callable by the `PLATFORM_ADMIN` role.
               * @param _depositManager The address of the `DepositManager` contract.
               */
              function setDepositManager(IDepositManager _depositManager) external;
              /**
               * @notice Sets the `NodeOperatorRegistry` address to `_NodeOperatorRegistry`.
               * @dev This function is only callable by the `PLATFORM_ADMIN` role.
               * @param _NodeOperatorRegistry The address of the `NodeOperatorRegistry` contract.
               */
              function setNodeOperatorRegistry(
                INodeOperatorRegistry _NodeOperatorRegistry
              ) external;
              /**
               * @notice Sets the `SwellTreasury` address to `_swellTreasury`.
               * @dev This function is only callable by the `PLATFORM_ADMIN` role.
               * @param _swellTreasury The new address of the `SwellTreasury` contract.
               */
              function setSwellTreasury(address _swellTreasury) external;
              // ***** Getters ******
              /**
                @dev Returns the PLATFORM_ADMIN role.
                @return The bytes32 representation of the PLATFORM_ADMIN role.
              */
              function PLATFORM_ADMIN() external pure returns (bytes32);
              /**
                @dev Returns the Swell ETH contract.
                @return The Swell ETH contract.
              */
              function swETH() external returns (IswETH);
              /**
                @dev Returns the address of the Swell Treasury contract.
                @return The address of the Swell Treasury contract.
              */
              function SwellTreasury() external returns (address);
              /**
                @dev Returns the Deposit Manager contract.
                @return The Deposit Manager contract.
              */
              function DepositManager() external returns (IDepositManager);
              /**
                @dev Returns the Node Operator Registry contract.
                @return The Node Operator Registry contract.
              */
              function NodeOperatorRegistry() external returns (INodeOperatorRegistry);
              /**
                @dev Returns true if core methods are currently paused.
                @return Whether core methods are paused.
              */
              function coreMethodsPaused() external returns (bool);
              /**
                @dev Returns true if bot methods are currently paused.
                @return Whether bot methods are paused.
              */
              function botMethodsPaused() external returns (bool);
              /**
                @dev Returns true if operator methods are currently paused.
                @return Whether operator methods are paused.
              */
              function operatorMethodsPaused() external returns (bool);
              /**
                @dev Returns true if withdrawals are currently paused.
                @dev ! Note that this is completely unused in the current implementation and is a placeholder that will be used once the withdrawals are implemented.
                @return Whether withdrawals are paused.
              */
              function withdrawalsPaused() external returns (bool);
              // ***** Pausable methods ******
              /**
                @dev Pauses the core methods of the Swell ecosystem, only callable by the PLATFORM_ADMIN
              */
              function pauseCoreMethods() external;
              /**
                @dev Unpauses the core methods of the Swell ecosystem, only callable by the PLATFORM_ADMIN
              */
              function unpauseCoreMethods() external;
              /**
                @dev Pauses the bot specific methods, only callable by the PLATFORM_ADMIN
              */
              function pauseBotMethods() external;
              /**
                @dev Unpauses the bot specific methods, only callable by the PLATFORM_ADMIN
              */
              function unpauseBotMethods() external;
              /**
                @dev Pauses the operator methods in the NO registry contract, only callable by the PLATFORM_ADMIN
              */
              function pauseOperatorMethods() external;
              /**
                @dev Unpauses the operator methods in the NO registry contract, only callable by the PLATFORM_ADMIN
              */
              function unpauseOperatorMethods() external;
              /**
                @dev Pauses the withdrawals of the Swell ecosystem, only callable by the PLATFORM_ADMIN
              */
              function pauseWithdrawals() external;
              /**
                @dev Unpauses the withdrawals of the Swell ecosystem, only callable by the PLATFORM_ADMIN
              */
              function unpauseWithdrawals() external;
              /**
               * @dev This method withdraws contract's _token balance to a platform admin
               * @param _token The ERC20 token to withdraw from the contract
               */
              function withdrawERC20(IERC20 _token) external;
            }
            // SPDX-License-Identifier: UNLICENSED
            pragma solidity 0.8.16;
            import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
            /**
             * @title IDepositManager
             * @author https://github.com/max-taylor
             * @notice The interface for the deposit manager contract
             */
            interface IDepositManager {
              // ***** Errors ******
              /**
               * @dev Error thrown when calling the withdrawETH method from an account that isn't the swETH contract
               */
              error InvalidETHWithdrawCaller();
              /**
               * @dev Error thrown when the depositDataRoot parameter in the setupValidators contract doesn't match the onchain deposit data root from the deposit contract
               */
              error InvalidDepositDataRoot();
              /**
               * @dev Error thrown when setting up new validators and the contract doesn't hold enough ETH to be able to set them up.
               */
              error InsufficientETHBalance();
              // ***** Events ******
              /**
               * Emitted when new validators are setup
               * @param pubKeys The pubKeys that have been used for validator setup
               */
              event ValidatorsSetup(bytes[] pubKeys);
              /**
               * @dev Event is fired when some contracts receive ETH
               * @param from The account that sent the ETH
               * @param amount The amount of ETH received
               */
              event ETHReceived(address indexed from, uint256 amount);
              // ************************************
              // ***** External methods ******
              /**
               * @dev This method withdraws contract's _token balance to a platform admin
               * @param _token The ERC20 token to withdraw from the contract
               */
              function withdrawERC20(IERC20 _token) external;
              /**
               * @dev Formats ETH1 the withdrawal credentials according to the following standard: https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/validator.md#eth1_address_withdrawal_prefix
               * @dev It doesn't outline the withdrawal prefixes, they can be found here: https://eth2book.info/altair/part3/config/constants#withdrawal-prefixes
               * @dev As the DepositManager on the execution layer is going to be the withdrawal contract, we will be doing ETH1 withdrawals. The standard for this is a 32 byte response where; the first byte stores the withdrawal prefix (0x01), the following 11 bytes are empty and the last 20 bytes are the address
               */
              function getWithdrawalCredentials()
                external
                view
                returns (bytes memory withdrawalCredentials);
              /**
               * @dev This method allows setting up of new validators in the beacon deposit contract, it ensures the provided pubKeys are unused in the NO registry
               * @notice An off-chain service provides front-running protection by validating each pubKey ensuring that it hasn't been used for a validator setup. This service snapshots the depositDataRoot of the deposit contract, then this value is re-read from the deposit contract within setupValdiators() and ensures that they match, this consistency provides the front-running protection. Read more here: https://research.lido.fi/t/mitigations-for-deposit-front-running-vulnerability/1239
               * @param _pubKeys The pubKeys to setup
               * @param _depositDataRoot The deposit contracts deposit root which MUST match the current beacon deposit contract deposit data root otherwise the contract will revert due to the risk of the front-running vulnerability.
               */
              function setupValidators(
                bytes[] calldata _pubKeys,
                bytes32 _depositDataRoot
              ) external;
            }
            // SPDX-License-Identifier: UNLICENSED
            pragma solidity 0.8.16;
            import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
            import {IAccessControlManager} from "../interfaces/IAccessControlManager.sol";
            import {IPoRAddresses} from "../vendors/IPoRAddresses.sol";
            /**
             * @title INodeOperatorRegistry
             * @author https://github.com/max-taylor
             * @notice Interface for the Node Operator Registry contract.
             */
            interface INodeOperatorRegistry is IPoRAddresses {
              /**
               * @dev  Struct containing the required details to setup a validator on the beacon chain
               * @param pubKey Public key of the validator
               * @param signature The signature of the validator
               */
              struct ValidatorDetails {
                bytes pubKey;
                bytes signature;
              }
              /**
               * @dev  Struct containing operator details
               * @param enabled Flag indicating if the operator is enabled or disabled
               * @param rewardAddress Address to sending repricing rewards to
               * @param controllingAddress The address that can control the operator account
               * @param name The name of the operator
               * @param activeValidators The amount of active validators for the operator
               */
              struct Operator {
                bool enabled;
                address rewardAddress;
                address controllingAddress;
                string name;
                uint128 activeValidators;
              }
              // ***** Events *****
              /**
               * @dev  Emitted when a new operator is added.
               * @param operatorAddress  The address of the newly added operator.
               * @param rewardAddress    The address associated with the reward for the operator.
               */
              event OperatorAdded(address operatorAddress, address rewardAddress);
              /**
               * @dev  Emitted when an operator is enabled.
               * @param operator  The address of the operator that was enabled.
               */
              event OperatorEnabled(address indexed operator);
              /**
               * @dev  Emitted when an operator is disabled.
               * @param operator  The address of the operator that was disabled.
               */
              event OperatorDisabled(address indexed operator);
              /**
               * @dev  Emitted when the validator details for an operator are added.
               * @param operator  The address of the operator for which the validator details were added.
               * @param pubKeys   An array of `ValidatorDetails` for the operator.
               */
              event OperatorAddedValidatorDetails(
                address indexed operator,
                ValidatorDetails[] pubKeys
              );
              /**
               * @dev  Emitted when active public keys are deleted.
               * @param pubKeys  An array of public keys that were deleted.
               */
              event ActivePubKeysDeleted(bytes[] pubKeys);
              /**
               * @dev  Emitted when pending public keys are deleted.
               * @param pubKeys  An array of public keys that were deleted.
               */
              event PendingPubKeysDeleted(bytes[] pubKeys);
              /**
               * @dev  Emitted when public keys are used for validator setup.
               * @param pubKeys  An array of public keys that were used for validator setup.
               */
              event PubKeysUsedForValidatorSetup(bytes[] pubKeys);
              // ***** Errors *****
              /**
               * @dev Thrown when an operator is not found.
               * @param operator  The address of the operator that was not found.
               */
              error NoOperatorFound(address operator);
              /**
               * @dev Thrown when an operator already exists.
               * @param operator The address of the operator that already exists.
               */
              error OperatorAlreadyExists(address operator);
              /**
               * @dev Thrown when an operator is already enabled.
               */
              error OperatorAlreadyEnabled();
              /**
               * @dev Thrown when an operator is already disabled.
               */
              error OperatorAlreadyDisabled();
              /**
               * @dev Thrown when an array length of zero is invalid.
               */
              error InvalidArrayLengthOfZero();
              /**
               * @dev Thrown when an operator is adding new validator details and this causes the total amount of operator's validator details to exceed uint128
               */
              error AmountOfValidatorDetailsExceedsLimit();
              /**
               * @dev Thrown during setup of new validators, when comparing the next operator's public key to the provided public key they should match. This ensures consistency in the tracking of the active and pending validator details.
               * @param foundPubKey The operator's next available public key
               * @param providedPubKey The public key that was passed in as an argument
               */
              error NextOperatorPubKeyMismatch(bytes foundPubKey, bytes providedPubKey);
              /**
               * @dev Thrown during the setup of new validators and when the operator that has no pending details left to use
               */
              error OperatorOutOfPendingKeys();
              /**
               * @dev Thrown when the given pubKey hasn't been added to the registry and cannot be found
               * @param pubKey  The public key that was not found.
               */
              error NoPubKeyFound(bytes pubKey);
              /**
               * @dev Thrown when an operator tries to use the node operator registry whilst they are disabled
               */
              error CannotUseDisabledOperator();
              /**
               * @dev Thrown when a duplicate public key is added.
               * @param existingKey  The public key that already exists.
               */
              error CannotAddDuplicatePubKey(bytes existingKey);
              /**
               * @dev Thrown when the given pubKey doesn't exist in the pending validator details sets
               * @param pubKey  The missing pubKey
               */
              error MissingPendingValidatorDetails(bytes pubKey);
              /**
               * @dev Thrown when the pubKey doesn't exist in the active validator details set
               * @param pubKey  The missing pubKey
               */
              error MissingActiveValidatorDetails(bytes pubKey);
              /**
               * @dev Throw when the msg.sender isn't the Deposit Manager contract
               */
              error InvalidPubKeySetupCaller();
              /**
               * @dev Thrown when an operator is trying to add validator details and a provided pubKey isn't the correct length
               */
              error InvalidPubKeyLength();
              /**
               * @dev Thrown when an operator is trying to add validator details and a provided signature isn't the correct length
               */
              error InvalidSignatureLength();
              // ************************************
              // ***** External  methods ******
              /**
               * @dev This method withdraws contract's _token balance to a platform admin
               * @param _token The ERC20 token to withdraw from the contract
               */
              function withdrawERC20(IERC20 _token) external;
              /**
               * @dev  Gets the next available validator details, ordered by operators with the least amount of active validators. There may be less available validators then the provided _numNewValidators amount, in that case the function will return an array of length equal to _numNewValidators but all indexes after the second return value; foundValidators, will be 0x0 values
               * @param _numNewValidators The number of new validators to get details for.
               * @return An array of ValidatorDetails and the length of the array of non-zero validator details
               * @notice This method tries to return enough validator details to equal the provided _numNewValidators, but if there aren't enough validator details to find, it will simply return what it found, and the caller will need to check for empty values.
               */
              function getNextValidatorDetails(
                uint256 _numNewValidators
              ) external view returns (ValidatorDetails[] memory, uint256 foundValidators);
              /**
               * @dev  Allows the DepositManager to move provided _pubKeys from the pending validator details arrays into the active validator details array. It also returns the validator details, so that the DepositManager can pass the signature along to the ETH2 deposit contract.
               * @param _pubKeys Array of public keys to use for validator setup.
               * @return validatorDetails The associated validator details for the given public keys
               * @notice This method will be called when the DepositManager is setting up new validators.
               */
              function usePubKeysForValidatorSetup(
                bytes[] calldata _pubKeys
              ) external returns (ValidatorDetails[] memory validatorDetails);
              // ** Operator management methods **
              /**
               * @dev  Adds new validator details to the registry.
              /**
               * @dev  Callable by node operator's to add their validator details to the setup queue
               * @param _validatorDetails Array of ValidatorDetails to add.
              */
              function addNewValidatorDetails(
                ValidatorDetails[] calldata _validatorDetails
              ) external;
              // ** PLATFORM_ADMIN management methods **
              /**
               * @dev  Adds a new operator to the registry.
               * @param _name Name of the operator.
               * @param _operatorAddress Address of the operator.
               * @param _rewardAddress Address of the reward recipient for this operator.
               * @notice Throws if an operator already exists with the given _operatorAddress
               */
              function addOperator(
                string calldata _name,
                address _operatorAddress,
                address _rewardAddress
              ) external;
              /**
               * @dev  Enables an operator in the registry.
               * @param _operatorAddress Address of the operator to enable.
               * @notice Throws NoOperatorFound if the operator address is not found in the registry
               */
              function enableOperator(address _operatorAddress) external;
              /**
               * @dev  Disables an operator in the registry.
               * @param _operatorAddress Address of the operator to disable.
               * @notice Throws NoOperatorFound if the operator address is not found in the registry
               */
              function disableOperator(address _operatorAddress) external;
              /**
               * @dev  Updates the controlling address of an operator in the registry.
               * @param _operatorAddress Current address of the operator.
               * @param _newOperatorAddress New address of the operator.
               * @notice Throws NoOperatorFound if the operator address is not found in the registry
               */
              function updateOperatorControllingAddress(
                address _operatorAddress,
                address _newOperatorAddress
              ) external;
              /**
               * @dev  Updates the reward address of an operator in the registry.
               * @param _operatorAddress Address of the operator to update.
               * @param _newRewardAddress New reward address for the operator.
               * @notice Throws NoOperatorFound if the operator address is not found in the registry
               */
              function updateOperatorRewardAddress(
                address _operatorAddress,
                address _newRewardAddress
              ) external;
              /**
               * @dev  Updates the name of an operator in the registry
               * @param _operatorAddress The address of the operator to update
               * @param _name The new name for the operator
               * @notice Throws NoOperatorFound if the operator address is not found in the registry
               */
              function updateOperatorName(
                address _operatorAddress,
                string calldata _name
              ) external;
              /**
               * @dev  Allows the PLATFORM_ADMIN to delete validators that are pending. This is likely to be called via an admin if a public key fails the front-running checks
               * @notice Throws InvalidArrayLengthOfZero if the length of _pubKeys is 0
               * @notice Throws NoPubKeyFound if any of the provided pubKeys is not found in the pending validators set
               * @param _pubKeys The public keys of the pending validators to delete
               */
              function deletePendingValidators(bytes[] calldata _pubKeys) external;
              /**
               * @dev  Allows the PLATFORM_ADMIN to delete validator public keys that have been used to setup a validator and that validator has now exited
               * @notice Throws NoPubKeyFound if any of the provided pubKeys is not found in the active validators set
               * @notice Throws InvalidArrayLengthOfZero if the length of _pubKeys is 0
               * @param _pubKeys The public keys of the active validators to delete
               */
              function deleteActiveValidators(bytes[] calldata _pubKeys) external;
              /**
               * @dev  Returns the address of the AccessControlManager contract
               */
              function AccessControlManager() external returns (IAccessControlManager);
              /**
               * @dev  Returns the operator details for a given operator address
               * @notice Throws NoOperatorFound if the operator address is not found in the registry
               * @param _operatorAddress The address of the operator to retrieve
               * @return operator The operator details, including name, reward address, and enabled status
               * @return totalValidatorDetails The total amount of validator details for an operator
               * @return operatorId The operator's Id
               */
              function getOperator(
                address _operatorAddress
              )
                external
                view
                returns (
                  Operator memory operator,
                  uint128 totalValidatorDetails,
                  uint128 operatorId
                );
              /**
               * @dev  Returns the pending validator details for a given operator address
               * @notice Throws NoOperatorFound if the operator address is not found in the registry
               * @param _operatorAddress The address of the operator to retrieve pending validator details for
               * @return validatorDetails The pending validator details for the given operator
               */
              function getOperatorsPendingValidatorDetails(
                address _operatorAddress
              ) external returns (ValidatorDetails[] memory);
              /**
               * @dev  Returns the active validator details for a given operator address
               * @notice Throws NoOperatorFound if the operator address is not found in the registry
               * @param _operatorAddress The address of the operator to retrieve active validator details for
               * @return validatorDetails The active validator details for the given operator
               */
              function getOperatorsActiveValidatorDetails(
                address _operatorAddress
              ) external returns (ValidatorDetails[] memory validatorDetails);
              /**
               * @dev  Returns the reward details for a given operator Id, this method is used in the swETH contract when paying swETH rewards
               * @param _operatorId The operator Id to get the reward details for
               * @return rewardAddress The reward address of the operator
               * @return activeValidators The amount of active validators for the operator
               */
              function getRewardDetailsForOperatorId(
                uint128 _operatorId
              ) external returns (address rewardAddress, uint128 activeValidators);
              /**
               * @dev  Returns the number of operators in the registry
               */
              function numOperators() external returns (uint128);
              /**
               * @dev  Returns the amount of pending validator keys in the registry
               */
              function numPendingValidators() external returns (uint256);
              /**
               * @dev  Returns the operator ID for a given operator address
               * @notice Throws NoOperatorFound if the operator address is not found in the registry
               * @param _operator The address of the operator to retrieve the operator ID for
               * @return _operatorId The operator ID for the given operator
               */
              function getOperatorIdForAddress(
                address _operator
              ) external returns (uint128 _operatorId);
              /**
               * @dev Returns the `operatorId` associated with the given `pubKey`.
               * @param pubKey  The public key to lookup the `operatorId` for.
               * @notice Returns 0 if no operatorId controls the pubKey
               */
              function getOperatorIdForPubKey(
                bytes calldata pubKey
              ) external returns (uint128);
            }
            // SPDX-License-Identifier: UNLICENSED
            pragma solidity 0.8.16;
            import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
            import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
            /**
             * @title SwETH Interface
             * @author https://github.com/max-taylor
             * @dev This interface provides the methods to interact with the SwETH contract.
             */
            interface IswETH is IERC20Upgradeable {
              // ***** Errors ******
              /**
               * @dev Error thrown when attempting to reprice with zero SwETH supply.
               */
              error CannotRepriceWithZeroSwETHSupply();
              /**
               * @dev Error thrown when passing a preRewardETHReserves value equal to 0 into the repricing function
               */
              error InvalidPreRewardETHReserves();
              /**
               * @dev Error thrown when repricing the rate and distributing rewards to NOs when they are no active validators. This condition should never happen; it means that no active validators were running but we still have rewards, despite this it's still here for security
               */
              error NoActiveValidators();
              /**
               * @dev Error thrown when updating the reward percentage for either the NOs or the swell treasury and the update will cause the NO percentage + swell treasury percentage to exceed 100%.
               */
              error RewardPercentageTotalOverflow();
              /**
               * @dev Thrown when calling the reprice function and not enough time has elapsed between the previous repriace and the current reprice.
               * @param remainingTime Remaining time until reprice can be called
               */
              error NotEnoughTimeElapsedForReprice(uint256 remainingTime);
              /**
               * @dev Thrown when repricing the rate and the difference in reserves values is greater than expected
               * @param repriceDiff The difference between the previous swETH rate and what would be the updated rate
               * @param maximumRepriceDiff The maximum allowed difference in swETH rate
               */
              error RepriceDifferenceTooLarge(
                uint256 repriceDiff,
                uint256 maximumRepriceDiff
              );
              /**
               * @dev Thrown during repricing when the difference in swETH supplied to repricing compared to the actual supply is too great
               * @param repriceswETHDiff The difference between the swETH supplied to repricing and actual supply
               * @param maximumswETHRepriceDiff The maximum allowed difference in swETH supply
               */
              error RepriceswETHDifferenceTooLarge(
                uint256 repriceswETHDiff,
                uint256 maximumswETHRepriceDiff
              );
              // ***** Events *****
              /**
               * @dev Event emitted when a user withdraws ETH for swETH
               * @param to Address of the recipient.
               * @param swETHBurned Amount of SwETH burned in the transaction.
               * @param ethReturned Amount of ETH returned in the transaction.
               */
              event ETHWithdrawn(
                address indexed to,
                uint256 swETHBurned,
                uint256 ethReturned
              );
              /**
               * @dev Event emitted when the swell treasury reward percentage is updated.
               * @dev Only callable by the platform admin
               * @param oldPercentage The previous swell treasury reward percentage.
               * @param newPercentage The new swell treasury reward percentage.
               */
              event SwellTreasuryRewardPercentageUpdate(
                uint256 oldPercentage,
                uint256 newPercentage
              );
              /**
               * @dev Event emitted when the node operator reward percentage is updated.
               * @dev Only callable by the platform admin
               * @param oldPercentage The previous node operator reward percentage.
               * @param newPercentage The new node operator reward percentage.
               */
              event NodeOperatorRewardPercentageUpdate(
                uint256 oldPercentage,
                uint256 newPercentage
              );
              /**
               * @dev Event emitted when the swETH - ETH rate is updated
               * @param newEthReserves The new ETH reserves for the swell protocol
               * @param newSwETHToETHRate The new SwETH to ETH rate.
               * @param nodeOperatorRewards The rewards for the node operator's.
               * @param swellTreasuryRewards The rewards for the swell treasury.
               * @param totalETHDeposited Current total ETH staked at time of reprice.
               */
              event Reprice(
                uint256 newEthReserves,
                uint256 newSwETHToETHRate,
                uint256 nodeOperatorRewards,
                uint256 swellTreasuryRewards,
                uint256 totalETHDeposited
              );
              /**
               * @dev Event is fired when some contracts receive ETH
               * @param from The account that sent the ETH
               * @param swETHMinted The amount of swETH minted to the caller
               * @param amount The amount of ETH received
               */
              event ETHDepositReceived(
                address indexed from,
                uint256 amount,
                uint256 swETHMinted,
                uint256 newTotalETHDeposited
              );
              /**
               * @dev Event emitted on a successful call to setMinimumRepriceTime
               * @param _oldMinimumRepriceTime The old reprice time
               * @param _newMinimumRepriceTime The new updated reprice time
               */
              event MinimumRepriceTimeUpdated(
                uint256 _oldMinimumRepriceTime,
                uint256 _newMinimumRepriceTime
              );
              /**
               * @dev Event emitted on a successful call to setMaximumRepriceswETHDifferencePercentage
               * @param _oldMaximumRepriceswETHDifferencePercentage The old maximum swETH supply difference
               * @param _newMaximumRepriceswETHDifferencePercentage The new updated swETH supply difference
               */
              event MaximumRepriceswETHDifferencePercentageUpdated(
                uint256 _oldMaximumRepriceswETHDifferencePercentage,
                uint256 _newMaximumRepriceswETHDifferencePercentage
              );
              /**
               * @dev Event emitted on a successful call to setMaximumRepriceDifferencePercentage
               * @param _oldMaximumRepriceDifferencePercentage The old maximum reprice difference
               * @param _newMaximumRepriceDifferencePercentage The new updated maximum reprice difference
               */
              event MaximumRepriceDifferencePercentageUpdated(
                uint256 _oldMaximumRepriceDifferencePercentage,
                uint256 _newMaximumRepriceDifferencePercentage
              );
              // ************************************
              // ***** External Methods ******
              /**
               * @dev This method withdraws contract's _token balance to a platform admin
               * @param _token The ERC20 token to withdraw from the contract
               */
              function withdrawERC20(IERC20 _token) external;
              /**
               * @dev Returns the ETH reserves that were provided in the most recent call to the reprice function
               * @return The last recorded ETH reserves
               */
              function lastRepriceETHReserves() external returns (uint256);
              /**
               * @dev Returns the last time the reprice method was called in UNIX
               * @return The UNIX timestamp of the last time reprice was called
               */
              function lastRepriceUNIX() external returns (uint256);
              /**
               * @dev Returns the total ETH that has been deposited over the protocols lifespan
               * @return The current total amount of ETH that has been deposited
               */
              function totalETHDeposited() external returns (uint256);
              /**
               * @dev Returns the current swell treasury reward percentage.
               * @return The current swell treasury reward percentage.
               */
              function swellTreasuryRewardPercentage() external returns (uint256);
              /**
               * @dev Returns the current node operator reward percentage.
               * @return The current node operator reward percentage.
               */
              function nodeOperatorRewardPercentage() external returns (uint256);
              /**
               * @dev Returns the current SwETH to ETH rate, returns 1:1 if no reprice has occurred otherwise it returns the swETHToETHRateFixed rate.
               * @return The current SwETH to ETH rate.
               */
              function swETHToETHRate() external returns (uint256);
              /**
               * @dev Returns the current ETH to SwETH rate.
               * @return The current ETH to SwETH rate.
               */
              function ethToSwETHRate() external returns (uint256);
              /**
               * @dev Returns the minimum reprice time
               * @return The minimum reprice time
               */
              function minimumRepriceTime() external returns (uint256);
              /**
               * @dev Returns the maximum percentage difference with 1e18 precision
               * @return The maximum percentage difference
               */
              function maximumRepriceDifferencePercentage() external returns (uint256);
              /**
               * @dev Returns the maximum percentage difference with 1e18 precision
               * @return The maximum percentage difference in suppled and actual swETH supply
               */
              function maximumRepriceswETHDifferencePercentage() external returns (uint256);
              /**
               * @dev Sets the new swell treasury reward percentage.
               * @notice Only a platform admin can call this function.
               * @param _newSwellTreasuryRewardPercentage The new swell treasury reward percentage to set.
               */
              function setSwellTreasuryRewardPercentage(
                uint256 _newSwellTreasuryRewardPercentage
              ) external;
              /**
               * @dev Sets the new node operator reward percentage.
               * @notice Only a platform admin can call this function.
               * @param _newNodeOperatorRewardPercentage The new node operator reward percentage to set.
               */
              function setNodeOperatorRewardPercentage(
                uint256 _newNodeOperatorRewardPercentage
              ) external;
              /**
               * @dev Sets the minimum permitted time between successful repricing calls using the block timestamp.
               * @notice Only a platform admin can call this function.
               * @param _minimumRepriceTime The new minimum time between successful repricing calls
               */
              function setMinimumRepriceTime(uint256 _minimumRepriceTime) external;
              /**
               * @dev Sets the maximum percentage allowable difference in swETH supplied to repricing compared to current swETH supply.
               * @notice Only a platform admin can call this function.
               * @param _maximumRepriceswETHDifferencePercentage The new maximum percentage swETH supply difference allowed.
               */
              function setMaximumRepriceswETHDifferencePercentage(
                uint256 _maximumRepriceswETHDifferencePercentage
              ) external;
              /**
               * @dev Sets the maximum percentage allowable difference in swETH to ETH price changes for a repricing call.
               * @notice Only a platform admin can call this function.
               * @param _maximumRepriceDifferencePercentage The new maximum percentage difference in repricing rate.
               */
              function setMaximumRepriceDifferencePercentage(
                uint256 _maximumRepriceDifferencePercentage
              ) external;
              /**
               * @dev Deposits ETH into the contract
               * @notice The amount of ETH deposited will be converted to SwETH at the current SwETH to ETH rate
               */
              function deposit() external payable;
              /**
              //  * TODO: Reword
               * @dev This method reprices the swETH -> ETH rate, this will be called via an offchain service on a regular interval, likely ~1 day. The swETH total supply is passed as an argument to avoid a potential race conditions between the off-chain reserve calculations and the on-chain repricing
               * @dev This method also mints a percentage of swETH as rewards to be claimed by NO's and the swell treasury. The formula for determining the amount of swETH to mint is the following: swETHToMint = (swETHSupply * newETHRewards * feeRate) / (preRewardETHReserves - newETHRewards * feeRate + newETHRewards)
               * @dev The formula is quite complicated because it needs to factor in the updated exchange rate whilst it calculates the amount of swETH rewards to mint. This ensures the rewards aren't double-minted and are backed by ETH.
               * @param _preRewardETHReserves The PoR value exclusive of the new ETH rewards earned
               * @param _newETHRewards The total amount of new ETH earnt over the period.
               * @param _swETHTotalSupply The total swETH supply at the time of off-chain reprice calculation
               */
              function reprice(
                uint256 _preRewardETHReserves,
                uint256 _newETHRewards,
                uint256 _swETHTotalSupply
              ) external;
            }
            // SPDX-License-Identifier: UNLICENSED
            pragma solidity 0.8.16;
            /**
             * @title IWhitelist
             * @author https://github.com/max-taylor
             * @dev Interface for managing a whitelist of addresses.
             */
            interface IWhitelist {
              // ***** Events ******
              /**
               * @dev Emitted when an address is added to the whitelist.
               * @param _address The address that was added to the whitelist.
               */
              event AddedToWhitelist(address indexed _address);
              /**
               * @dev Emitted when an address is removed from the whitelist.
               * @param _address The address that was removed from the whitelist.
               */
              event RemovedFromWhitelist(address indexed _address);
              /**
               * @dev Emitted when the whitelist is enabled.
               */
              event WhitelistEnabled();
              /**
               * @dev Emitted when the whitelist is disabled.
               */
              event WhitelistDisabled();
              // ***** Errors ******
              /**
               * @dev Throws an error indicating that the address is already in the whitelist.
               * @param _address The address that already exists in the whitelist.
               */
              error AddressAlreadyInWhitelist(address _address);
              /**
               * @dev Throws an error indicating that the address is missing from the whitelist.
               * @param _address The address that is missing from the whitelist.
               */
              error AddressMissingFromWhitelist(address _address);
              /**
               * @dev Throws an error indicating that the whitelist is already enabled.
               */
              error WhitelistAlreadyEnabled();
              /**
               * @dev Throws an error indicating that the whitelist is already disabled.
               */
              error WhitelistAlreadyDisabled();
              /**
               * @dev Throws an error indicating that the address is not in the whitelist.
               */
              error NotInWhitelist();
              // ************************************
              // ***** External Methods ******
              /**
               * @dev Returns true if the whitelist is enabled, false otherwise.
                @return bool representing whether the whitelist is enabled.
              */
              function whitelistEnabled() external returns (bool);
              /**
               * @dev Returns true if the address is in the whitelist, false otherwise.
               * @param _address The address to check.
                @return bool representing whether the address is in the whitelist.
              */
              function whitelistedAddresses(address _address) external returns (bool);
              /**
               * @dev Adds the specified address to the whitelist, reverts if not the platform admin
               * @param _address The address to add.
               */
              function addToWhitelist(address _address) external;
              /**
               * @dev Adds the array of addresses to the whitelist, reverts if not the platform admin.
               * @param _addresses The address to add.
               */
              function batchAddToWhitelist(address[] calldata _addresses) external;
              /**
               * @dev Removes the specified address from the whitelist, reverts if not the platform admin
               * @param _address The address to remove.
               */
              function removeFromWhitelist(address _address) external;
              /**
               * @dev Removes the array of addresses from the whitelist, reverts if not the platform admin
               * @param _addresses The array of addresses to remove.
               */
              function batchRemoveFromWhitelist(address[] calldata _addresses) external;
              /**
               * @dev Enables the whitelist, allowing only whitelisted addresses to interact with the contract. Reverts if the caller is not the platform admin
               */
              function enableWhitelist() external;
              /**
               * @dev Disables the whitelist, allowing all addresses to interact with the contract. Reverts if the caller is not the platform admin
               */
              function disableWhitelist() external;
            }
            // SPDX-License-Identifier: UNLICENSED
            pragma solidity 0.8.16;
            /**
             * @title SwellLib
             * @author https://github.com/max-taylor
             * @notice This library contains roles, errors, events and functions that are widely used throughout the protocol
             */
            library SwellLib {
              // ***** Roles *****
              /**
               * @dev The platform admin role
               */
              bytes32 public constant PLATFORM_ADMIN = keccak256("PLATFORM_ADMIN");
              /**
               * @dev The bot role
               */
              bytes32 public constant BOT = keccak256("BOT");
              // ***** Errors *****
              /**
               * @dev Thrown when _checkZeroAddress is called with the zero address
               */
              error CannotBeZeroAddress();
              /**
               * @dev Thrown in some contracts when the contract call is received by the fallback method
               */
              error InvalidMethodCall();
              /**
               * @dev Thrown in some contracts when ETH is sent directly to the contract
               */
              error InvalidETHDeposit();
              /**
               * @dev Thrown when interacting with a method on the protocol that is disabled via the coreMethodsPaused bool
               */
              error CoreMethodsPaused();
              /**
               * @dev Thrown when interacting with a method on the protocol that is disabled via the botMethodsPaused bool
               */
              error BotMethodsPaused();
              /**
               * @dev Thrown when interacting with a method on the protocol that is disabled via the operatorMethodsPaused bool
               */
              error OperatorMethodsPaused();
              /**
               * @dev Thrown when interacting with a method on the protocol that is disabled via the withdrawalsPaused bool
               */
              error WithdrawalsPaused();
              /**
               * @dev Thrown when calling the withdrawERC20 method and the contracts balance is 0
               */
              error NoTokensToWithdraw();
              // ************************************
              // ***** Internal Methods *****
              /**
               * @dev This helper is used throughout the protocol to guard against zero addresses being passed as parameters
               * @param _address The address to check if it is the zero address
               */
              function _checkZeroAddress(address _address) internal pure {
                if (_address == address(0)) {
                  revert CannotBeZeroAddress();
                }
              }
            }
            // SPDX-License-Identifier: MIT
            pragma solidity 0.8.16;
            /**
             * @title Chainlink Proof-of-Reserve address list interface.
             * @notice This interface enables Chainlink nodes to get the list addresses to be used in a PoR feed. A single
             * contract that implements this interface can only store an address list for a single PoR feed.
             * @dev All functions in this interface are expected to be called off-chain, so gas usage is not a big concern.
             * This makes it possible to store addresses in optimized data types and convert them to human-readable strings
             * in `getPoRAddressList()`.
             */
            interface IPoRAddresses {
              /**
               * @notice Get total number of addresses in the list.
               * @return The array length
               */
              function getPoRAddressListLength() external view returns (uint256);
              /**
               * @notice Get a batch of human-readable addresses from the address list.
               * @dev Due to limitations of gas usage in off-chain calls, we need to support fetching the addresses in batches.
               * EVM addresses need to be converted to human-readable strings. The address strings need to be in the same format
               * that would be used when querying the balance of that address.
               * @param startIndex The index of the first address in the batch.
               * @param endIndex The index of the last address in the batch. If `endIndex > getPoRAddressListLength()-1`,
               * endIndex need to default to `getPoRAddressListLength()-1`. If `endIndex < startIndex`, the result would be an
               * empty array.
               * @return Array of addresses as strings.
               */
              function getPoRAddressList(
                uint256 startIndex,
                uint256 endIndex
              ) external view returns (string[] memory);
            }
            // SPDX-License-Identifier: UNLICENSED
            pragma solidity 0.8.16;
            /**
             * @title IRateProvider
             * @notice This interface ensure compatibility with Balancer's Metastable pools, the getRate() method is used as the pool rate. This reduces arbitrages whenever the swETH rate increases from a repricing event.
             * @dev https://github.com/balancer-labs/metastable-rate-providers/blob/master/contracts/interfaces/IRateProvider.sol
             */
            interface IRateProvider {
              function getRate() external view returns (uint256);
            }