ethers.umd.js 1.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922
  1. const __$G = (typeof globalThis !== 'undefined' ? globalThis: typeof window !== 'undefined' ? window: typeof global !== 'undefined' ? global: typeof self !== 'undefined' ? self: {});
  2. (function (global, factory) {
  3. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  4. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  5. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ethers = {}));
  6. })(this, (function (exports) { 'use strict';
  7. /* Do NOT modify this file; see /src.ts/_admin/update-version.ts */
  8. /**
  9. * The current version of Ethers.
  10. */
  11. const version = "6.13.5";
  12. /**
  13. * Property helper functions.
  14. *
  15. * @_subsection api/utils:Properties [about-properties]
  16. */
  17. function checkType(value, type, name) {
  18. const types = type.split("|").map(t => t.trim());
  19. for (let i = 0; i < types.length; i++) {
  20. switch (type) {
  21. case "any":
  22. return;
  23. case "bigint":
  24. case "boolean":
  25. case "number":
  26. case "string":
  27. if (typeof (value) === type) {
  28. return;
  29. }
  30. }
  31. }
  32. const error = new Error(`invalid value for type ${type}`);
  33. error.code = "INVALID_ARGUMENT";
  34. error.argument = `value.${name}`;
  35. error.value = value;
  36. throw error;
  37. }
  38. /**
  39. * Resolves to a new object that is a copy of %%value%%, but with all
  40. * values resolved.
  41. */
  42. async function resolveProperties(value) {
  43. const keys = Object.keys(value);
  44. const results = await Promise.all(keys.map((k) => Promise.resolve(value[k])));
  45. return results.reduce((accum, v, index) => {
  46. accum[keys[index]] = v;
  47. return accum;
  48. }, {});
  49. }
  50. /**
  51. * Assigns the %%values%% to %%target%% as read-only values.
  52. *
  53. * It %%types%% is specified, the values are checked.
  54. */
  55. function defineProperties(target, values, types) {
  56. for (let key in values) {
  57. let value = values[key];
  58. const type = (types ? types[key] : null);
  59. if (type) {
  60. checkType(value, type, key);
  61. }
  62. Object.defineProperty(target, key, { enumerable: true, value, writable: false });
  63. }
  64. }
  65. /**
  66. * All errors in ethers include properties to ensure they are both
  67. * human-readable (i.e. ``.message``) and machine-readable (i.e. ``.code``).
  68. *
  69. * The [[isError]] function can be used to check the error ``code`` and
  70. * provide a type guard for the properties present on that error interface.
  71. *
  72. * @_section: api/utils/errors:Errors [about-errors]
  73. */
  74. function stringify$1(value) {
  75. if (value == null) {
  76. return "null";
  77. }
  78. if (Array.isArray(value)) {
  79. return "[ " + (value.map(stringify$1)).join(", ") + " ]";
  80. }
  81. if (value instanceof Uint8Array) {
  82. const HEX = "0123456789abcdef";
  83. let result = "0x";
  84. for (let i = 0; i < value.length; i++) {
  85. result += HEX[value[i] >> 4];
  86. result += HEX[value[i] & 0xf];
  87. }
  88. return result;
  89. }
  90. if (typeof (value) === "object" && typeof (value.toJSON) === "function") {
  91. return stringify$1(value.toJSON());
  92. }
  93. switch (typeof (value)) {
  94. case "boolean":
  95. case "symbol":
  96. return value.toString();
  97. case "bigint":
  98. return BigInt(value).toString();
  99. case "number":
  100. return (value).toString();
  101. case "string":
  102. return JSON.stringify(value);
  103. case "object": {
  104. const keys = Object.keys(value);
  105. keys.sort();
  106. return "{ " + keys.map((k) => `${stringify$1(k)}: ${stringify$1(value[k])}`).join(", ") + " }";
  107. }
  108. }
  109. return `[ COULD NOT SERIALIZE ]`;
  110. }
  111. /**
  112. * Returns true if the %%error%% matches an error thrown by ethers
  113. * that matches the error %%code%%.
  114. *
  115. * In TypeScript environments, this can be used to check that %%error%%
  116. * matches an EthersError type, which means the expected properties will
  117. * be set.
  118. *
  119. * @See [ErrorCodes](api:ErrorCode)
  120. * @example
  121. * try {
  122. * // code....
  123. * } catch (e) {
  124. * if (isError(e, "CALL_EXCEPTION")) {
  125. * // The Type Guard has validated this object
  126. * console.log(e.data);
  127. * }
  128. * }
  129. */
  130. function isError(error, code) {
  131. return (error && error.code === code);
  132. }
  133. /**
  134. * Returns true if %%error%% is a [[CallExceptionError].
  135. */
  136. function isCallException(error) {
  137. return isError(error, "CALL_EXCEPTION");
  138. }
  139. /**
  140. * Returns a new Error configured to the format ethers emits errors, with
  141. * the %%message%%, [[api:ErrorCode]] %%code%% and additional properties
  142. * for the corresponding EthersError.
  143. *
  144. * Each error in ethers includes the version of ethers, a
  145. * machine-readable [[ErrorCode]], and depending on %%code%%, additional
  146. * required properties. The error message will also include the %%message%%,
  147. * ethers version, %%code%% and all additional properties, serialized.
  148. */
  149. function makeError(message, code, info) {
  150. let shortMessage = message;
  151. {
  152. const details = [];
  153. if (info) {
  154. if ("message" in info || "code" in info || "name" in info) {
  155. throw new Error(`value will overwrite populated values: ${stringify$1(info)}`);
  156. }
  157. for (const key in info) {
  158. if (key === "shortMessage") {
  159. continue;
  160. }
  161. const value = (info[key]);
  162. // try {
  163. details.push(key + "=" + stringify$1(value));
  164. // } catch (error: any) {
  165. // console.log("MMM", error.message);
  166. // details.push(key + "=[could not serialize object]");
  167. // }
  168. }
  169. }
  170. details.push(`code=${code}`);
  171. details.push(`version=${version}`);
  172. if (details.length) {
  173. message += " (" + details.join(", ") + ")";
  174. }
  175. }
  176. let error;
  177. switch (code) {
  178. case "INVALID_ARGUMENT":
  179. error = new TypeError(message);
  180. break;
  181. case "NUMERIC_FAULT":
  182. case "BUFFER_OVERRUN":
  183. error = new RangeError(message);
  184. break;
  185. default:
  186. error = new Error(message);
  187. }
  188. defineProperties(error, { code });
  189. if (info) {
  190. Object.assign(error, info);
  191. }
  192. if (error.shortMessage == null) {
  193. defineProperties(error, { shortMessage });
  194. }
  195. return error;
  196. }
  197. /**
  198. * Throws an EthersError with %%message%%, %%code%% and additional error
  199. * %%info%% when %%check%% is falsish..
  200. *
  201. * @see [[api:makeError]]
  202. */
  203. function assert(check, message, code, info) {
  204. if (!check) {
  205. throw makeError(message, code, info);
  206. }
  207. }
  208. /**
  209. * A simple helper to simply ensuring provided arguments match expected
  210. * constraints, throwing if not.
  211. *
  212. * In TypeScript environments, the %%check%% has been asserted true, so
  213. * any further code does not need additional compile-time checks.
  214. */
  215. function assertArgument(check, message, name, value) {
  216. assert(check, message, "INVALID_ARGUMENT", { argument: name, value: value });
  217. }
  218. function assertArgumentCount(count, expectedCount, message) {
  219. if (message == null) {
  220. message = "";
  221. }
  222. if (message) {
  223. message = ": " + message;
  224. }
  225. assert(count >= expectedCount, "missing argument" + message, "MISSING_ARGUMENT", {
  226. count: count,
  227. expectedCount: expectedCount
  228. });
  229. assert(count <= expectedCount, "too many arguments" + message, "UNEXPECTED_ARGUMENT", {
  230. count: count,
  231. expectedCount: expectedCount
  232. });
  233. }
  234. const _normalizeForms = ["NFD", "NFC", "NFKD", "NFKC"].reduce((accum, form) => {
  235. try {
  236. // General test for normalize
  237. /* c8 ignore start */
  238. if ("test".normalize(form) !== "test") {
  239. throw new Error("bad");
  240. }
  241. ;
  242. /* c8 ignore stop */
  243. if (form === "NFD") {
  244. const check = String.fromCharCode(0xe9).normalize("NFD");
  245. const expected = String.fromCharCode(0x65, 0x0301);
  246. /* c8 ignore start */
  247. if (check !== expected) {
  248. throw new Error("broken");
  249. }
  250. /* c8 ignore stop */
  251. }
  252. accum.push(form);
  253. }
  254. catch (error) { }
  255. return accum;
  256. }, []);
  257. /**
  258. * Throws if the normalization %%form%% is not supported.
  259. */
  260. function assertNormalize(form) {
  261. assert(_normalizeForms.indexOf(form) >= 0, "platform missing String.prototype.normalize", "UNSUPPORTED_OPERATION", {
  262. operation: "String.prototype.normalize", info: { form }
  263. });
  264. }
  265. /**
  266. * Many classes use file-scoped values to guard the constructor,
  267. * making it effectively private. This facilitates that pattern
  268. * by ensuring the %%givenGaurd%% matches the file-scoped %%guard%%,
  269. * throwing if not, indicating the %%className%% if provided.
  270. */
  271. function assertPrivate(givenGuard, guard, className) {
  272. if (className == null) {
  273. className = "";
  274. }
  275. if (givenGuard !== guard) {
  276. let method = className, operation = "new";
  277. if (className) {
  278. method += ".";
  279. operation += " " + className;
  280. }
  281. assert(false, `private constructor; use ${method}from* methods`, "UNSUPPORTED_OPERATION", {
  282. operation
  283. });
  284. }
  285. }
  286. /**
  287. * Some data helpers.
  288. *
  289. *
  290. * @_subsection api/utils:Data Helpers [about-data]
  291. */
  292. function _getBytes(value, name, copy) {
  293. if (value instanceof Uint8Array) {
  294. if (copy) {
  295. return new Uint8Array(value);
  296. }
  297. return value;
  298. }
  299. if (typeof (value) === "string" && value.match(/^0x(?:[0-9a-f][0-9a-f])*$/i)) {
  300. const result = new Uint8Array((value.length - 2) / 2);
  301. let offset = 2;
  302. for (let i = 0; i < result.length; i++) {
  303. result[i] = parseInt(value.substring(offset, offset + 2), 16);
  304. offset += 2;
  305. }
  306. return result;
  307. }
  308. assertArgument(false, "invalid BytesLike value", name || "value", value);
  309. }
  310. /**
  311. * Get a typed Uint8Array for %%value%%. If already a Uint8Array
  312. * the original %%value%% is returned; if a copy is required use
  313. * [[getBytesCopy]].
  314. *
  315. * @see: getBytesCopy
  316. */
  317. function getBytes(value, name) {
  318. return _getBytes(value, name, false);
  319. }
  320. /**
  321. * Get a typed Uint8Array for %%value%%, creating a copy if necessary
  322. * to prevent any modifications of the returned value from being
  323. * reflected elsewhere.
  324. *
  325. * @see: getBytes
  326. */
  327. function getBytesCopy(value, name) {
  328. return _getBytes(value, name, true);
  329. }
  330. /**
  331. * Returns true if %%value%% is a valid [[HexString]].
  332. *
  333. * If %%length%% is ``true`` or a //number//, it also checks that
  334. * %%value%% is a valid [[DataHexString]] of %%length%% (if a //number//)
  335. * bytes of data (e.g. ``0x1234`` is 2 bytes).
  336. */
  337. function isHexString(value, length) {
  338. if (typeof (value) !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) {
  339. return false;
  340. }
  341. if (typeof (length) === "number" && value.length !== 2 + 2 * length) {
  342. return false;
  343. }
  344. if (length === true && (value.length % 2) !== 0) {
  345. return false;
  346. }
  347. return true;
  348. }
  349. /**
  350. * Returns true if %%value%% is a valid representation of arbitrary
  351. * data (i.e. a valid [[DataHexString]] or a Uint8Array).
  352. */
  353. function isBytesLike(value) {
  354. return (isHexString(value, true) || (value instanceof Uint8Array));
  355. }
  356. const HexCharacters = "0123456789abcdef";
  357. /**
  358. * Returns a [[DataHexString]] representation of %%data%%.
  359. */
  360. function hexlify(data) {
  361. const bytes = getBytes(data);
  362. let result = "0x";
  363. for (let i = 0; i < bytes.length; i++) {
  364. const v = bytes[i];
  365. result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f];
  366. }
  367. return result;
  368. }
  369. /**
  370. * Returns a [[DataHexString]] by concatenating all values
  371. * within %%data%%.
  372. */
  373. function concat(datas) {
  374. return "0x" + datas.map((d) => hexlify(d).substring(2)).join("");
  375. }
  376. /**
  377. * Returns the length of %%data%%, in bytes.
  378. */
  379. function dataLength(data) {
  380. if (isHexString(data, true)) {
  381. return (data.length - 2) / 2;
  382. }
  383. return getBytes(data).length;
  384. }
  385. /**
  386. * Returns a [[DataHexString]] by slicing %%data%% from the %%start%%
  387. * offset to the %%end%% offset.
  388. *
  389. * By default %%start%% is 0 and %%end%% is the length of %%data%%.
  390. */
  391. function dataSlice(data, start, end) {
  392. const bytes = getBytes(data);
  393. if (end != null && end > bytes.length) {
  394. assert(false, "cannot slice beyond data bounds", "BUFFER_OVERRUN", {
  395. buffer: bytes, length: bytes.length, offset: end
  396. });
  397. }
  398. return hexlify(bytes.slice((start == null) ? 0 : start, (end == null) ? bytes.length : end));
  399. }
  400. /**
  401. * Return the [[DataHexString]] result by stripping all **leading**
  402. ** zero bytes from %%data%%.
  403. */
  404. function stripZerosLeft(data) {
  405. let bytes = hexlify(data).substring(2);
  406. while (bytes.startsWith("00")) {
  407. bytes = bytes.substring(2);
  408. }
  409. return "0x" + bytes;
  410. }
  411. function zeroPad(data, length, left) {
  412. const bytes = getBytes(data);
  413. assert(length >= bytes.length, "padding exceeds data length", "BUFFER_OVERRUN", {
  414. buffer: new Uint8Array(bytes),
  415. length: length,
  416. offset: length + 1
  417. });
  418. const result = new Uint8Array(length);
  419. result.fill(0);
  420. if (left) {
  421. result.set(bytes, length - bytes.length);
  422. }
  423. else {
  424. result.set(bytes, 0);
  425. }
  426. return hexlify(result);
  427. }
  428. /**
  429. * Return the [[DataHexString]] of %%data%% padded on the **left**
  430. * to %%length%% bytes.
  431. *
  432. * If %%data%% already exceeds %%length%%, a [[BufferOverrunError]] is
  433. * thrown.
  434. *
  435. * This pads data the same as **values** are in Solidity
  436. * (e.g. ``uint128``).
  437. */
  438. function zeroPadValue(data, length) {
  439. return zeroPad(data, length, true);
  440. }
  441. /**
  442. * Return the [[DataHexString]] of %%data%% padded on the **right**
  443. * to %%length%% bytes.
  444. *
  445. * If %%data%% already exceeds %%length%%, a [[BufferOverrunError]] is
  446. * thrown.
  447. *
  448. * This pads data the same as **bytes** are in Solidity
  449. * (e.g. ``bytes16``).
  450. */
  451. function zeroPadBytes(data, length) {
  452. return zeroPad(data, length, false);
  453. }
  454. /**
  455. * Some mathematic operations.
  456. *
  457. * @_subsection: api/utils:Math Helpers [about-maths]
  458. */
  459. const BN_0$a = BigInt(0);
  460. const BN_1$5 = BigInt(1);
  461. //const BN_Max256 = (BN_1 << BigInt(256)) - BN_1;
  462. // IEEE 754 support 53-bits of mantissa
  463. const maxValue = 0x1fffffffffffff;
  464. /**
  465. * Convert %%value%% from a twos-compliment representation of %%width%%
  466. * bits to its value.
  467. *
  468. * If the highest bit is ``1``, the result will be negative.
  469. */
  470. function fromTwos(_value, _width) {
  471. const value = getUint(_value, "value");
  472. const width = BigInt(getNumber(_width, "width"));
  473. assert((value >> width) === BN_0$a, "overflow", "NUMERIC_FAULT", {
  474. operation: "fromTwos", fault: "overflow", value: _value
  475. });
  476. // Top bit set; treat as a negative value
  477. if (value >> (width - BN_1$5)) {
  478. const mask = (BN_1$5 << width) - BN_1$5;
  479. return -(((~value) & mask) + BN_1$5);
  480. }
  481. return value;
  482. }
  483. /**
  484. * Convert %%value%% to a twos-compliment representation of
  485. * %%width%% bits.
  486. *
  487. * The result will always be positive.
  488. */
  489. function toTwos(_value, _width) {
  490. let value = getBigInt(_value, "value");
  491. const width = BigInt(getNumber(_width, "width"));
  492. const limit = (BN_1$5 << (width - BN_1$5));
  493. if (value < BN_0$a) {
  494. value = -value;
  495. assert(value <= limit, "too low", "NUMERIC_FAULT", {
  496. operation: "toTwos", fault: "overflow", value: _value
  497. });
  498. const mask = (BN_1$5 << width) - BN_1$5;
  499. return ((~value) & mask) + BN_1$5;
  500. }
  501. else {
  502. assert(value < limit, "too high", "NUMERIC_FAULT", {
  503. operation: "toTwos", fault: "overflow", value: _value
  504. });
  505. }
  506. return value;
  507. }
  508. /**
  509. * Mask %%value%% with a bitmask of %%bits%% ones.
  510. */
  511. function mask(_value, _bits) {
  512. const value = getUint(_value, "value");
  513. const bits = BigInt(getNumber(_bits, "bits"));
  514. return value & ((BN_1$5 << bits) - BN_1$5);
  515. }
  516. /**
  517. * Gets a BigInt from %%value%%. If it is an invalid value for
  518. * a BigInt, then an ArgumentError will be thrown for %%name%%.
  519. */
  520. function getBigInt(value, name) {
  521. switch (typeof (value)) {
  522. case "bigint": return value;
  523. case "number":
  524. assertArgument(Number.isInteger(value), "underflow", name || "value", value);
  525. assertArgument(value >= -maxValue && value <= maxValue, "overflow", name || "value", value);
  526. return BigInt(value);
  527. case "string":
  528. try {
  529. if (value === "") {
  530. throw new Error("empty string");
  531. }
  532. if (value[0] === "-" && value[1] !== "-") {
  533. return -BigInt(value.substring(1));
  534. }
  535. return BigInt(value);
  536. }
  537. catch (e) {
  538. assertArgument(false, `invalid BigNumberish string: ${e.message}`, name || "value", value);
  539. }
  540. }
  541. assertArgument(false, "invalid BigNumberish value", name || "value", value);
  542. }
  543. /**
  544. * Returns %%value%% as a bigint, validating it is valid as a bigint
  545. * value and that it is positive.
  546. */
  547. function getUint(value, name) {
  548. const result = getBigInt(value, name);
  549. assert(result >= BN_0$a, "unsigned value cannot be negative", "NUMERIC_FAULT", {
  550. fault: "overflow", operation: "getUint", value
  551. });
  552. return result;
  553. }
  554. const Nibbles$1 = "0123456789abcdef";
  555. /*
  556. * Converts %%value%% to a BigInt. If %%value%% is a Uint8Array, it
  557. * is treated as Big Endian data.
  558. */
  559. function toBigInt(value) {
  560. if (value instanceof Uint8Array) {
  561. let result = "0x0";
  562. for (const v of value) {
  563. result += Nibbles$1[v >> 4];
  564. result += Nibbles$1[v & 0x0f];
  565. }
  566. return BigInt(result);
  567. }
  568. return getBigInt(value);
  569. }
  570. /**
  571. * Gets a //number// from %%value%%. If it is an invalid value for
  572. * a //number//, then an ArgumentError will be thrown for %%name%%.
  573. */
  574. function getNumber(value, name) {
  575. switch (typeof (value)) {
  576. case "bigint":
  577. assertArgument(value >= -maxValue && value <= maxValue, "overflow", name || "value", value);
  578. return Number(value);
  579. case "number":
  580. assertArgument(Number.isInteger(value), "underflow", name || "value", value);
  581. assertArgument(value >= -maxValue && value <= maxValue, "overflow", name || "value", value);
  582. return value;
  583. case "string":
  584. try {
  585. if (value === "") {
  586. throw new Error("empty string");
  587. }
  588. return getNumber(BigInt(value), name);
  589. }
  590. catch (e) {
  591. assertArgument(false, `invalid numeric string: ${e.message}`, name || "value", value);
  592. }
  593. }
  594. assertArgument(false, "invalid numeric value", name || "value", value);
  595. }
  596. /**
  597. * Converts %%value%% to a number. If %%value%% is a Uint8Array, it
  598. * is treated as Big Endian data. Throws if the value is not safe.
  599. */
  600. function toNumber(value) {
  601. return getNumber(toBigInt(value));
  602. }
  603. /**
  604. * Converts %%value%% to a Big Endian hexstring, optionally padded to
  605. * %%width%% bytes.
  606. */
  607. function toBeHex(_value, _width) {
  608. const value = getUint(_value, "value");
  609. let result = value.toString(16);
  610. if (_width == null) {
  611. // Ensure the value is of even length
  612. if (result.length % 2) {
  613. result = "0" + result;
  614. }
  615. }
  616. else {
  617. const width = getNumber(_width, "width");
  618. assert(width * 2 >= result.length, `value exceeds width (${width} bytes)`, "NUMERIC_FAULT", {
  619. operation: "toBeHex",
  620. fault: "overflow",
  621. value: _value
  622. });
  623. // Pad the value to the required width
  624. while (result.length < (width * 2)) {
  625. result = "0" + result;
  626. }
  627. }
  628. return "0x" + result;
  629. }
  630. /**
  631. * Converts %%value%% to a Big Endian Uint8Array.
  632. */
  633. function toBeArray(_value) {
  634. const value = getUint(_value, "value");
  635. if (value === BN_0$a) {
  636. return new Uint8Array([]);
  637. }
  638. let hex = value.toString(16);
  639. if (hex.length % 2) {
  640. hex = "0" + hex;
  641. }
  642. const result = new Uint8Array(hex.length / 2);
  643. for (let i = 0; i < result.length; i++) {
  644. const offset = i * 2;
  645. result[i] = parseInt(hex.substring(offset, offset + 2), 16);
  646. }
  647. return result;
  648. }
  649. /**
  650. * Returns a [[HexString]] for %%value%% safe to use as a //Quantity//.
  651. *
  652. * A //Quantity// does not have and leading 0 values unless the value is
  653. * the literal value `0x0`. This is most commonly used for JSSON-RPC
  654. * numeric values.
  655. */
  656. function toQuantity(value) {
  657. let result = hexlify(isBytesLike(value) ? value : toBeArray(value)).substring(2);
  658. while (result.startsWith("0")) {
  659. result = result.substring(1);
  660. }
  661. if (result === "") {
  662. result = "0";
  663. }
  664. return "0x" + result;
  665. }
  666. /**
  667. * The [Base58 Encoding](link-base58) scheme allows a **numeric** value
  668. * to be encoded as a compact string using a radix of 58 using only
  669. * alpha-numeric characters. Confusingly similar characters are omitted
  670. * (i.e. ``"l0O"``).
  671. *
  672. * Note that Base58 encodes a **numeric** value, not arbitrary bytes,
  673. * since any zero-bytes on the left would get removed. To mitigate this
  674. * issue most schemes that use Base58 choose specific high-order values
  675. * to ensure non-zero prefixes.
  676. *
  677. * @_subsection: api/utils:Base58 Encoding [about-base58]
  678. */
  679. const Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
  680. let Lookup = null;
  681. function getAlpha(letter) {
  682. if (Lookup == null) {
  683. Lookup = {};
  684. for (let i = 0; i < Alphabet.length; i++) {
  685. Lookup[Alphabet[i]] = BigInt(i);
  686. }
  687. }
  688. const result = Lookup[letter];
  689. assertArgument(result != null, `invalid base58 value`, "letter", letter);
  690. return result;
  691. }
  692. const BN_0$9 = BigInt(0);
  693. const BN_58 = BigInt(58);
  694. /**
  695. * Encode %%value%% as a Base58-encoded string.
  696. */
  697. function encodeBase58(_value) {
  698. const bytes = getBytes(_value);
  699. let value = toBigInt(bytes);
  700. let result = "";
  701. while (value) {
  702. result = Alphabet[Number(value % BN_58)] + result;
  703. value /= BN_58;
  704. }
  705. // Account for leading padding zeros
  706. for (let i = 0; i < bytes.length; i++) {
  707. if (bytes[i]) {
  708. break;
  709. }
  710. result = Alphabet[0] + result;
  711. }
  712. return result;
  713. }
  714. /**
  715. * Decode the Base58-encoded %%value%%.
  716. */
  717. function decodeBase58(value) {
  718. let result = BN_0$9;
  719. for (let i = 0; i < value.length; i++) {
  720. result *= BN_58;
  721. result += getAlpha(value[i]);
  722. }
  723. return result;
  724. }
  725. // utils/base64-browser
  726. function decodeBase64(textData) {
  727. textData = atob(textData);
  728. const data = new Uint8Array(textData.length);
  729. for (let i = 0; i < textData.length; i++) {
  730. data[i] = textData.charCodeAt(i);
  731. }
  732. return getBytes(data);
  733. }
  734. function encodeBase64(_data) {
  735. const data = getBytes(_data);
  736. let textData = "";
  737. for (let i = 0; i < data.length; i++) {
  738. textData += String.fromCharCode(data[i]);
  739. }
  740. return btoa(textData);
  741. }
  742. /**
  743. * Events allow for applications to use the observer pattern, which
  744. * allows subscribing and publishing events, outside the normal
  745. * execution paths.
  746. *
  747. * @_section api/utils/events:Events [about-events]
  748. */
  749. /**
  750. * When an [[EventEmitterable]] triggers a [[Listener]], the
  751. * callback always ahas one additional argument passed, which is
  752. * an **EventPayload**.
  753. */
  754. class EventPayload {
  755. /**
  756. * The event filter.
  757. */
  758. filter;
  759. /**
  760. * The **EventEmitterable**.
  761. */
  762. emitter;
  763. #listener;
  764. /**
  765. * Create a new **EventPayload** for %%emitter%% with
  766. * the %%listener%% and for %%filter%%.
  767. */
  768. constructor(emitter, listener, filter) {
  769. this.#listener = listener;
  770. defineProperties(this, { emitter, filter });
  771. }
  772. /**
  773. * Unregister the triggered listener for future events.
  774. */
  775. async removeListener() {
  776. if (this.#listener == null) {
  777. return;
  778. }
  779. await this.emitter.off(this.filter, this.#listener);
  780. }
  781. }
  782. /**
  783. * Using strings in Ethereum (or any security-basd system) requires
  784. * additional care. These utilities attempt to mitigate some of the
  785. * safety issues as well as provide the ability to recover and analyse
  786. * strings.
  787. *
  788. * @_subsection api/utils:Strings and UTF-8 [about-strings]
  789. */
  790. function errorFunc(reason, offset, bytes, output, badCodepoint) {
  791. assertArgument(false, `invalid codepoint at offset ${offset}; ${reason}`, "bytes", bytes);
  792. }
  793. function ignoreFunc(reason, offset, bytes, output, badCodepoint) {
  794. // If there is an invalid prefix (including stray continuation), skip any additional continuation bytes
  795. if (reason === "BAD_PREFIX" || reason === "UNEXPECTED_CONTINUE") {
  796. let i = 0;
  797. for (let o = offset + 1; o < bytes.length; o++) {
  798. if (bytes[o] >> 6 !== 0x02) {
  799. break;
  800. }
  801. i++;
  802. }
  803. return i;
  804. }
  805. // This byte runs us past the end of the string, so just jump to the end
  806. // (but the first byte was read already read and therefore skipped)
  807. if (reason === "OVERRUN") {
  808. return bytes.length - offset - 1;
  809. }
  810. // Nothing to skip
  811. return 0;
  812. }
  813. function replaceFunc(reason, offset, bytes, output, badCodepoint) {
  814. // Overlong representations are otherwise "valid" code points; just non-deistingtished
  815. if (reason === "OVERLONG") {
  816. assertArgument(typeof (badCodepoint) === "number", "invalid bad code point for replacement", "badCodepoint", badCodepoint);
  817. output.push(badCodepoint);
  818. return 0;
  819. }
  820. // Put the replacement character into the output
  821. output.push(0xfffd);
  822. // Otherwise, process as if ignoring errors
  823. return ignoreFunc(reason, offset, bytes);
  824. }
  825. /**
  826. * A handful of popular, built-in UTF-8 error handling strategies.
  827. *
  828. * **``"error"``** - throws on ANY illegal UTF-8 sequence or
  829. * non-canonical (overlong) codepoints (this is the default)
  830. *
  831. * **``"ignore"``** - silently drops any illegal UTF-8 sequence
  832. * and accepts non-canonical (overlong) codepoints
  833. *
  834. * **``"replace"``** - replace any illegal UTF-8 sequence with the
  835. * UTF-8 replacement character (i.e. ``"\\ufffd"``) and accepts
  836. * non-canonical (overlong) codepoints
  837. *
  838. * @returns: Record<"error" | "ignore" | "replace", Utf8ErrorFunc>
  839. */
  840. const Utf8ErrorFuncs = Object.freeze({
  841. error: errorFunc,
  842. ignore: ignoreFunc,
  843. replace: replaceFunc
  844. });
  845. // http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499
  846. function getUtf8CodePoints(_bytes, onError) {
  847. if (onError == null) {
  848. onError = Utf8ErrorFuncs.error;
  849. }
  850. const bytes = getBytes(_bytes, "bytes");
  851. const result = [];
  852. let i = 0;
  853. // Invalid bytes are ignored
  854. while (i < bytes.length) {
  855. const c = bytes[i++];
  856. // 0xxx xxxx
  857. if (c >> 7 === 0) {
  858. result.push(c);
  859. continue;
  860. }
  861. // Multibyte; how many bytes left for this character?
  862. let extraLength = null;
  863. let overlongMask = null;
  864. // 110x xxxx 10xx xxxx
  865. if ((c & 0xe0) === 0xc0) {
  866. extraLength = 1;
  867. overlongMask = 0x7f;
  868. // 1110 xxxx 10xx xxxx 10xx xxxx
  869. }
  870. else if ((c & 0xf0) === 0xe0) {
  871. extraLength = 2;
  872. overlongMask = 0x7ff;
  873. // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx
  874. }
  875. else if ((c & 0xf8) === 0xf0) {
  876. extraLength = 3;
  877. overlongMask = 0xffff;
  878. }
  879. else {
  880. if ((c & 0xc0) === 0x80) {
  881. i += onError("UNEXPECTED_CONTINUE", i - 1, bytes, result);
  882. }
  883. else {
  884. i += onError("BAD_PREFIX", i - 1, bytes, result);
  885. }
  886. continue;
  887. }
  888. // Do we have enough bytes in our data?
  889. if (i - 1 + extraLength >= bytes.length) {
  890. i += onError("OVERRUN", i - 1, bytes, result);
  891. continue;
  892. }
  893. // Remove the length prefix from the char
  894. let res = c & ((1 << (8 - extraLength - 1)) - 1);
  895. for (let j = 0; j < extraLength; j++) {
  896. let nextChar = bytes[i];
  897. // Invalid continuation byte
  898. if ((nextChar & 0xc0) != 0x80) {
  899. i += onError("MISSING_CONTINUE", i, bytes, result);
  900. res = null;
  901. break;
  902. }
  903. res = (res << 6) | (nextChar & 0x3f);
  904. i++;
  905. }
  906. // See above loop for invalid continuation byte
  907. if (res === null) {
  908. continue;
  909. }
  910. // Maximum code point
  911. if (res > 0x10ffff) {
  912. i += onError("OUT_OF_RANGE", i - 1 - extraLength, bytes, result, res);
  913. continue;
  914. }
  915. // Reserved for UTF-16 surrogate halves
  916. if (res >= 0xd800 && res <= 0xdfff) {
  917. i += onError("UTF16_SURROGATE", i - 1 - extraLength, bytes, result, res);
  918. continue;
  919. }
  920. // Check for overlong sequences (more bytes than needed)
  921. if (res <= overlongMask) {
  922. i += onError("OVERLONG", i - 1 - extraLength, bytes, result, res);
  923. continue;
  924. }
  925. result.push(res);
  926. }
  927. return result;
  928. }
  929. // http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array
  930. /**
  931. * Returns the UTF-8 byte representation of %%str%%.
  932. *
  933. * If %%form%% is specified, the string is normalized.
  934. */
  935. function toUtf8Bytes(str, form) {
  936. assertArgument(typeof (str) === "string", "invalid string value", "str", str);
  937. if (form != null) {
  938. assertNormalize(form);
  939. str = str.normalize(form);
  940. }
  941. let result = [];
  942. for (let i = 0; i < str.length; i++) {
  943. const c = str.charCodeAt(i);
  944. if (c < 0x80) {
  945. result.push(c);
  946. }
  947. else if (c < 0x800) {
  948. result.push((c >> 6) | 0xc0);
  949. result.push((c & 0x3f) | 0x80);
  950. }
  951. else if ((c & 0xfc00) == 0xd800) {
  952. i++;
  953. const c2 = str.charCodeAt(i);
  954. assertArgument(i < str.length && ((c2 & 0xfc00) === 0xdc00), "invalid surrogate pair", "str", str);
  955. // Surrogate Pair
  956. const pair = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff);
  957. result.push((pair >> 18) | 0xf0);
  958. result.push(((pair >> 12) & 0x3f) | 0x80);
  959. result.push(((pair >> 6) & 0x3f) | 0x80);
  960. result.push((pair & 0x3f) | 0x80);
  961. }
  962. else {
  963. result.push((c >> 12) | 0xe0);
  964. result.push(((c >> 6) & 0x3f) | 0x80);
  965. result.push((c & 0x3f) | 0x80);
  966. }
  967. }
  968. return new Uint8Array(result);
  969. }
  970. //export
  971. function _toUtf8String(codePoints) {
  972. return codePoints.map((codePoint) => {
  973. if (codePoint <= 0xffff) {
  974. return String.fromCharCode(codePoint);
  975. }
  976. codePoint -= 0x10000;
  977. return String.fromCharCode((((codePoint >> 10) & 0x3ff) + 0xd800), ((codePoint & 0x3ff) + 0xdc00));
  978. }).join("");
  979. }
  980. /**
  981. * Returns the string represented by the UTF-8 data %%bytes%%.
  982. *
  983. * When %%onError%% function is specified, it is called on UTF-8
  984. * errors allowing recovery using the [[Utf8ErrorFunc]] API.
  985. * (default: [error](Utf8ErrorFuncs))
  986. */
  987. function toUtf8String(bytes, onError) {
  988. return _toUtf8String(getUtf8CodePoints(bytes, onError));
  989. }
  990. /**
  991. * Returns the UTF-8 code-points for %%str%%.
  992. *
  993. * If %%form%% is specified, the string is normalized.
  994. */
  995. function toUtf8CodePoints(str, form) {
  996. return getUtf8CodePoints(toUtf8Bytes(str, form));
  997. }
  998. function createGetUrl(options) {
  999. async function getUrl(req, _signal) {
  1000. assert(_signal == null || !_signal.cancelled, "request cancelled before sending", "CANCELLED");
  1001. const protocol = req.url.split(":")[0].toLowerCase();
  1002. assert(protocol === "http" || protocol === "https", `unsupported protocol ${protocol}`, "UNSUPPORTED_OPERATION", {
  1003. info: { protocol },
  1004. operation: "request"
  1005. });
  1006. assert(protocol === "https" || !req.credentials || req.allowInsecureAuthentication, "insecure authorized connections unsupported", "UNSUPPORTED_OPERATION", {
  1007. operation: "request"
  1008. });
  1009. let error = null;
  1010. const controller = new AbortController();
  1011. const timer = setTimeout(() => {
  1012. error = makeError("request timeout", "TIMEOUT");
  1013. controller.abort();
  1014. }, req.timeout);
  1015. if (_signal) {
  1016. _signal.addListener(() => {
  1017. error = makeError("request cancelled", "CANCELLED");
  1018. controller.abort();
  1019. });
  1020. }
  1021. const init = {
  1022. method: req.method,
  1023. headers: new Headers(Array.from(req)),
  1024. body: req.body || undefined,
  1025. signal: controller.signal
  1026. };
  1027. let resp;
  1028. try {
  1029. resp = await fetch(req.url, init);
  1030. }
  1031. catch (_error) {
  1032. clearTimeout(timer);
  1033. if (error) {
  1034. throw error;
  1035. }
  1036. throw _error;
  1037. }
  1038. clearTimeout(timer);
  1039. const headers = {};
  1040. resp.headers.forEach((value, key) => {
  1041. headers[key.toLowerCase()] = value;
  1042. });
  1043. const respBody = await resp.arrayBuffer();
  1044. const body = (respBody == null) ? null : new Uint8Array(respBody);
  1045. return {
  1046. statusCode: resp.status,
  1047. statusMessage: resp.statusText,
  1048. headers, body
  1049. };
  1050. }
  1051. return getUrl;
  1052. }
  1053. /**
  1054. * Fetching content from the web is environment-specific, so Ethers
  1055. * provides an abstraction that each environment can implement to provide
  1056. * this service.
  1057. *
  1058. * On [Node.js](link-node), the ``http`` and ``https`` libs are used to
  1059. * create a request object, register event listeners and process data
  1060. * and populate the [[FetchResponse]].
  1061. *
  1062. * In a browser, the [DOM fetch](link-js-fetch) is used, and the resulting
  1063. * ``Promise`` is waited on to retrieve the payload.
  1064. *
  1065. * The [[FetchRequest]] is responsible for handling many common situations,
  1066. * such as redirects, server throttling, authentication, etc.
  1067. *
  1068. * It also handles common gateways, such as IPFS and data URIs.
  1069. *
  1070. * @_section api/utils/fetching:Fetching Web Content [about-fetch]
  1071. */
  1072. const MAX_ATTEMPTS = 12;
  1073. const SLOT_INTERVAL = 250;
  1074. // The global FetchGetUrlFunc implementation.
  1075. let defaultGetUrlFunc = createGetUrl();
  1076. const reData = new RegExp("^data:([^;:]*)?(;base64)?,(.*)$", "i");
  1077. const reIpfs = new RegExp("^ipfs:/\/(ipfs/)?(.*)$", "i");
  1078. // If locked, new Gateways cannot be added
  1079. let locked$5 = false;
  1080. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs
  1081. async function dataGatewayFunc(url, signal) {
  1082. try {
  1083. const match = url.match(reData);
  1084. if (!match) {
  1085. throw new Error("invalid data");
  1086. }
  1087. return new FetchResponse(200, "OK", {
  1088. "content-type": (match[1] || "text/plain"),
  1089. }, (match[2] ? decodeBase64(match[3]) : unpercent(match[3])));
  1090. }
  1091. catch (error) {
  1092. return new FetchResponse(599, "BAD REQUEST (invalid data: URI)", {}, null, new FetchRequest(url));
  1093. }
  1094. }
  1095. /**
  1096. * Returns a [[FetchGatewayFunc]] for fetching content from a standard
  1097. * IPFS gateway hosted at %%baseUrl%%.
  1098. */
  1099. function getIpfsGatewayFunc(baseUrl) {
  1100. async function gatewayIpfs(url, signal) {
  1101. try {
  1102. const match = url.match(reIpfs);
  1103. if (!match) {
  1104. throw new Error("invalid link");
  1105. }
  1106. return new FetchRequest(`${baseUrl}${match[2]}`);
  1107. }
  1108. catch (error) {
  1109. return new FetchResponse(599, "BAD REQUEST (invalid IPFS URI)", {}, null, new FetchRequest(url));
  1110. }
  1111. }
  1112. return gatewayIpfs;
  1113. }
  1114. const Gateways = {
  1115. "data": dataGatewayFunc,
  1116. "ipfs": getIpfsGatewayFunc("https:/\/gateway.ipfs.io/ipfs/")
  1117. };
  1118. const fetchSignals = new WeakMap();
  1119. /**
  1120. * @_ignore
  1121. */
  1122. class FetchCancelSignal {
  1123. #listeners;
  1124. #cancelled;
  1125. constructor(request) {
  1126. this.#listeners = [];
  1127. this.#cancelled = false;
  1128. fetchSignals.set(request, () => {
  1129. if (this.#cancelled) {
  1130. return;
  1131. }
  1132. this.#cancelled = true;
  1133. for (const listener of this.#listeners) {
  1134. setTimeout(() => { listener(); }, 0);
  1135. }
  1136. this.#listeners = [];
  1137. });
  1138. }
  1139. addListener(listener) {
  1140. assert(!this.#cancelled, "singal already cancelled", "UNSUPPORTED_OPERATION", {
  1141. operation: "fetchCancelSignal.addCancelListener"
  1142. });
  1143. this.#listeners.push(listener);
  1144. }
  1145. get cancelled() { return this.#cancelled; }
  1146. checkSignal() {
  1147. assert(!this.cancelled, "cancelled", "CANCELLED", {});
  1148. }
  1149. }
  1150. // Check the signal, throwing if it is cancelled
  1151. function checkSignal(signal) {
  1152. if (signal == null) {
  1153. throw new Error("missing signal; should not happen");
  1154. }
  1155. signal.checkSignal();
  1156. return signal;
  1157. }
  1158. /**
  1159. * Represents a request for a resource using a URI.
  1160. *
  1161. * By default, the supported schemes are ``HTTP``, ``HTTPS``, ``data:``,
  1162. * and ``IPFS:``.
  1163. *
  1164. * Additional schemes can be added globally using [[registerGateway]].
  1165. *
  1166. * @example:
  1167. * req = new FetchRequest("https://www.ricmoo.com")
  1168. * resp = await req.send()
  1169. * resp.body.length
  1170. * //_result:
  1171. */
  1172. class FetchRequest {
  1173. #allowInsecure;
  1174. #gzip;
  1175. #headers;
  1176. #method;
  1177. #timeout;
  1178. #url;
  1179. #body;
  1180. #bodyType;
  1181. #creds;
  1182. // Hooks
  1183. #preflight;
  1184. #process;
  1185. #retry;
  1186. #signal;
  1187. #throttle;
  1188. #getUrlFunc;
  1189. /**
  1190. * The fetch URL to request.
  1191. */
  1192. get url() { return this.#url; }
  1193. set url(url) {
  1194. this.#url = String(url);
  1195. }
  1196. /**
  1197. * The fetch body, if any, to send as the request body. //(default: null)//
  1198. *
  1199. * When setting a body, the intrinsic ``Content-Type`` is automatically
  1200. * set and will be used if **not overridden** by setting a custom
  1201. * header.
  1202. *
  1203. * If %%body%% is null, the body is cleared (along with the
  1204. * intrinsic ``Content-Type``).
  1205. *
  1206. * If %%body%% is a string, the intrinsic ``Content-Type`` is set to
  1207. * ``text/plain``.
  1208. *
  1209. * If %%body%% is a Uint8Array, the intrinsic ``Content-Type`` is set to
  1210. * ``application/octet-stream``.
  1211. *
  1212. * If %%body%% is any other object, the intrinsic ``Content-Type`` is
  1213. * set to ``application/json``.
  1214. */
  1215. get body() {
  1216. if (this.#body == null) {
  1217. return null;
  1218. }
  1219. return new Uint8Array(this.#body);
  1220. }
  1221. set body(body) {
  1222. if (body == null) {
  1223. this.#body = undefined;
  1224. this.#bodyType = undefined;
  1225. }
  1226. else if (typeof (body) === "string") {
  1227. this.#body = toUtf8Bytes(body);
  1228. this.#bodyType = "text/plain";
  1229. }
  1230. else if (body instanceof Uint8Array) {
  1231. this.#body = body;
  1232. this.#bodyType = "application/octet-stream";
  1233. }
  1234. else if (typeof (body) === "object") {
  1235. this.#body = toUtf8Bytes(JSON.stringify(body));
  1236. this.#bodyType = "application/json";
  1237. }
  1238. else {
  1239. throw new Error("invalid body");
  1240. }
  1241. }
  1242. /**
  1243. * Returns true if the request has a body.
  1244. */
  1245. hasBody() {
  1246. return (this.#body != null);
  1247. }
  1248. /**
  1249. * The HTTP method to use when requesting the URI. If no method
  1250. * has been explicitly set, then ``GET`` is used if the body is
  1251. * null and ``POST`` otherwise.
  1252. */
  1253. get method() {
  1254. if (this.#method) {
  1255. return this.#method;
  1256. }
  1257. if (this.hasBody()) {
  1258. return "POST";
  1259. }
  1260. return "GET";
  1261. }
  1262. set method(method) {
  1263. if (method == null) {
  1264. method = "";
  1265. }
  1266. this.#method = String(method).toUpperCase();
  1267. }
  1268. /**
  1269. * The headers that will be used when requesting the URI. All
  1270. * keys are lower-case.
  1271. *
  1272. * This object is a copy, so any changes will **NOT** be reflected
  1273. * in the ``FetchRequest``.
  1274. *
  1275. * To set a header entry, use the ``setHeader`` method.
  1276. */
  1277. get headers() {
  1278. const headers = Object.assign({}, this.#headers);
  1279. if (this.#creds) {
  1280. headers["authorization"] = `Basic ${encodeBase64(toUtf8Bytes(this.#creds))}`;
  1281. }
  1282. if (this.allowGzip) {
  1283. headers["accept-encoding"] = "gzip";
  1284. }
  1285. if (headers["content-type"] == null && this.#bodyType) {
  1286. headers["content-type"] = this.#bodyType;
  1287. }
  1288. if (this.body) {
  1289. headers["content-length"] = String(this.body.length);
  1290. }
  1291. return headers;
  1292. }
  1293. /**
  1294. * Get the header for %%key%%, ignoring case.
  1295. */
  1296. getHeader(key) {
  1297. return this.headers[key.toLowerCase()];
  1298. }
  1299. /**
  1300. * Set the header for %%key%% to %%value%%. All values are coerced
  1301. * to a string.
  1302. */
  1303. setHeader(key, value) {
  1304. this.#headers[String(key).toLowerCase()] = String(value);
  1305. }
  1306. /**
  1307. * Clear all headers, resetting all intrinsic headers.
  1308. */
  1309. clearHeaders() {
  1310. this.#headers = {};
  1311. }
  1312. [Symbol.iterator]() {
  1313. const headers = this.headers;
  1314. const keys = Object.keys(headers);
  1315. let index = 0;
  1316. return {
  1317. next: () => {
  1318. if (index < keys.length) {
  1319. const key = keys[index++];
  1320. return {
  1321. value: [key, headers[key]], done: false
  1322. };
  1323. }
  1324. return { value: undefined, done: true };
  1325. }
  1326. };
  1327. }
  1328. /**
  1329. * The value that will be sent for the ``Authorization`` header.
  1330. *
  1331. * To set the credentials, use the ``setCredentials`` method.
  1332. */
  1333. get credentials() {
  1334. return this.#creds || null;
  1335. }
  1336. /**
  1337. * Sets an ``Authorization`` for %%username%% with %%password%%.
  1338. */
  1339. setCredentials(username, password) {
  1340. assertArgument(!username.match(/:/), "invalid basic authentication username", "username", "[REDACTED]");
  1341. this.#creds = `${username}:${password}`;
  1342. }
  1343. /**
  1344. * Enable and request gzip-encoded responses. The response will
  1345. * automatically be decompressed. //(default: true)//
  1346. */
  1347. get allowGzip() {
  1348. return this.#gzip;
  1349. }
  1350. set allowGzip(value) {
  1351. this.#gzip = !!value;
  1352. }
  1353. /**
  1354. * Allow ``Authentication`` credentials to be sent over insecure
  1355. * channels. //(default: false)//
  1356. */
  1357. get allowInsecureAuthentication() {
  1358. return !!this.#allowInsecure;
  1359. }
  1360. set allowInsecureAuthentication(value) {
  1361. this.#allowInsecure = !!value;
  1362. }
  1363. /**
  1364. * The timeout (in milliseconds) to wait for a complete response.
  1365. * //(default: 5 minutes)//
  1366. */
  1367. get timeout() { return this.#timeout; }
  1368. set timeout(timeout) {
  1369. assertArgument(timeout >= 0, "timeout must be non-zero", "timeout", timeout);
  1370. this.#timeout = timeout;
  1371. }
  1372. /**
  1373. * This function is called prior to each request, for example
  1374. * during a redirection or retry in case of server throttling.
  1375. *
  1376. * This offers an opportunity to populate headers or update
  1377. * content before sending a request.
  1378. */
  1379. get preflightFunc() {
  1380. return this.#preflight || null;
  1381. }
  1382. set preflightFunc(preflight) {
  1383. this.#preflight = preflight;
  1384. }
  1385. /**
  1386. * This function is called after each response, offering an
  1387. * opportunity to provide client-level throttling or updating
  1388. * response data.
  1389. *
  1390. * Any error thrown in this causes the ``send()`` to throw.
  1391. *
  1392. * To schedule a retry attempt (assuming the maximum retry limit
  1393. * has not been reached), use [[response.throwThrottleError]].
  1394. */
  1395. get processFunc() {
  1396. return this.#process || null;
  1397. }
  1398. set processFunc(process) {
  1399. this.#process = process;
  1400. }
  1401. /**
  1402. * This function is called on each retry attempt.
  1403. */
  1404. get retryFunc() {
  1405. return this.#retry || null;
  1406. }
  1407. set retryFunc(retry) {
  1408. this.#retry = retry;
  1409. }
  1410. /**
  1411. * This function is called to fetch content from HTTP and
  1412. * HTTPS URLs and is platform specific (e.g. nodejs vs
  1413. * browsers).
  1414. *
  1415. * This is by default the currently registered global getUrl
  1416. * function, which can be changed using [[registerGetUrl]].
  1417. * If this has been set, setting is to ``null`` will cause
  1418. * this FetchRequest (and any future clones) to revert back to
  1419. * using the currently registered global getUrl function.
  1420. *
  1421. * Setting this is generally not necessary, but may be useful
  1422. * for developers that wish to intercept requests or to
  1423. * configurege a proxy or other agent.
  1424. */
  1425. get getUrlFunc() {
  1426. return this.#getUrlFunc || defaultGetUrlFunc;
  1427. }
  1428. set getUrlFunc(value) {
  1429. this.#getUrlFunc = value;
  1430. }
  1431. /**
  1432. * Create a new FetchRequest instance with default values.
  1433. *
  1434. * Once created, each property may be set before issuing a
  1435. * ``.send()`` to make the request.
  1436. */
  1437. constructor(url) {
  1438. this.#url = String(url);
  1439. this.#allowInsecure = false;
  1440. this.#gzip = true;
  1441. this.#headers = {};
  1442. this.#method = "";
  1443. this.#timeout = 300000;
  1444. this.#throttle = {
  1445. slotInterval: SLOT_INTERVAL,
  1446. maxAttempts: MAX_ATTEMPTS
  1447. };
  1448. this.#getUrlFunc = null;
  1449. }
  1450. toString() {
  1451. return `<FetchRequest method=${JSON.stringify(this.method)} url=${JSON.stringify(this.url)} headers=${JSON.stringify(this.headers)} body=${this.#body ? hexlify(this.#body) : "null"}>`;
  1452. }
  1453. /**
  1454. * Update the throttle parameters used to determine maximum
  1455. * attempts and exponential-backoff properties.
  1456. */
  1457. setThrottleParams(params) {
  1458. if (params.slotInterval != null) {
  1459. this.#throttle.slotInterval = params.slotInterval;
  1460. }
  1461. if (params.maxAttempts != null) {
  1462. this.#throttle.maxAttempts = params.maxAttempts;
  1463. }
  1464. }
  1465. async #send(attempt, expires, delay, _request, _response) {
  1466. if (attempt >= this.#throttle.maxAttempts) {
  1467. return _response.makeServerError("exceeded maximum retry limit");
  1468. }
  1469. assert(getTime$2() <= expires, "timeout", "TIMEOUT", {
  1470. operation: "request.send", reason: "timeout", request: _request
  1471. });
  1472. if (delay > 0) {
  1473. await wait(delay);
  1474. }
  1475. let req = this.clone();
  1476. const scheme = (req.url.split(":")[0] || "").toLowerCase();
  1477. // Process any Gateways
  1478. if (scheme in Gateways) {
  1479. const result = await Gateways[scheme](req.url, checkSignal(_request.#signal));
  1480. if (result instanceof FetchResponse) {
  1481. let response = result;
  1482. if (this.processFunc) {
  1483. checkSignal(_request.#signal);
  1484. try {
  1485. response = await this.processFunc(req, response);
  1486. }
  1487. catch (error) {
  1488. // Something went wrong during processing; throw a 5xx server error
  1489. if (error.throttle == null || typeof (error.stall) !== "number") {
  1490. response.makeServerError("error in post-processing function", error).assertOk();
  1491. }
  1492. // Ignore throttling
  1493. }
  1494. }
  1495. return response;
  1496. }
  1497. req = result;
  1498. }
  1499. // We have a preflight function; update the request
  1500. if (this.preflightFunc) {
  1501. req = await this.preflightFunc(req);
  1502. }
  1503. const resp = await this.getUrlFunc(req, checkSignal(_request.#signal));
  1504. let response = new FetchResponse(resp.statusCode, resp.statusMessage, resp.headers, resp.body, _request);
  1505. if (response.statusCode === 301 || response.statusCode === 302) {
  1506. // Redirect
  1507. try {
  1508. const location = response.headers.location || "";
  1509. return req.redirect(location).#send(attempt + 1, expires, 0, _request, response);
  1510. }
  1511. catch (error) { }
  1512. // Things won't get any better on another attempt; abort
  1513. return response;
  1514. }
  1515. else if (response.statusCode === 429) {
  1516. // Throttle
  1517. if (this.retryFunc == null || (await this.retryFunc(req, response, attempt))) {
  1518. const retryAfter = response.headers["retry-after"];
  1519. let delay = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt));
  1520. if (typeof (retryAfter) === "string" && retryAfter.match(/^[1-9][0-9]*$/)) {
  1521. delay = parseInt(retryAfter);
  1522. }
  1523. return req.clone().#send(attempt + 1, expires, delay, _request, response);
  1524. }
  1525. }
  1526. if (this.processFunc) {
  1527. checkSignal(_request.#signal);
  1528. try {
  1529. response = await this.processFunc(req, response);
  1530. }
  1531. catch (error) {
  1532. // Something went wrong during processing; throw a 5xx server error
  1533. if (error.throttle == null || typeof (error.stall) !== "number") {
  1534. response.makeServerError("error in post-processing function", error).assertOk();
  1535. }
  1536. // Throttle
  1537. let delay = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt));
  1538. if (error.stall >= 0) {
  1539. delay = error.stall;
  1540. }
  1541. return req.clone().#send(attempt + 1, expires, delay, _request, response);
  1542. }
  1543. }
  1544. return response;
  1545. }
  1546. /**
  1547. * Resolves to the response by sending the request.
  1548. */
  1549. send() {
  1550. assert(this.#signal == null, "request already sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.send" });
  1551. this.#signal = new FetchCancelSignal(this);
  1552. return this.#send(0, getTime$2() + this.timeout, 0, this, new FetchResponse(0, "", {}, null, this));
  1553. }
  1554. /**
  1555. * Cancels the inflight response, causing a ``CANCELLED``
  1556. * error to be rejected from the [[send]].
  1557. */
  1558. cancel() {
  1559. assert(this.#signal != null, "request has not been sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.cancel" });
  1560. const signal = fetchSignals.get(this);
  1561. if (!signal) {
  1562. throw new Error("missing signal; should not happen");
  1563. }
  1564. signal();
  1565. }
  1566. /**
  1567. * Returns a new [[FetchRequest]] that represents the redirection
  1568. * to %%location%%.
  1569. */
  1570. redirect(location) {
  1571. // Redirection; for now we only support absolute locations
  1572. const current = this.url.split(":")[0].toLowerCase();
  1573. const target = location.split(":")[0].toLowerCase();
  1574. // Don't allow redirecting:
  1575. // - non-GET requests
  1576. // - downgrading the security (e.g. https => http)
  1577. // - to non-HTTP (or non-HTTPS) protocols [this could be relaxed?]
  1578. assert(this.method === "GET" && (current !== "https" || target !== "http") && location.match(/^https?:/), `unsupported redirect`, "UNSUPPORTED_OPERATION", {
  1579. operation: `redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(location)})`
  1580. });
  1581. // Create a copy of this request, with a new URL
  1582. const req = new FetchRequest(location);
  1583. req.method = "GET";
  1584. req.allowGzip = this.allowGzip;
  1585. req.timeout = this.timeout;
  1586. req.#headers = Object.assign({}, this.#headers);
  1587. if (this.#body) {
  1588. req.#body = new Uint8Array(this.#body);
  1589. }
  1590. req.#bodyType = this.#bodyType;
  1591. // Do not forward credentials unless on the same domain; only absolute
  1592. //req.allowInsecure = false;
  1593. // paths are currently supported; may want a way to specify to forward?
  1594. //setStore(req.#props, "creds", getStore(this.#pros, "creds"));
  1595. return req;
  1596. }
  1597. /**
  1598. * Create a new copy of this request.
  1599. */
  1600. clone() {
  1601. const clone = new FetchRequest(this.url);
  1602. // Preserve "default method" (i.e. null)
  1603. clone.#method = this.#method;
  1604. // Preserve "default body" with type, copying the Uint8Array is present
  1605. if (this.#body) {
  1606. clone.#body = this.#body;
  1607. }
  1608. clone.#bodyType = this.#bodyType;
  1609. // Preserve "default headers"
  1610. clone.#headers = Object.assign({}, this.#headers);
  1611. // Credentials is readonly, so we copy internally
  1612. clone.#creds = this.#creds;
  1613. if (this.allowGzip) {
  1614. clone.allowGzip = true;
  1615. }
  1616. clone.timeout = this.timeout;
  1617. if (this.allowInsecureAuthentication) {
  1618. clone.allowInsecureAuthentication = true;
  1619. }
  1620. clone.#preflight = this.#preflight;
  1621. clone.#process = this.#process;
  1622. clone.#retry = this.#retry;
  1623. clone.#throttle = Object.assign({}, this.#throttle);
  1624. clone.#getUrlFunc = this.#getUrlFunc;
  1625. return clone;
  1626. }
  1627. /**
  1628. * Locks all static configuration for gateways and FetchGetUrlFunc
  1629. * registration.
  1630. */
  1631. static lockConfig() {
  1632. locked$5 = true;
  1633. }
  1634. /**
  1635. * Get the current Gateway function for %%scheme%%.
  1636. */
  1637. static getGateway(scheme) {
  1638. return Gateways[scheme.toLowerCase()] || null;
  1639. }
  1640. /**
  1641. * Use the %%func%% when fetching URIs using %%scheme%%.
  1642. *
  1643. * This method affects all requests globally.
  1644. *
  1645. * If [[lockConfig]] has been called, no change is made and this
  1646. * throws.
  1647. */
  1648. static registerGateway(scheme, func) {
  1649. scheme = scheme.toLowerCase();
  1650. if (scheme === "http" || scheme === "https") {
  1651. throw new Error(`cannot intercept ${scheme}; use registerGetUrl`);
  1652. }
  1653. if (locked$5) {
  1654. throw new Error("gateways locked");
  1655. }
  1656. Gateways[scheme] = func;
  1657. }
  1658. /**
  1659. * Use %%getUrl%% when fetching URIs over HTTP and HTTPS requests.
  1660. *
  1661. * This method affects all requests globally.
  1662. *
  1663. * If [[lockConfig]] has been called, no change is made and this
  1664. * throws.
  1665. */
  1666. static registerGetUrl(getUrl) {
  1667. if (locked$5) {
  1668. throw new Error("gateways locked");
  1669. }
  1670. defaultGetUrlFunc = getUrl;
  1671. }
  1672. /**
  1673. * Creates a getUrl function that fetches content from HTTP and
  1674. * HTTPS URLs.
  1675. *
  1676. * The available %%options%% are dependent on the platform
  1677. * implementation of the default getUrl function.
  1678. *
  1679. * This is not generally something that is needed, but is useful
  1680. * when trying to customize simple behaviour when fetching HTTP
  1681. * content.
  1682. */
  1683. static createGetUrlFunc(options) {
  1684. return createGetUrl();
  1685. }
  1686. /**
  1687. * Creates a function that can "fetch" data URIs.
  1688. *
  1689. * Note that this is automatically done internally to support
  1690. * data URIs, so it is not necessary to register it.
  1691. *
  1692. * This is not generally something that is needed, but may
  1693. * be useful in a wrapper to perfom custom data URI functionality.
  1694. */
  1695. static createDataGateway() {
  1696. return dataGatewayFunc;
  1697. }
  1698. /**
  1699. * Creates a function that will fetch IPFS (unvalidated) from
  1700. * a custom gateway baseUrl.
  1701. *
  1702. * The default IPFS gateway used internally is
  1703. * ``"https:/\/gateway.ipfs.io/ipfs/"``.
  1704. */
  1705. static createIpfsGatewayFunc(baseUrl) {
  1706. return getIpfsGatewayFunc(baseUrl);
  1707. }
  1708. }
  1709. /**
  1710. * The response for a FetchRequest.
  1711. */
  1712. class FetchResponse {
  1713. #statusCode;
  1714. #statusMessage;
  1715. #headers;
  1716. #body;
  1717. #request;
  1718. #error;
  1719. toString() {
  1720. return `<FetchResponse status=${this.statusCode} body=${this.#body ? hexlify(this.#body) : "null"}>`;
  1721. }
  1722. /**
  1723. * The response status code.
  1724. */
  1725. get statusCode() { return this.#statusCode; }
  1726. /**
  1727. * The response status message.
  1728. */
  1729. get statusMessage() { return this.#statusMessage; }
  1730. /**
  1731. * The response headers. All keys are lower-case.
  1732. */
  1733. get headers() { return Object.assign({}, this.#headers); }
  1734. /**
  1735. * The response body, or ``null`` if there was no body.
  1736. */
  1737. get body() {
  1738. return (this.#body == null) ? null : new Uint8Array(this.#body);
  1739. }
  1740. /**
  1741. * The response body as a UTF-8 encoded string, or the empty
  1742. * string (i.e. ``""``) if there was no body.
  1743. *
  1744. * An error is thrown if the body is invalid UTF-8 data.
  1745. */
  1746. get bodyText() {
  1747. try {
  1748. return (this.#body == null) ? "" : toUtf8String(this.#body);
  1749. }
  1750. catch (error) {
  1751. assert(false, "response body is not valid UTF-8 data", "UNSUPPORTED_OPERATION", {
  1752. operation: "bodyText", info: { response: this }
  1753. });
  1754. }
  1755. }
  1756. /**
  1757. * The response body, decoded as JSON.
  1758. *
  1759. * An error is thrown if the body is invalid JSON-encoded data
  1760. * or if there was no body.
  1761. */
  1762. get bodyJson() {
  1763. try {
  1764. return JSON.parse(this.bodyText);
  1765. }
  1766. catch (error) {
  1767. assert(false, "response body is not valid JSON", "UNSUPPORTED_OPERATION", {
  1768. operation: "bodyJson", info: { response: this }
  1769. });
  1770. }
  1771. }
  1772. [Symbol.iterator]() {
  1773. const headers = this.headers;
  1774. const keys = Object.keys(headers);
  1775. let index = 0;
  1776. return {
  1777. next: () => {
  1778. if (index < keys.length) {
  1779. const key = keys[index++];
  1780. return {
  1781. value: [key, headers[key]], done: false
  1782. };
  1783. }
  1784. return { value: undefined, done: true };
  1785. }
  1786. };
  1787. }
  1788. constructor(statusCode, statusMessage, headers, body, request) {
  1789. this.#statusCode = statusCode;
  1790. this.#statusMessage = statusMessage;
  1791. this.#headers = Object.keys(headers).reduce((accum, k) => {
  1792. accum[k.toLowerCase()] = String(headers[k]);
  1793. return accum;
  1794. }, {});
  1795. this.#body = ((body == null) ? null : new Uint8Array(body));
  1796. this.#request = (request || null);
  1797. this.#error = { message: "" };
  1798. }
  1799. /**
  1800. * Return a Response with matching headers and body, but with
  1801. * an error status code (i.e. 599) and %%message%% with an
  1802. * optional %%error%%.
  1803. */
  1804. makeServerError(message, error) {
  1805. let statusMessage;
  1806. if (!message) {
  1807. message = `${this.statusCode} ${this.statusMessage}`;
  1808. statusMessage = `CLIENT ESCALATED SERVER ERROR (${message})`;
  1809. }
  1810. else {
  1811. statusMessage = `CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${message})`;
  1812. }
  1813. const response = new FetchResponse(599, statusMessage, this.headers, this.body, this.#request || undefined);
  1814. response.#error = { message, error };
  1815. return response;
  1816. }
  1817. /**
  1818. * If called within a [request.processFunc](FetchRequest-processFunc)
  1819. * call, causes the request to retry as if throttled for %%stall%%
  1820. * milliseconds.
  1821. */
  1822. throwThrottleError(message, stall) {
  1823. if (stall == null) {
  1824. stall = -1;
  1825. }
  1826. else {
  1827. assertArgument(Number.isInteger(stall) && stall >= 0, "invalid stall timeout", "stall", stall);
  1828. }
  1829. const error = new Error(message || "throttling requests");
  1830. defineProperties(error, { stall, throttle: true });
  1831. throw error;
  1832. }
  1833. /**
  1834. * Get the header value for %%key%%, ignoring case.
  1835. */
  1836. getHeader(key) {
  1837. return this.headers[key.toLowerCase()];
  1838. }
  1839. /**
  1840. * Returns true if the response has a body.
  1841. */
  1842. hasBody() {
  1843. return (this.#body != null);
  1844. }
  1845. /**
  1846. * The request made for this response.
  1847. */
  1848. get request() { return this.#request; }
  1849. /**
  1850. * Returns true if this response was a success statusCode.
  1851. */
  1852. ok() {
  1853. return (this.#error.message === "" && this.statusCode >= 200 && this.statusCode < 300);
  1854. }
  1855. /**
  1856. * Throws a ``SERVER_ERROR`` if this response is not ok.
  1857. */
  1858. assertOk() {
  1859. if (this.ok()) {
  1860. return;
  1861. }
  1862. let { message, error } = this.#error;
  1863. if (message === "") {
  1864. message = `server response ${this.statusCode} ${this.statusMessage}`;
  1865. }
  1866. let requestUrl = null;
  1867. if (this.request) {
  1868. requestUrl = this.request.url;
  1869. }
  1870. let responseBody = null;
  1871. try {
  1872. if (this.#body) {
  1873. responseBody = toUtf8String(this.#body);
  1874. }
  1875. }
  1876. catch (e) { }
  1877. assert(false, message, "SERVER_ERROR", {
  1878. request: (this.request || "unknown request"), response: this, error,
  1879. info: {
  1880. requestUrl, responseBody,
  1881. responseStatus: `${this.statusCode} ${this.statusMessage}`
  1882. }
  1883. });
  1884. }
  1885. }
  1886. function getTime$2() { return (new Date()).getTime(); }
  1887. function unpercent(value) {
  1888. return toUtf8Bytes(value.replace(/%([0-9a-f][0-9a-f])/gi, (all, code) => {
  1889. return String.fromCharCode(parseInt(code, 16));
  1890. }));
  1891. }
  1892. function wait(delay) {
  1893. return new Promise((resolve) => setTimeout(resolve, delay));
  1894. }
  1895. /**
  1896. * The **FixedNumber** class permits using values with decimal places,
  1897. * using fixed-pont math.
  1898. *
  1899. * Fixed-point math is still based on integers under-the-hood, but uses an
  1900. * internal offset to store fractional components below, and each operation
  1901. * corrects for this after each operation.
  1902. *
  1903. * @_section: api/utils/fixed-point-math:Fixed-Point Maths [about-fixed-point-math]
  1904. */
  1905. const BN_N1 = BigInt(-1);
  1906. const BN_0$8 = BigInt(0);
  1907. const BN_1$4 = BigInt(1);
  1908. const BN_5 = BigInt(5);
  1909. const _guard$5 = {};
  1910. // Constant to pull zeros from for multipliers
  1911. let Zeros$1 = "0000";
  1912. while (Zeros$1.length < 80) {
  1913. Zeros$1 += Zeros$1;
  1914. }
  1915. // Returns a string "1" followed by decimal "0"s
  1916. function getTens(decimals) {
  1917. let result = Zeros$1;
  1918. while (result.length < decimals) {
  1919. result += result;
  1920. }
  1921. return BigInt("1" + result.substring(0, decimals));
  1922. }
  1923. function checkValue(val, format, safeOp) {
  1924. const width = BigInt(format.width);
  1925. if (format.signed) {
  1926. const limit = (BN_1$4 << (width - BN_1$4));
  1927. assert(safeOp == null || (val >= -limit && val < limit), "overflow", "NUMERIC_FAULT", {
  1928. operation: safeOp, fault: "overflow", value: val
  1929. });
  1930. if (val > BN_0$8) {
  1931. val = fromTwos(mask(val, width), width);
  1932. }
  1933. else {
  1934. val = -fromTwos(mask(-val, width), width);
  1935. }
  1936. }
  1937. else {
  1938. const limit = (BN_1$4 << width);
  1939. assert(safeOp == null || (val >= 0 && val < limit), "overflow", "NUMERIC_FAULT", {
  1940. operation: safeOp, fault: "overflow", value: val
  1941. });
  1942. val = (((val % limit) + limit) % limit) & (limit - BN_1$4);
  1943. }
  1944. return val;
  1945. }
  1946. function getFormat(value) {
  1947. if (typeof (value) === "number") {
  1948. value = `fixed128x${value}`;
  1949. }
  1950. let signed = true;
  1951. let width = 128;
  1952. let decimals = 18;
  1953. if (typeof (value) === "string") {
  1954. // Parse the format string
  1955. if (value === "fixed") ;
  1956. else if (value === "ufixed") {
  1957. signed = false;
  1958. }
  1959. else {
  1960. const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);
  1961. assertArgument(match, "invalid fixed format", "format", value);
  1962. signed = (match[1] !== "u");
  1963. width = parseInt(match[2]);
  1964. decimals = parseInt(match[3]);
  1965. }
  1966. }
  1967. else if (value) {
  1968. // Extract the values from the object
  1969. const v = value;
  1970. const check = (key, type, defaultValue) => {
  1971. if (v[key] == null) {
  1972. return defaultValue;
  1973. }
  1974. assertArgument(typeof (v[key]) === type, "invalid fixed format (" + key + " not " + type + ")", "format." + key, v[key]);
  1975. return v[key];
  1976. };
  1977. signed = check("signed", "boolean", signed);
  1978. width = check("width", "number", width);
  1979. decimals = check("decimals", "number", decimals);
  1980. }
  1981. assertArgument((width % 8) === 0, "invalid FixedNumber width (not byte aligned)", "format.width", width);
  1982. assertArgument(decimals <= 80, "invalid FixedNumber decimals (too large)", "format.decimals", decimals);
  1983. const name = (signed ? "" : "u") + "fixed" + String(width) + "x" + String(decimals);
  1984. return { signed, width, decimals, name };
  1985. }
  1986. function toString(val, decimals) {
  1987. let negative = "";
  1988. if (val < BN_0$8) {
  1989. negative = "-";
  1990. val *= BN_N1;
  1991. }
  1992. let str = val.toString();
  1993. // No decimal point for whole values
  1994. if (decimals === 0) {
  1995. return (negative + str);
  1996. }
  1997. // Pad out to the whole component (including a whole digit)
  1998. while (str.length <= decimals) {
  1999. str = Zeros$1 + str;
  2000. }
  2001. // Insert the decimal point
  2002. const index = str.length - decimals;
  2003. str = str.substring(0, index) + "." + str.substring(index);
  2004. // Trim the whole component (leaving at least one 0)
  2005. while (str[0] === "0" && str[1] !== ".") {
  2006. str = str.substring(1);
  2007. }
  2008. // Trim the decimal component (leaving at least one 0)
  2009. while (str[str.length - 1] === "0" && str[str.length - 2] !== ".") {
  2010. str = str.substring(0, str.length - 1);
  2011. }
  2012. return (negative + str);
  2013. }
  2014. /**
  2015. * A FixedNumber represents a value over its [[FixedFormat]]
  2016. * arithmetic field.
  2017. *
  2018. * A FixedNumber can be used to perform math, losslessly, on
  2019. * values which have decmial places.
  2020. *
  2021. * A FixedNumber has a fixed bit-width to store values in, and stores all
  2022. * values internally by multiplying the value by 10 raised to the power of
  2023. * %%decimals%%.
  2024. *
  2025. * If operations are performed that cause a value to grow too high (close to
  2026. * positive infinity) or too low (close to negative infinity), the value
  2027. * is said to //overflow//.
  2028. *
  2029. * For example, an 8-bit signed value, with 0 decimals may only be within
  2030. * the range ``-128`` to ``127``; so ``-128 - 1`` will overflow and become
  2031. * ``127``. Likewise, ``127 + 1`` will overflow and become ``-127``.
  2032. *
  2033. * Many operation have a normal and //unsafe// variant. The normal variant
  2034. * will throw a [[NumericFaultError]] on any overflow, while the //unsafe//
  2035. * variant will silently allow overflow, corrupting its value value.
  2036. *
  2037. * If operations are performed that cause a value to become too small
  2038. * (close to zero), the value loses precison and is said to //underflow//.
  2039. *
  2040. * For example, an value with 1 decimal place may store a number as small
  2041. * as ``0.1``, but the value of ``0.1 / 2`` is ``0.05``, which cannot fit
  2042. * into 1 decimal place, so underflow occurs which means precision is lost
  2043. * and the value becomes ``0``.
  2044. *
  2045. * Some operations have a normal and //signalling// variant. The normal
  2046. * variant will silently ignore underflow, while the //signalling// variant
  2047. * will thow a [[NumericFaultError]] on underflow.
  2048. */
  2049. class FixedNumber {
  2050. /**
  2051. * The specific fixed-point arithmetic field for this value.
  2052. */
  2053. format;
  2054. #format;
  2055. // The actual value (accounting for decimals)
  2056. #val;
  2057. // A base-10 value to multiple values by to maintain the magnitude
  2058. #tens;
  2059. /**
  2060. * This is a property so console.log shows a human-meaningful value.
  2061. *
  2062. * @private
  2063. */
  2064. _value;
  2065. // Use this when changing this file to get some typing info,
  2066. // but then switch to any to mask the internal type
  2067. //constructor(guard: any, value: bigint, format: _FixedFormat) {
  2068. /**
  2069. * @private
  2070. */
  2071. constructor(guard, value, format) {
  2072. assertPrivate(guard, _guard$5, "FixedNumber");
  2073. this.#val = value;
  2074. this.#format = format;
  2075. const _value = toString(value, format.decimals);
  2076. defineProperties(this, { format: format.name, _value });
  2077. this.#tens = getTens(format.decimals);
  2078. }
  2079. /**
  2080. * If true, negative values are permitted, otherwise only
  2081. * positive values and zero are allowed.
  2082. */
  2083. get signed() { return this.#format.signed; }
  2084. /**
  2085. * The number of bits available to store the value.
  2086. */
  2087. get width() { return this.#format.width; }
  2088. /**
  2089. * The number of decimal places in the fixed-point arithment field.
  2090. */
  2091. get decimals() { return this.#format.decimals; }
  2092. /**
  2093. * The value as an integer, based on the smallest unit the
  2094. * [[decimals]] allow.
  2095. */
  2096. get value() { return this.#val; }
  2097. #checkFormat(other) {
  2098. assertArgument(this.format === other.format, "incompatible format; use fixedNumber.toFormat", "other", other);
  2099. }
  2100. #checkValue(val, safeOp) {
  2101. /*
  2102. const width = BigInt(this.width);
  2103. if (this.signed) {
  2104. const limit = (BN_1 << (width - BN_1));
  2105. assert(safeOp == null || (val >= -limit && val < limit), "overflow", "NUMERIC_FAULT", {
  2106. operation: <string>safeOp, fault: "overflow", value: val
  2107. });
  2108. if (val > BN_0) {
  2109. val = fromTwos(mask(val, width), width);
  2110. } else {
  2111. val = -fromTwos(mask(-val, width), width);
  2112. }
  2113. } else {
  2114. const masked = mask(val, width);
  2115. assert(safeOp == null || (val >= 0 && val === masked), "overflow", "NUMERIC_FAULT", {
  2116. operation: <string>safeOp, fault: "overflow", value: val
  2117. });
  2118. val = masked;
  2119. }
  2120. */
  2121. val = checkValue(val, this.#format, safeOp);
  2122. return new FixedNumber(_guard$5, val, this.#format);
  2123. }
  2124. #add(o, safeOp) {
  2125. this.#checkFormat(o);
  2126. return this.#checkValue(this.#val + o.#val, safeOp);
  2127. }
  2128. /**
  2129. * Returns a new [[FixedNumber]] with the result of %%this%% added
  2130. * to %%other%%, ignoring overflow.
  2131. */
  2132. addUnsafe(other) { return this.#add(other); }
  2133. /**
  2134. * Returns a new [[FixedNumber]] with the result of %%this%% added
  2135. * to %%other%%. A [[NumericFaultError]] is thrown if overflow
  2136. * occurs.
  2137. */
  2138. add(other) { return this.#add(other, "add"); }
  2139. #sub(o, safeOp) {
  2140. this.#checkFormat(o);
  2141. return this.#checkValue(this.#val - o.#val, safeOp);
  2142. }
  2143. /**
  2144. * Returns a new [[FixedNumber]] with the result of %%other%% subtracted
  2145. * from %%this%%, ignoring overflow.
  2146. */
  2147. subUnsafe(other) { return this.#sub(other); }
  2148. /**
  2149. * Returns a new [[FixedNumber]] with the result of %%other%% subtracted
  2150. * from %%this%%. A [[NumericFaultError]] is thrown if overflow
  2151. * occurs.
  2152. */
  2153. sub(other) { return this.#sub(other, "sub"); }
  2154. #mul(o, safeOp) {
  2155. this.#checkFormat(o);
  2156. return this.#checkValue((this.#val * o.#val) / this.#tens, safeOp);
  2157. }
  2158. /**
  2159. * Returns a new [[FixedNumber]] with the result of %%this%% multiplied
  2160. * by %%other%%, ignoring overflow and underflow (precision loss).
  2161. */
  2162. mulUnsafe(other) { return this.#mul(other); }
  2163. /**
  2164. * Returns a new [[FixedNumber]] with the result of %%this%% multiplied
  2165. * by %%other%%. A [[NumericFaultError]] is thrown if overflow
  2166. * occurs.
  2167. */
  2168. mul(other) { return this.#mul(other, "mul"); }
  2169. /**
  2170. * Returns a new [[FixedNumber]] with the result of %%this%% multiplied
  2171. * by %%other%%. A [[NumericFaultError]] is thrown if overflow
  2172. * occurs or if underflow (precision loss) occurs.
  2173. */
  2174. mulSignal(other) {
  2175. this.#checkFormat(other);
  2176. const value = this.#val * other.#val;
  2177. assert((value % this.#tens) === BN_0$8, "precision lost during signalling mul", "NUMERIC_FAULT", {
  2178. operation: "mulSignal", fault: "underflow", value: this
  2179. });
  2180. return this.#checkValue(value / this.#tens, "mulSignal");
  2181. }
  2182. #div(o, safeOp) {
  2183. assert(o.#val !== BN_0$8, "division by zero", "NUMERIC_FAULT", {
  2184. operation: "div", fault: "divide-by-zero", value: this
  2185. });
  2186. this.#checkFormat(o);
  2187. return this.#checkValue((this.#val * this.#tens) / o.#val, safeOp);
  2188. }
  2189. /**
  2190. * Returns a new [[FixedNumber]] with the result of %%this%% divided
  2191. * by %%other%%, ignoring underflow (precision loss). A
  2192. * [[NumericFaultError]] is thrown if overflow occurs.
  2193. */
  2194. divUnsafe(other) { return this.#div(other); }
  2195. /**
  2196. * Returns a new [[FixedNumber]] with the result of %%this%% divided
  2197. * by %%other%%, ignoring underflow (precision loss). A
  2198. * [[NumericFaultError]] is thrown if overflow occurs.
  2199. */
  2200. div(other) { return this.#div(other, "div"); }
  2201. /**
  2202. * Returns a new [[FixedNumber]] with the result of %%this%% divided
  2203. * by %%other%%. A [[NumericFaultError]] is thrown if underflow
  2204. * (precision loss) occurs.
  2205. */
  2206. divSignal(other) {
  2207. assert(other.#val !== BN_0$8, "division by zero", "NUMERIC_FAULT", {
  2208. operation: "div", fault: "divide-by-zero", value: this
  2209. });
  2210. this.#checkFormat(other);
  2211. const value = (this.#val * this.#tens);
  2212. assert((value % other.#val) === BN_0$8, "precision lost during signalling div", "NUMERIC_FAULT", {
  2213. operation: "divSignal", fault: "underflow", value: this
  2214. });
  2215. return this.#checkValue(value / other.#val, "divSignal");
  2216. }
  2217. /**
  2218. * Returns a comparison result between %%this%% and %%other%%.
  2219. *
  2220. * This is suitable for use in sorting, where ``-1`` implies %%this%%
  2221. * is smaller, ``1`` implies %%this%% is larger and ``0`` implies
  2222. * both are equal.
  2223. */
  2224. cmp(other) {
  2225. let a = this.value, b = other.value;
  2226. // Coerce a and b to the same magnitude
  2227. const delta = this.decimals - other.decimals;
  2228. if (delta > 0) {
  2229. b *= getTens(delta);
  2230. }
  2231. else if (delta < 0) {
  2232. a *= getTens(-delta);
  2233. }
  2234. // Comnpare
  2235. if (a < b) {
  2236. return -1;
  2237. }
  2238. if (a > b) {
  2239. return 1;
  2240. }
  2241. return 0;
  2242. }
  2243. /**
  2244. * Returns true if %%other%% is equal to %%this%%.
  2245. */
  2246. eq(other) { return this.cmp(other) === 0; }
  2247. /**
  2248. * Returns true if %%other%% is less than to %%this%%.
  2249. */
  2250. lt(other) { return this.cmp(other) < 0; }
  2251. /**
  2252. * Returns true if %%other%% is less than or equal to %%this%%.
  2253. */
  2254. lte(other) { return this.cmp(other) <= 0; }
  2255. /**
  2256. * Returns true if %%other%% is greater than to %%this%%.
  2257. */
  2258. gt(other) { return this.cmp(other) > 0; }
  2259. /**
  2260. * Returns true if %%other%% is greater than or equal to %%this%%.
  2261. */
  2262. gte(other) { return this.cmp(other) >= 0; }
  2263. /**
  2264. * Returns a new [[FixedNumber]] which is the largest **integer**
  2265. * that is less than or equal to %%this%%.
  2266. *
  2267. * The decimal component of the result will always be ``0``.
  2268. */
  2269. floor() {
  2270. let val = this.#val;
  2271. if (this.#val < BN_0$8) {
  2272. val -= this.#tens - BN_1$4;
  2273. }
  2274. val = (this.#val / this.#tens) * this.#tens;
  2275. return this.#checkValue(val, "floor");
  2276. }
  2277. /**
  2278. * Returns a new [[FixedNumber]] which is the smallest **integer**
  2279. * that is greater than or equal to %%this%%.
  2280. *
  2281. * The decimal component of the result will always be ``0``.
  2282. */
  2283. ceiling() {
  2284. let val = this.#val;
  2285. if (this.#val > BN_0$8) {
  2286. val += this.#tens - BN_1$4;
  2287. }
  2288. val = (this.#val / this.#tens) * this.#tens;
  2289. return this.#checkValue(val, "ceiling");
  2290. }
  2291. /**
  2292. * Returns a new [[FixedNumber]] with the decimal component
  2293. * rounded up on ties at %%decimals%% places.
  2294. */
  2295. round(decimals) {
  2296. if (decimals == null) {
  2297. decimals = 0;
  2298. }
  2299. // Not enough precision to not already be rounded
  2300. if (decimals >= this.decimals) {
  2301. return this;
  2302. }
  2303. const delta = this.decimals - decimals;
  2304. const bump = BN_5 * getTens(delta - 1);
  2305. let value = this.value + bump;
  2306. const tens = getTens(delta);
  2307. value = (value / tens) * tens;
  2308. checkValue(value, this.#format, "round");
  2309. return new FixedNumber(_guard$5, value, this.#format);
  2310. }
  2311. /**
  2312. * Returns true if %%this%% is equal to ``0``.
  2313. */
  2314. isZero() { return (this.#val === BN_0$8); }
  2315. /**
  2316. * Returns true if %%this%% is less than ``0``.
  2317. */
  2318. isNegative() { return (this.#val < BN_0$8); }
  2319. /**
  2320. * Returns the string representation of %%this%%.
  2321. */
  2322. toString() { return this._value; }
  2323. /**
  2324. * Returns a float approximation.
  2325. *
  2326. * Due to IEEE 754 precission (or lack thereof), this function
  2327. * can only return an approximation and most values will contain
  2328. * rounding errors.
  2329. */
  2330. toUnsafeFloat() { return parseFloat(this.toString()); }
  2331. /**
  2332. * Return a new [[FixedNumber]] with the same value but has had
  2333. * its field set to %%format%%.
  2334. *
  2335. * This will throw if the value cannot fit into %%format%%.
  2336. */
  2337. toFormat(format) {
  2338. return FixedNumber.fromString(this.toString(), format);
  2339. }
  2340. /**
  2341. * Creates a new [[FixedNumber]] for %%value%% divided by
  2342. * %%decimal%% places with %%format%%.
  2343. *
  2344. * This will throw a [[NumericFaultError]] if %%value%% (once adjusted
  2345. * for %%decimals%%) cannot fit in %%format%%, either due to overflow
  2346. * or underflow (precision loss).
  2347. */
  2348. static fromValue(_value, _decimals, _format) {
  2349. const decimals = (_decimals == null) ? 0 : getNumber(_decimals);
  2350. const format = getFormat(_format);
  2351. let value = getBigInt(_value, "value");
  2352. const delta = decimals - format.decimals;
  2353. if (delta > 0) {
  2354. const tens = getTens(delta);
  2355. assert((value % tens) === BN_0$8, "value loses precision for format", "NUMERIC_FAULT", {
  2356. operation: "fromValue", fault: "underflow", value: _value
  2357. });
  2358. value /= tens;
  2359. }
  2360. else if (delta < 0) {
  2361. value *= getTens(-delta);
  2362. }
  2363. checkValue(value, format, "fromValue");
  2364. return new FixedNumber(_guard$5, value, format);
  2365. }
  2366. /**
  2367. * Creates a new [[FixedNumber]] for %%value%% with %%format%%.
  2368. *
  2369. * This will throw a [[NumericFaultError]] if %%value%% cannot fit
  2370. * in %%format%%, either due to overflow or underflow (precision loss).
  2371. */
  2372. static fromString(_value, _format) {
  2373. const match = _value.match(/^(-?)([0-9]*)\.?([0-9]*)$/);
  2374. assertArgument(match && (match[2].length + match[3].length) > 0, "invalid FixedNumber string value", "value", _value);
  2375. const format = getFormat(_format);
  2376. let whole = (match[2] || "0"), decimal = (match[3] || "");
  2377. // Pad out the decimals
  2378. while (decimal.length < format.decimals) {
  2379. decimal += Zeros$1;
  2380. }
  2381. // Check precision is safe
  2382. assert(decimal.substring(format.decimals).match(/^0*$/), "too many decimals for format", "NUMERIC_FAULT", {
  2383. operation: "fromString", fault: "underflow", value: _value
  2384. });
  2385. // Remove extra padding
  2386. decimal = decimal.substring(0, format.decimals);
  2387. const value = BigInt(match[1] + whole + decimal);
  2388. checkValue(value, format, "fromString");
  2389. return new FixedNumber(_guard$5, value, format);
  2390. }
  2391. /**
  2392. * Creates a new [[FixedNumber]] with the big-endian representation
  2393. * %%value%% with %%format%%.
  2394. *
  2395. * This will throw a [[NumericFaultError]] if %%value%% cannot fit
  2396. * in %%format%% due to overflow.
  2397. */
  2398. static fromBytes(_value, _format) {
  2399. let value = toBigInt(getBytes(_value, "value"));
  2400. const format = getFormat(_format);
  2401. if (format.signed) {
  2402. value = fromTwos(value, format.width);
  2403. }
  2404. checkValue(value, format, "fromBytes");
  2405. return new FixedNumber(_guard$5, value, format);
  2406. }
  2407. }
  2408. //const f1 = FixedNumber.fromString("12.56", "fixed16x2");
  2409. //const f2 = FixedNumber.fromString("0.3", "fixed16x2");
  2410. //console.log(f1.divSignal(f2));
  2411. //const BUMP = FixedNumber.from("0.5");
  2412. //See: https://github.com/ethereum/wiki/wiki/RLP
  2413. function hexlifyByte(value) {
  2414. let result = value.toString(16);
  2415. while (result.length < 2) {
  2416. result = "0" + result;
  2417. }
  2418. return "0x" + result;
  2419. }
  2420. function unarrayifyInteger(data, offset, length) {
  2421. let result = 0;
  2422. for (let i = 0; i < length; i++) {
  2423. result = (result * 256) + data[offset + i];
  2424. }
  2425. return result;
  2426. }
  2427. function _decodeChildren(data, offset, childOffset, length) {
  2428. const result = [];
  2429. while (childOffset < offset + 1 + length) {
  2430. const decoded = _decode(data, childOffset);
  2431. result.push(decoded.result);
  2432. childOffset += decoded.consumed;
  2433. assert(childOffset <= offset + 1 + length, "child data too short", "BUFFER_OVERRUN", {
  2434. buffer: data, length, offset
  2435. });
  2436. }
  2437. return { consumed: (1 + length), result: result };
  2438. }
  2439. // returns { consumed: number, result: Object }
  2440. function _decode(data, offset) {
  2441. assert(data.length !== 0, "data too short", "BUFFER_OVERRUN", {
  2442. buffer: data, length: 0, offset: 1
  2443. });
  2444. const checkOffset = (offset) => {
  2445. assert(offset <= data.length, "data short segment too short", "BUFFER_OVERRUN", {
  2446. buffer: data, length: data.length, offset
  2447. });
  2448. };
  2449. // Array with extra length prefix
  2450. if (data[offset] >= 0xf8) {
  2451. const lengthLength = data[offset] - 0xf7;
  2452. checkOffset(offset + 1 + lengthLength);
  2453. const length = unarrayifyInteger(data, offset + 1, lengthLength);
  2454. checkOffset(offset + 1 + lengthLength + length);
  2455. return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length);
  2456. }
  2457. else if (data[offset] >= 0xc0) {
  2458. const length = data[offset] - 0xc0;
  2459. checkOffset(offset + 1 + length);
  2460. return _decodeChildren(data, offset, offset + 1, length);
  2461. }
  2462. else if (data[offset] >= 0xb8) {
  2463. const lengthLength = data[offset] - 0xb7;
  2464. checkOffset(offset + 1 + lengthLength);
  2465. const length = unarrayifyInteger(data, offset + 1, lengthLength);
  2466. checkOffset(offset + 1 + lengthLength + length);
  2467. const result = hexlify(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length));
  2468. return { consumed: (1 + lengthLength + length), result: result };
  2469. }
  2470. else if (data[offset] >= 0x80) {
  2471. const length = data[offset] - 0x80;
  2472. checkOffset(offset + 1 + length);
  2473. const result = hexlify(data.slice(offset + 1, offset + 1 + length));
  2474. return { consumed: (1 + length), result: result };
  2475. }
  2476. return { consumed: 1, result: hexlifyByte(data[offset]) };
  2477. }
  2478. /**
  2479. * Decodes %%data%% into the structured data it represents.
  2480. */
  2481. function decodeRlp(_data) {
  2482. const data = getBytes(_data, "data");
  2483. const decoded = _decode(data, 0);
  2484. assertArgument(decoded.consumed === data.length, "unexpected junk after rlp payload", "data", _data);
  2485. return decoded.result;
  2486. }
  2487. //See: https://github.com/ethereum/wiki/wiki/RLP
  2488. function arrayifyInteger(value) {
  2489. const result = [];
  2490. while (value) {
  2491. result.unshift(value & 0xff);
  2492. value >>= 8;
  2493. }
  2494. return result;
  2495. }
  2496. function _encode(object) {
  2497. if (Array.isArray(object)) {
  2498. let payload = [];
  2499. object.forEach(function (child) {
  2500. payload = payload.concat(_encode(child));
  2501. });
  2502. if (payload.length <= 55) {
  2503. payload.unshift(0xc0 + payload.length);
  2504. return payload;
  2505. }
  2506. const length = arrayifyInteger(payload.length);
  2507. length.unshift(0xf7 + length.length);
  2508. return length.concat(payload);
  2509. }
  2510. const data = Array.prototype.slice.call(getBytes(object, "object"));
  2511. if (data.length === 1 && data[0] <= 0x7f) {
  2512. return data;
  2513. }
  2514. else if (data.length <= 55) {
  2515. data.unshift(0x80 + data.length);
  2516. return data;
  2517. }
  2518. const length = arrayifyInteger(data.length);
  2519. length.unshift(0xb7 + length.length);
  2520. return length.concat(data);
  2521. }
  2522. const nibbles = "0123456789abcdef";
  2523. /**
  2524. * Encodes %%object%% as an RLP-encoded [[DataHexString]].
  2525. */
  2526. function encodeRlp(object) {
  2527. let result = "0x";
  2528. for (const v of _encode(object)) {
  2529. result += nibbles[v >> 4];
  2530. result += nibbles[v & 0xf];
  2531. }
  2532. return result;
  2533. }
  2534. /**
  2535. * Most interactions with Ethereum requires integer values, which use
  2536. * the smallest magnitude unit.
  2537. *
  2538. * For example, imagine dealing with dollars and cents. Since dollars
  2539. * are divisible, non-integer values are possible, such as ``$10.77``.
  2540. * By using the smallest indivisible unit (i.e. cents), the value can
  2541. * be kept as the integer ``1077``.
  2542. *
  2543. * When receiving decimal input from the user (as a decimal string),
  2544. * the value should be converted to an integer and when showing a user
  2545. * a value, the integer value should be converted to a decimal string.
  2546. *
  2547. * This creates a clear distinction, between values to be used by code
  2548. * (integers) and values used for display logic to users (decimals).
  2549. *
  2550. * The native unit in Ethereum, //ether// is divisible to 18 decimal places,
  2551. * where each individual unit is called a //wei//.
  2552. *
  2553. * @_subsection api/utils:Unit Conversion [about-units]
  2554. */
  2555. const names = [
  2556. "wei",
  2557. "kwei",
  2558. "mwei",
  2559. "gwei",
  2560. "szabo",
  2561. "finney",
  2562. "ether",
  2563. ];
  2564. /**
  2565. * Converts %%value%% into a //decimal string//, assuming %%unit%% decimal
  2566. * places. The %%unit%% may be the number of decimal places or the name of
  2567. * a unit (e.g. ``"gwei"`` for 9 decimal places).
  2568. *
  2569. */
  2570. function formatUnits(value, unit) {
  2571. let decimals = 18;
  2572. if (typeof (unit) === "string") {
  2573. const index = names.indexOf(unit);
  2574. assertArgument(index >= 0, "invalid unit", "unit", unit);
  2575. decimals = 3 * index;
  2576. }
  2577. else if (unit != null) {
  2578. decimals = getNumber(unit, "unit");
  2579. }
  2580. return FixedNumber.fromValue(value, decimals, { decimals, width: 512 }).toString();
  2581. }
  2582. /**
  2583. * Converts the //decimal string// %%value%% to a BigInt, assuming
  2584. * %%unit%% decimal places. The %%unit%% may the number of decimal places
  2585. * or the name of a unit (e.g. ``"gwei"`` for 9 decimal places).
  2586. */
  2587. function parseUnits$1(value, unit) {
  2588. assertArgument(typeof (value) === "string", "value must be a string", "value", value);
  2589. let decimals = 18;
  2590. if (typeof (unit) === "string") {
  2591. const index = names.indexOf(unit);
  2592. assertArgument(index >= 0, "invalid unit", "unit", unit);
  2593. decimals = 3 * index;
  2594. }
  2595. else if (unit != null) {
  2596. decimals = getNumber(unit, "unit");
  2597. }
  2598. return FixedNumber.fromString(value, { decimals, width: 512 }).value;
  2599. }
  2600. /**
  2601. * Converts %%value%% into a //decimal string// using 18 decimal places.
  2602. */
  2603. function formatEther(wei) {
  2604. return formatUnits(wei, 18);
  2605. }
  2606. /**
  2607. * Converts the //decimal string// %%ether%% to a BigInt, using 18
  2608. * decimal places.
  2609. */
  2610. function parseEther(ether) {
  2611. return parseUnits$1(ether, 18);
  2612. }
  2613. /**
  2614. * Explain UUID and link to RFC here.
  2615. *
  2616. * @_subsection: api/utils:UUID [about-uuid]
  2617. */
  2618. /**
  2619. * Returns the version 4 [[link-uuid]] for the %%randomBytes%%.
  2620. *
  2621. * @see: https://www.ietf.org/rfc/rfc4122.txt (Section 4.4)
  2622. */
  2623. function uuidV4(randomBytes) {
  2624. const bytes = getBytes(randomBytes, "randomBytes");
  2625. // Section: 4.1.3:
  2626. // - time_hi_and_version[12:16] = 0b0100
  2627. bytes[6] = (bytes[6] & 0x0f) | 0x40;
  2628. // Section 4.4
  2629. // - clock_seq_hi_and_reserved[6] = 0b0
  2630. // - clock_seq_hi_and_reserved[7] = 0b1
  2631. bytes[8] = (bytes[8] & 0x3f) | 0x80;
  2632. const value = hexlify(bytes);
  2633. return [
  2634. value.substring(2, 10),
  2635. value.substring(10, 14),
  2636. value.substring(14, 18),
  2637. value.substring(18, 22),
  2638. value.substring(22, 34),
  2639. ].join("-");
  2640. }
  2641. /**
  2642. * @_ignore:
  2643. */
  2644. const WordSize = 32;
  2645. const Padding = new Uint8Array(WordSize);
  2646. // Properties used to immediate pass through to the underlying object
  2647. // - `then` is used to detect if an object is a Promise for await
  2648. const passProperties$1 = ["then"];
  2649. const _guard$4 = {};
  2650. const resultNames = new WeakMap();
  2651. function getNames(result) {
  2652. return resultNames.get(result);
  2653. }
  2654. function setNames(result, names) {
  2655. resultNames.set(result, names);
  2656. }
  2657. function throwError(name, error) {
  2658. const wrapped = new Error(`deferred error during ABI decoding triggered accessing ${name}`);
  2659. wrapped.error = error;
  2660. throw wrapped;
  2661. }
  2662. function toObject(names, items, deep) {
  2663. if (names.indexOf(null) >= 0) {
  2664. return items.map((item, index) => {
  2665. if (item instanceof Result) {
  2666. return toObject(getNames(item), item, deep);
  2667. }
  2668. return item;
  2669. });
  2670. }
  2671. return names.reduce((accum, name, index) => {
  2672. let item = items.getValue(name);
  2673. if (!(name in accum)) {
  2674. if (deep && item instanceof Result) {
  2675. item = toObject(getNames(item), item, deep);
  2676. }
  2677. accum[name] = item;
  2678. }
  2679. return accum;
  2680. }, {});
  2681. }
  2682. /**
  2683. * A [[Result]] is a sub-class of Array, which allows accessing any
  2684. * of its values either positionally by its index or, if keys are
  2685. * provided by its name.
  2686. *
  2687. * @_docloc: api/abi
  2688. */
  2689. class Result extends Array {
  2690. // No longer used; but cannot be removed as it will remove the
  2691. // #private field from the .d.ts which may break backwards
  2692. // compatibility
  2693. #names;
  2694. /**
  2695. * @private
  2696. */
  2697. constructor(...args) {
  2698. // To properly sub-class Array so the other built-in
  2699. // functions work, the constructor has to behave fairly
  2700. // well. So, in the event we are created via fromItems()
  2701. // we build the read-only Result object we want, but on
  2702. // any other input, we use the default constructor
  2703. // constructor(guard: any, items: Array<any>, keys?: Array<null | string>);
  2704. const guard = args[0];
  2705. let items = args[1];
  2706. let names = (args[2] || []).slice();
  2707. let wrap = true;
  2708. if (guard !== _guard$4) {
  2709. items = args;
  2710. names = [];
  2711. wrap = false;
  2712. }
  2713. // Can't just pass in ...items since an array of length 1
  2714. // is a special case in the super.
  2715. super(items.length);
  2716. items.forEach((item, index) => { this[index] = item; });
  2717. // Find all unique keys
  2718. const nameCounts = names.reduce((accum, name) => {
  2719. if (typeof (name) === "string") {
  2720. accum.set(name, (accum.get(name) || 0) + 1);
  2721. }
  2722. return accum;
  2723. }, (new Map()));
  2724. // Remove any key thats not unique
  2725. setNames(this, Object.freeze(items.map((item, index) => {
  2726. const name = names[index];
  2727. if (name != null && nameCounts.get(name) === 1) {
  2728. return name;
  2729. }
  2730. return null;
  2731. })));
  2732. // Dummy operations to prevent TypeScript from complaining
  2733. this.#names = [];
  2734. if (this.#names == null) {
  2735. void (this.#names);
  2736. }
  2737. if (!wrap) {
  2738. return;
  2739. }
  2740. // A wrapped Result is immutable
  2741. Object.freeze(this);
  2742. // Proxy indices and names so we can trap deferred errors
  2743. const proxy = new Proxy(this, {
  2744. get: (target, prop, receiver) => {
  2745. if (typeof (prop) === "string") {
  2746. // Index accessor
  2747. if (prop.match(/^[0-9]+$/)) {
  2748. const index = getNumber(prop, "%index");
  2749. if (index < 0 || index >= this.length) {
  2750. throw new RangeError("out of result range");
  2751. }
  2752. const item = target[index];
  2753. if (item instanceof Error) {
  2754. throwError(`index ${index}`, item);
  2755. }
  2756. return item;
  2757. }
  2758. // Pass important checks (like `then` for Promise) through
  2759. if (passProperties$1.indexOf(prop) >= 0) {
  2760. return Reflect.get(target, prop, receiver);
  2761. }
  2762. const value = target[prop];
  2763. if (value instanceof Function) {
  2764. // Make sure functions work with private variables
  2765. // See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#no_private_property_forwarding
  2766. return function (...args) {
  2767. return value.apply((this === receiver) ? target : this, args);
  2768. };
  2769. }
  2770. else if (!(prop in target)) {
  2771. // Possible name accessor
  2772. return target.getValue.apply((this === receiver) ? target : this, [prop]);
  2773. }
  2774. }
  2775. return Reflect.get(target, prop, receiver);
  2776. }
  2777. });
  2778. setNames(proxy, getNames(this));
  2779. return proxy;
  2780. }
  2781. /**
  2782. * Returns the Result as a normal Array. If %%deep%%, any children
  2783. * which are Result objects are also converted to a normal Array.
  2784. *
  2785. * This will throw if there are any outstanding deferred
  2786. * errors.
  2787. */
  2788. toArray(deep) {
  2789. const result = [];
  2790. this.forEach((item, index) => {
  2791. if (item instanceof Error) {
  2792. throwError(`index ${index}`, item);
  2793. }
  2794. if (deep && item instanceof Result) {
  2795. item = item.toArray(deep);
  2796. }
  2797. result.push(item);
  2798. });
  2799. return result;
  2800. }
  2801. /**
  2802. * Returns the Result as an Object with each name-value pair. If
  2803. * %%deep%%, any children which are Result objects are also
  2804. * converted to an Object.
  2805. *
  2806. * This will throw if any value is unnamed, or if there are
  2807. * any outstanding deferred errors.
  2808. */
  2809. toObject(deep) {
  2810. const names = getNames(this);
  2811. return names.reduce((accum, name, index) => {
  2812. assert(name != null, `value at index ${index} unnamed`, "UNSUPPORTED_OPERATION", {
  2813. operation: "toObject()"
  2814. });
  2815. return toObject(names, this, deep);
  2816. }, {});
  2817. }
  2818. /**
  2819. * @_ignore
  2820. */
  2821. slice(start, end) {
  2822. if (start == null) {
  2823. start = 0;
  2824. }
  2825. if (start < 0) {
  2826. start += this.length;
  2827. if (start < 0) {
  2828. start = 0;
  2829. }
  2830. }
  2831. if (end == null) {
  2832. end = this.length;
  2833. }
  2834. if (end < 0) {
  2835. end += this.length;
  2836. if (end < 0) {
  2837. end = 0;
  2838. }
  2839. }
  2840. if (end > this.length) {
  2841. end = this.length;
  2842. }
  2843. const _names = getNames(this);
  2844. const result = [], names = [];
  2845. for (let i = start; i < end; i++) {
  2846. result.push(this[i]);
  2847. names.push(_names[i]);
  2848. }
  2849. return new Result(_guard$4, result, names);
  2850. }
  2851. /**
  2852. * @_ignore
  2853. */
  2854. filter(callback, thisArg) {
  2855. const _names = getNames(this);
  2856. const result = [], names = [];
  2857. for (let i = 0; i < this.length; i++) {
  2858. const item = this[i];
  2859. if (item instanceof Error) {
  2860. throwError(`index ${i}`, item);
  2861. }
  2862. if (callback.call(thisArg, item, i, this)) {
  2863. result.push(item);
  2864. names.push(_names[i]);
  2865. }
  2866. }
  2867. return new Result(_guard$4, result, names);
  2868. }
  2869. /**
  2870. * @_ignore
  2871. */
  2872. map(callback, thisArg) {
  2873. const result = [];
  2874. for (let i = 0; i < this.length; i++) {
  2875. const item = this[i];
  2876. if (item instanceof Error) {
  2877. throwError(`index ${i}`, item);
  2878. }
  2879. result.push(callback.call(thisArg, item, i, this));
  2880. }
  2881. return result;
  2882. }
  2883. /**
  2884. * Returns the value for %%name%%.
  2885. *
  2886. * Since it is possible to have a key whose name conflicts with
  2887. * a method on a [[Result]] or its superclass Array, or any
  2888. * JavaScript keyword, this ensures all named values are still
  2889. * accessible by name.
  2890. */
  2891. getValue(name) {
  2892. const index = getNames(this).indexOf(name);
  2893. if (index === -1) {
  2894. return undefined;
  2895. }
  2896. const value = this[index];
  2897. if (value instanceof Error) {
  2898. throwError(`property ${JSON.stringify(name)}`, value.error);
  2899. }
  2900. return value;
  2901. }
  2902. /**
  2903. * Creates a new [[Result]] for %%items%% with each entry
  2904. * also accessible by its corresponding name in %%keys%%.
  2905. */
  2906. static fromItems(items, keys) {
  2907. return new Result(_guard$4, items, keys);
  2908. }
  2909. }
  2910. /**
  2911. * Returns all errors found in a [[Result]].
  2912. *
  2913. * Since certain errors encountered when creating a [[Result]] do
  2914. * not impact the ability to continue parsing data, they are
  2915. * deferred until they are actually accessed. Hence a faulty string
  2916. * in an Event that is never used does not impact the program flow.
  2917. *
  2918. * However, sometimes it may be useful to access, identify or
  2919. * validate correctness of a [[Result]].
  2920. *
  2921. * @_docloc api/abi
  2922. */
  2923. function checkResultErrors(result) {
  2924. // Find the first error (if any)
  2925. const errors = [];
  2926. const checkErrors = function (path, object) {
  2927. if (!Array.isArray(object)) {
  2928. return;
  2929. }
  2930. for (let key in object) {
  2931. const childPath = path.slice();
  2932. childPath.push(key);
  2933. try {
  2934. checkErrors(childPath, object[key]);
  2935. }
  2936. catch (error) {
  2937. errors.push({ path: childPath, error: error });
  2938. }
  2939. }
  2940. };
  2941. checkErrors([], result);
  2942. return errors;
  2943. }
  2944. function getValue$1(value) {
  2945. let bytes = toBeArray(value);
  2946. assert(bytes.length <= WordSize, "value out-of-bounds", "BUFFER_OVERRUN", { buffer: bytes, length: WordSize, offset: bytes.length });
  2947. if (bytes.length !== WordSize) {
  2948. bytes = getBytesCopy(concat([Padding.slice(bytes.length % WordSize), bytes]));
  2949. }
  2950. return bytes;
  2951. }
  2952. /**
  2953. * @_ignore
  2954. */
  2955. class Coder {
  2956. // The coder name:
  2957. // - address, uint256, tuple, array, etc.
  2958. name;
  2959. // The fully expanded type, including composite types:
  2960. // - address, uint256, tuple(address,bytes), uint256[3][4][], etc.
  2961. type;
  2962. // The localName bound in the signature, in this example it is "baz":
  2963. // - tuple(address foo, uint bar) baz
  2964. localName;
  2965. // Whether this type is dynamic:
  2966. // - Dynamic: bytes, string, address[], tuple(boolean[]), etc.
  2967. // - Not Dynamic: address, uint256, boolean[3], tuple(address, uint8)
  2968. dynamic;
  2969. constructor(name, type, localName, dynamic) {
  2970. defineProperties(this, { name, type, localName, dynamic }, {
  2971. name: "string", type: "string", localName: "string", dynamic: "boolean"
  2972. });
  2973. }
  2974. _throwError(message, value) {
  2975. assertArgument(false, message, this.localName, value);
  2976. }
  2977. }
  2978. /**
  2979. * @_ignore
  2980. */
  2981. class Writer {
  2982. // An array of WordSize lengthed objects to concatenation
  2983. #data;
  2984. #dataLength;
  2985. constructor() {
  2986. this.#data = [];
  2987. this.#dataLength = 0;
  2988. }
  2989. get data() {
  2990. return concat(this.#data);
  2991. }
  2992. get length() { return this.#dataLength; }
  2993. #writeData(data) {
  2994. this.#data.push(data);
  2995. this.#dataLength += data.length;
  2996. return data.length;
  2997. }
  2998. appendWriter(writer) {
  2999. return this.#writeData(getBytesCopy(writer.data));
  3000. }
  3001. // Arrayish item; pad on the right to *nearest* WordSize
  3002. writeBytes(value) {
  3003. let bytes = getBytesCopy(value);
  3004. const paddingOffset = bytes.length % WordSize;
  3005. if (paddingOffset) {
  3006. bytes = getBytesCopy(concat([bytes, Padding.slice(paddingOffset)]));
  3007. }
  3008. return this.#writeData(bytes);
  3009. }
  3010. // Numeric item; pad on the left *to* WordSize
  3011. writeValue(value) {
  3012. return this.#writeData(getValue$1(value));
  3013. }
  3014. // Inserts a numeric place-holder, returning a callback that can
  3015. // be used to asjust the value later
  3016. writeUpdatableValue() {
  3017. const offset = this.#data.length;
  3018. this.#data.push(Padding);
  3019. this.#dataLength += WordSize;
  3020. return (value) => {
  3021. this.#data[offset] = getValue$1(value);
  3022. };
  3023. }
  3024. }
  3025. /**
  3026. * @_ignore
  3027. */
  3028. class Reader {
  3029. // Allows incomplete unpadded data to be read; otherwise an error
  3030. // is raised if attempting to overrun the buffer. This is required
  3031. // to deal with an old Solidity bug, in which event data for
  3032. // external (not public thoguh) was tightly packed.
  3033. allowLoose;
  3034. #data;
  3035. #offset;
  3036. #bytesRead;
  3037. #parent;
  3038. #maxInflation;
  3039. constructor(data, allowLoose, maxInflation) {
  3040. defineProperties(this, { allowLoose: !!allowLoose });
  3041. this.#data = getBytesCopy(data);
  3042. this.#bytesRead = 0;
  3043. this.#parent = null;
  3044. this.#maxInflation = (maxInflation != null) ? maxInflation : 1024;
  3045. this.#offset = 0;
  3046. }
  3047. get data() { return hexlify(this.#data); }
  3048. get dataLength() { return this.#data.length; }
  3049. get consumed() { return this.#offset; }
  3050. get bytes() { return new Uint8Array(this.#data); }
  3051. #incrementBytesRead(count) {
  3052. if (this.#parent) {
  3053. return this.#parent.#incrementBytesRead(count);
  3054. }
  3055. this.#bytesRead += count;
  3056. // Check for excessive inflation (see: #4537)
  3057. assert(this.#maxInflation < 1 || this.#bytesRead <= this.#maxInflation * this.dataLength, `compressed ABI data exceeds inflation ratio of ${this.#maxInflation} ( see: https:/\/github.com/ethers-io/ethers.js/issues/4537 )`, "BUFFER_OVERRUN", {
  3058. buffer: getBytesCopy(this.#data), offset: this.#offset,
  3059. length: count, info: {
  3060. bytesRead: this.#bytesRead,
  3061. dataLength: this.dataLength
  3062. }
  3063. });
  3064. }
  3065. #peekBytes(offset, length, loose) {
  3066. let alignedLength = Math.ceil(length / WordSize) * WordSize;
  3067. if (this.#offset + alignedLength > this.#data.length) {
  3068. if (this.allowLoose && loose && this.#offset + length <= this.#data.length) {
  3069. alignedLength = length;
  3070. }
  3071. else {
  3072. assert(false, "data out-of-bounds", "BUFFER_OVERRUN", {
  3073. buffer: getBytesCopy(this.#data),
  3074. length: this.#data.length,
  3075. offset: this.#offset + alignedLength
  3076. });
  3077. }
  3078. }
  3079. return this.#data.slice(this.#offset, this.#offset + alignedLength);
  3080. }
  3081. // Create a sub-reader with the same underlying data, but offset
  3082. subReader(offset) {
  3083. const reader = new Reader(this.#data.slice(this.#offset + offset), this.allowLoose, this.#maxInflation);
  3084. reader.#parent = this;
  3085. return reader;
  3086. }
  3087. // Read bytes
  3088. readBytes(length, loose) {
  3089. let bytes = this.#peekBytes(0, length, !!loose);
  3090. this.#incrementBytesRead(length);
  3091. this.#offset += bytes.length;
  3092. // @TODO: Make sure the length..end bytes are all 0?
  3093. return bytes.slice(0, length);
  3094. }
  3095. // Read a numeric values
  3096. readValue() {
  3097. return toBigInt(this.readBytes(WordSize));
  3098. }
  3099. readIndex() {
  3100. return toNumber(this.readBytes(WordSize));
  3101. }
  3102. }
  3103. function number(n) {
  3104. if (!Number.isSafeInteger(n) || n < 0)
  3105. throw new Error(`Wrong positive integer: ${n}`);
  3106. }
  3107. function bytes(b, ...lengths) {
  3108. if (!(b instanceof Uint8Array))
  3109. throw new Error('Expected Uint8Array');
  3110. if (lengths.length > 0 && !lengths.includes(b.length))
  3111. throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
  3112. }
  3113. function hash(hash) {
  3114. if (typeof hash !== 'function' || typeof hash.create !== 'function')
  3115. throw new Error('Hash should be wrapped by utils.wrapConstructor');
  3116. number(hash.outputLen);
  3117. number(hash.blockLen);
  3118. }
  3119. function exists(instance, checkFinished = true) {
  3120. if (instance.destroyed)
  3121. throw new Error('Hash instance has been destroyed');
  3122. if (checkFinished && instance.finished)
  3123. throw new Error('Hash#digest() has already been called');
  3124. }
  3125. function output(out, instance) {
  3126. bytes(out);
  3127. const min = instance.outputLen;
  3128. if (out.length < min) {
  3129. throw new Error(`digestInto() expects output buffer of length at least ${min}`);
  3130. }
  3131. }
  3132. const crypto$1 = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
  3133. /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
  3134. // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
  3135. // node.js versions earlier than v19 don't declare it in global scope.
  3136. // For node.js, package.json#exports field mapping rewrites import
  3137. // from `crypto` to `cryptoNode`, which imports native module.
  3138. // Makes the utils un-importable in browsers without a bundler.
  3139. // Once node.js 18 is deprecated, we can just drop the import.
  3140. const u8a$1 = (a) => a instanceof Uint8Array;
  3141. const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
  3142. // Cast array to view
  3143. const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
  3144. // The rotate right (circular right shift) operation for uint32
  3145. const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
  3146. // big-endian hardware is rare. Just in case someone still decides to run hashes:
  3147. // early-throw an error because we don't support BE yet.
  3148. const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
  3149. if (!isLE)
  3150. throw new Error('Non little-endian hardware is not supported');
  3151. // There is no setImmediate in browser and setTimeout is slow.
  3152. // call of async fn will return Promise, which will be fullfiled only on
  3153. // next scheduler queue processing step and this is exactly what we need.
  3154. const nextTick = async () => { };
  3155. // Returns control to thread each 'tick' ms to avoid blocking
  3156. async function asyncLoop(iters, tick, cb) {
  3157. let ts = Date.now();
  3158. for (let i = 0; i < iters; i++) {
  3159. cb(i);
  3160. // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
  3161. const diff = Date.now() - ts;
  3162. if (diff >= 0 && diff < tick)
  3163. continue;
  3164. await nextTick();
  3165. ts += diff;
  3166. }
  3167. }
  3168. /**
  3169. * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
  3170. */
  3171. function utf8ToBytes$1(str) {
  3172. if (typeof str !== 'string')
  3173. throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
  3174. return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
  3175. }
  3176. /**
  3177. * Normalizes (non-hex) string or Uint8Array to Uint8Array.
  3178. * Warning: when Uint8Array is passed, it would NOT get copied.
  3179. * Keep in mind for future mutable operations.
  3180. */
  3181. function toBytes(data) {
  3182. if (typeof data === 'string')
  3183. data = utf8ToBytes$1(data);
  3184. if (!u8a$1(data))
  3185. throw new Error(`expected Uint8Array, got ${typeof data}`);
  3186. return data;
  3187. }
  3188. /**
  3189. * Copies several Uint8Arrays into one.
  3190. */
  3191. function concatBytes$1(...arrays) {
  3192. const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));
  3193. let pad = 0; // walk through each item, ensure they have proper type
  3194. arrays.forEach((a) => {
  3195. if (!u8a$1(a))
  3196. throw new Error('Uint8Array expected');
  3197. r.set(a, pad);
  3198. pad += a.length;
  3199. });
  3200. return r;
  3201. }
  3202. // For runtime check if class implements interface
  3203. class Hash {
  3204. // Safe version that clones internal state
  3205. clone() {
  3206. return this._cloneInto();
  3207. }
  3208. }
  3209. const toStr = {}.toString;
  3210. function checkOpts(defaults, opts) {
  3211. if (opts !== undefined && toStr.call(opts) !== '[object Object]')
  3212. throw new Error('Options should be object or undefined');
  3213. const merged = Object.assign(defaults, opts);
  3214. return merged;
  3215. }
  3216. function wrapConstructor(hashCons) {
  3217. const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
  3218. const tmp = hashCons();
  3219. hashC.outputLen = tmp.outputLen;
  3220. hashC.blockLen = tmp.blockLen;
  3221. hashC.create = () => hashCons();
  3222. return hashC;
  3223. }
  3224. /**
  3225. * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
  3226. */
  3227. function randomBytes$2(bytesLength = 32) {
  3228. if (crypto$1 && typeof crypto$1.getRandomValues === 'function') {
  3229. return crypto$1.getRandomValues(new Uint8Array(bytesLength));
  3230. }
  3231. throw new Error('crypto.getRandomValues must be defined');
  3232. }
  3233. // HMAC (RFC 2104)
  3234. class HMAC extends Hash {
  3235. constructor(hash$1, _key) {
  3236. super();
  3237. this.finished = false;
  3238. this.destroyed = false;
  3239. hash(hash$1);
  3240. const key = toBytes(_key);
  3241. this.iHash = hash$1.create();
  3242. if (typeof this.iHash.update !== 'function')
  3243. throw new Error('Expected instance of class which extends utils.Hash');
  3244. this.blockLen = this.iHash.blockLen;
  3245. this.outputLen = this.iHash.outputLen;
  3246. const blockLen = this.blockLen;
  3247. const pad = new Uint8Array(blockLen);
  3248. // blockLen can be bigger than outputLen
  3249. pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key);
  3250. for (let i = 0; i < pad.length; i++)
  3251. pad[i] ^= 0x36;
  3252. this.iHash.update(pad);
  3253. // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
  3254. this.oHash = hash$1.create();
  3255. // Undo internal XOR && apply outer XOR
  3256. for (let i = 0; i < pad.length; i++)
  3257. pad[i] ^= 0x36 ^ 0x5c;
  3258. this.oHash.update(pad);
  3259. pad.fill(0);
  3260. }
  3261. update(buf) {
  3262. exists(this);
  3263. this.iHash.update(buf);
  3264. return this;
  3265. }
  3266. digestInto(out) {
  3267. exists(this);
  3268. bytes(out, this.outputLen);
  3269. this.finished = true;
  3270. this.iHash.digestInto(out);
  3271. this.oHash.update(out);
  3272. this.oHash.digestInto(out);
  3273. this.destroy();
  3274. }
  3275. digest() {
  3276. const out = new Uint8Array(this.oHash.outputLen);
  3277. this.digestInto(out);
  3278. return out;
  3279. }
  3280. _cloneInto(to) {
  3281. // Create new instance without calling constructor since key already in state and we don't know it.
  3282. to || (to = Object.create(Object.getPrototypeOf(this), {}));
  3283. const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
  3284. to = to;
  3285. to.finished = finished;
  3286. to.destroyed = destroyed;
  3287. to.blockLen = blockLen;
  3288. to.outputLen = outputLen;
  3289. to.oHash = oHash._cloneInto(to.oHash);
  3290. to.iHash = iHash._cloneInto(to.iHash);
  3291. return to;
  3292. }
  3293. destroy() {
  3294. this.destroyed = true;
  3295. this.oHash.destroy();
  3296. this.iHash.destroy();
  3297. }
  3298. }
  3299. /**
  3300. * HMAC: RFC2104 message authentication code.
  3301. * @param hash - function that would be used e.g. sha256
  3302. * @param key - message key
  3303. * @param message - message data
  3304. */
  3305. const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
  3306. hmac.create = (hash, key) => new HMAC(hash, key);
  3307. // Common prologue and epilogue for sync/async functions
  3308. function pbkdf2Init(hash$1, _password, _salt, _opts) {
  3309. hash(hash$1);
  3310. const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
  3311. const { c, dkLen, asyncTick } = opts;
  3312. number(c);
  3313. number(dkLen);
  3314. number(asyncTick);
  3315. if (c < 1)
  3316. throw new Error('PBKDF2: iterations (c) should be >= 1');
  3317. const password = toBytes(_password);
  3318. const salt = toBytes(_salt);
  3319. // DK = PBKDF2(PRF, Password, Salt, c, dkLen);
  3320. const DK = new Uint8Array(dkLen);
  3321. // U1 = PRF(Password, Salt + INT_32_BE(i))
  3322. const PRF = hmac.create(hash$1, password);
  3323. const PRFSalt = PRF._cloneInto().update(salt);
  3324. return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
  3325. }
  3326. function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
  3327. PRF.destroy();
  3328. PRFSalt.destroy();
  3329. if (prfW)
  3330. prfW.destroy();
  3331. u.fill(0);
  3332. return DK;
  3333. }
  3334. /**
  3335. * PBKDF2-HMAC: RFC 2898 key derivation function
  3336. * @param hash - hash function that would be used e.g. sha256
  3337. * @param password - password from which a derived key is generated
  3338. * @param salt - cryptographic salt
  3339. * @param opts - {c, dkLen} where c is work factor and dkLen is output message size
  3340. */
  3341. function pbkdf2$1(hash, password, salt, opts) {
  3342. const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
  3343. let prfW; // Working copy
  3344. const arr = new Uint8Array(4);
  3345. const view = createView(arr);
  3346. const u = new Uint8Array(PRF.outputLen);
  3347. // DK = T1 + T2 + ⋯ + Tdklen/hlen
  3348. for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
  3349. // Ti = F(Password, Salt, c, i)
  3350. const Ti = DK.subarray(pos, pos + PRF.outputLen);
  3351. view.setInt32(0, ti, false);
  3352. // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc
  3353. // U1 = PRF(Password, Salt + INT_32_BE(i))
  3354. (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
  3355. Ti.set(u.subarray(0, Ti.length));
  3356. for (let ui = 1; ui < c; ui++) {
  3357. // Uc = PRF(Password, Uc−1)
  3358. PRF._cloneInto(prfW).update(u).digestInto(u);
  3359. for (let i = 0; i < Ti.length; i++)
  3360. Ti[i] ^= u[i];
  3361. }
  3362. }
  3363. return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
  3364. }
  3365. // Polyfill for Safari 14
  3366. function setBigUint64(view, byteOffset, value, isLE) {
  3367. if (typeof view.setBigUint64 === 'function')
  3368. return view.setBigUint64(byteOffset, value, isLE);
  3369. const _32n = BigInt(32);
  3370. const _u32_max = BigInt(0xffffffff);
  3371. const wh = Number((value >> _32n) & _u32_max);
  3372. const wl = Number(value & _u32_max);
  3373. const h = isLE ? 4 : 0;
  3374. const l = isLE ? 0 : 4;
  3375. view.setUint32(byteOffset + h, wh, isLE);
  3376. view.setUint32(byteOffset + l, wl, isLE);
  3377. }
  3378. // Base SHA2 class (RFC 6234)
  3379. class SHA2 extends Hash {
  3380. constructor(blockLen, outputLen, padOffset, isLE) {
  3381. super();
  3382. this.blockLen = blockLen;
  3383. this.outputLen = outputLen;
  3384. this.padOffset = padOffset;
  3385. this.isLE = isLE;
  3386. this.finished = false;
  3387. this.length = 0;
  3388. this.pos = 0;
  3389. this.destroyed = false;
  3390. this.buffer = new Uint8Array(blockLen);
  3391. this.view = createView(this.buffer);
  3392. }
  3393. update(data) {
  3394. exists(this);
  3395. const { view, buffer, blockLen } = this;
  3396. data = toBytes(data);
  3397. const len = data.length;
  3398. for (let pos = 0; pos < len;) {
  3399. const take = Math.min(blockLen - this.pos, len - pos);
  3400. // Fast path: we have at least one block in input, cast it to view and process
  3401. if (take === blockLen) {
  3402. const dataView = createView(data);
  3403. for (; blockLen <= len - pos; pos += blockLen)
  3404. this.process(dataView, pos);
  3405. continue;
  3406. }
  3407. buffer.set(data.subarray(pos, pos + take), this.pos);
  3408. this.pos += take;
  3409. pos += take;
  3410. if (this.pos === blockLen) {
  3411. this.process(view, 0);
  3412. this.pos = 0;
  3413. }
  3414. }
  3415. this.length += data.length;
  3416. this.roundClean();
  3417. return this;
  3418. }
  3419. digestInto(out) {
  3420. exists(this);
  3421. output(out, this);
  3422. this.finished = true;
  3423. // Padding
  3424. // We can avoid allocation of buffer for padding completely if it
  3425. // was previously not allocated here. But it won't change performance.
  3426. const { buffer, view, blockLen, isLE } = this;
  3427. let { pos } = this;
  3428. // append the bit '1' to the message
  3429. buffer[pos++] = 0b10000000;
  3430. this.buffer.subarray(pos).fill(0);
  3431. // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again
  3432. if (this.padOffset > blockLen - pos) {
  3433. this.process(view, 0);
  3434. pos = 0;
  3435. }
  3436. // Pad until full block byte with zeros
  3437. for (let i = pos; i < blockLen; i++)
  3438. buffer[i] = 0;
  3439. // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
  3440. // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
  3441. // So we just write lowest 64 bits of that value.
  3442. setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
  3443. this.process(view, 0);
  3444. const oview = createView(out);
  3445. const len = this.outputLen;
  3446. // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
  3447. if (len % 4)
  3448. throw new Error('_sha2: outputLen should be aligned to 32bit');
  3449. const outLen = len / 4;
  3450. const state = this.get();
  3451. if (outLen > state.length)
  3452. throw new Error('_sha2: outputLen bigger than state');
  3453. for (let i = 0; i < outLen; i++)
  3454. oview.setUint32(4 * i, state[i], isLE);
  3455. }
  3456. digest() {
  3457. const { buffer, outputLen } = this;
  3458. this.digestInto(buffer);
  3459. const res = buffer.slice(0, outputLen);
  3460. this.destroy();
  3461. return res;
  3462. }
  3463. _cloneInto(to) {
  3464. to || (to = new this.constructor());
  3465. to.set(...this.get());
  3466. const { blockLen, buffer, length, finished, destroyed, pos } = this;
  3467. to.length = length;
  3468. to.pos = pos;
  3469. to.finished = finished;
  3470. to.destroyed = destroyed;
  3471. if (length % blockLen)
  3472. to.buffer.set(buffer);
  3473. return to;
  3474. }
  3475. }
  3476. // SHA2-256 need to try 2^128 hashes to execute birthday attack.
  3477. // BTC network is doing 2^67 hashes/sec as per early 2023.
  3478. // Choice: a ? b : c
  3479. const Chi = (a, b, c) => (a & b) ^ (~a & c);
  3480. // Majority function, true if any two inpust is true
  3481. const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
  3482. // Round constants:
  3483. // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
  3484. // prettier-ignore
  3485. const SHA256_K = /* @__PURE__ */ new Uint32Array([
  3486. 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
  3487. 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
  3488. 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  3489. 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
  3490. 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
  3491. 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  3492. 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
  3493. 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
  3494. ]);
  3495. // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
  3496. // prettier-ignore
  3497. const IV = /* @__PURE__ */ new Uint32Array([
  3498. 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
  3499. ]);
  3500. // Temporary buffer, not used to store anything between runs
  3501. // Named this way because it matches specification.
  3502. const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
  3503. class SHA256 extends SHA2 {
  3504. constructor() {
  3505. super(64, 32, 8, false);
  3506. // We cannot use array here since array allows indexing by variable
  3507. // which means optimizer/compiler cannot use registers.
  3508. this.A = IV[0] | 0;
  3509. this.B = IV[1] | 0;
  3510. this.C = IV[2] | 0;
  3511. this.D = IV[3] | 0;
  3512. this.E = IV[4] | 0;
  3513. this.F = IV[5] | 0;
  3514. this.G = IV[6] | 0;
  3515. this.H = IV[7] | 0;
  3516. }
  3517. get() {
  3518. const { A, B, C, D, E, F, G, H } = this;
  3519. return [A, B, C, D, E, F, G, H];
  3520. }
  3521. // prettier-ignore
  3522. set(A, B, C, D, E, F, G, H) {
  3523. this.A = A | 0;
  3524. this.B = B | 0;
  3525. this.C = C | 0;
  3526. this.D = D | 0;
  3527. this.E = E | 0;
  3528. this.F = F | 0;
  3529. this.G = G | 0;
  3530. this.H = H | 0;
  3531. }
  3532. process(view, offset) {
  3533. // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
  3534. for (let i = 0; i < 16; i++, offset += 4)
  3535. SHA256_W[i] = view.getUint32(offset, false);
  3536. for (let i = 16; i < 64; i++) {
  3537. const W15 = SHA256_W[i - 15];
  3538. const W2 = SHA256_W[i - 2];
  3539. const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
  3540. const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
  3541. SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
  3542. }
  3543. // Compression function main loop, 64 rounds
  3544. let { A, B, C, D, E, F, G, H } = this;
  3545. for (let i = 0; i < 64; i++) {
  3546. const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
  3547. const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
  3548. const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
  3549. const T2 = (sigma0 + Maj(A, B, C)) | 0;
  3550. H = G;
  3551. G = F;
  3552. F = E;
  3553. E = (D + T1) | 0;
  3554. D = C;
  3555. C = B;
  3556. B = A;
  3557. A = (T1 + T2) | 0;
  3558. }
  3559. // Add the compressed chunk to the current hash value
  3560. A = (A + this.A) | 0;
  3561. B = (B + this.B) | 0;
  3562. C = (C + this.C) | 0;
  3563. D = (D + this.D) | 0;
  3564. E = (E + this.E) | 0;
  3565. F = (F + this.F) | 0;
  3566. G = (G + this.G) | 0;
  3567. H = (H + this.H) | 0;
  3568. this.set(A, B, C, D, E, F, G, H);
  3569. }
  3570. roundClean() {
  3571. SHA256_W.fill(0);
  3572. }
  3573. destroy() {
  3574. this.set(0, 0, 0, 0, 0, 0, 0, 0);
  3575. this.buffer.fill(0);
  3576. }
  3577. }
  3578. /**
  3579. * SHA2-256 hash function
  3580. * @param message - data that would be hashed
  3581. */
  3582. const sha256$1 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
  3583. const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
  3584. const _32n = /* @__PURE__ */ BigInt(32);
  3585. // We are not using BigUint64Array, because they are extremely slow as per 2022
  3586. function fromBig(n, le = false) {
  3587. if (le)
  3588. return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
  3589. return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
  3590. }
  3591. function split$1(lst, le = false) {
  3592. let Ah = new Uint32Array(lst.length);
  3593. let Al = new Uint32Array(lst.length);
  3594. for (let i = 0; i < lst.length; i++) {
  3595. const { h, l } = fromBig(lst[i], le);
  3596. [Ah[i], Al[i]] = [h, l];
  3597. }
  3598. return [Ah, Al];
  3599. }
  3600. const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
  3601. // for Shift in [0, 32)
  3602. const shrSH = (h, _l, s) => h >>> s;
  3603. const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
  3604. // Right rotate for Shift in [1, 32)
  3605. const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
  3606. const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
  3607. // Right rotate for Shift in (32, 64), NOTE: 32 is special case.
  3608. const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
  3609. const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
  3610. // Right rotate for shift===32 (just swaps l&h)
  3611. const rotr32H = (_h, l) => l;
  3612. const rotr32L = (h, _l) => h;
  3613. // Left rotate for Shift in [1, 32)
  3614. const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
  3615. const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
  3616. // Left rotate for Shift in (32, 64), NOTE: 32 is special case.
  3617. const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
  3618. const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
  3619. // JS uses 32-bit signed integers for bitwise operations which means we cannot
  3620. // simple take carry out of low bit sum by shift, we need to use division.
  3621. function add(Ah, Al, Bh, Bl) {
  3622. const l = (Al >>> 0) + (Bl >>> 0);
  3623. return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
  3624. }
  3625. // Addition with more than 2 elements
  3626. const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
  3627. const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
  3628. const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
  3629. const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
  3630. const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
  3631. const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
  3632. // prettier-ignore
  3633. const u64 = {
  3634. fromBig, split: split$1, toBig,
  3635. shrSH, shrSL,
  3636. rotrSH, rotrSL, rotrBH, rotrBL,
  3637. rotr32H, rotr32L,
  3638. rotlSH, rotlSL, rotlBH, rotlBL,
  3639. add, add3L, add3H, add4L, add4H, add5H, add5L,
  3640. };
  3641. // Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):
  3642. // prettier-ignore
  3643. const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([
  3644. '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
  3645. '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
  3646. '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
  3647. '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
  3648. '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
  3649. '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
  3650. '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
  3651. '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
  3652. '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
  3653. '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
  3654. '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
  3655. '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
  3656. '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
  3657. '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
  3658. '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
  3659. '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
  3660. '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
  3661. '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
  3662. '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
  3663. '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
  3664. ].map(n => BigInt(n))))();
  3665. // Temporary buffer, not used to store anything between runs
  3666. const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
  3667. const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
  3668. class SHA512 extends SHA2 {
  3669. constructor() {
  3670. super(128, 64, 16, false);
  3671. // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.
  3672. // Also looks cleaner and easier to verify with spec.
  3673. // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
  3674. // h -- high 32 bits, l -- low 32 bits
  3675. this.Ah = 0x6a09e667 | 0;
  3676. this.Al = 0xf3bcc908 | 0;
  3677. this.Bh = 0xbb67ae85 | 0;
  3678. this.Bl = 0x84caa73b | 0;
  3679. this.Ch = 0x3c6ef372 | 0;
  3680. this.Cl = 0xfe94f82b | 0;
  3681. this.Dh = 0xa54ff53a | 0;
  3682. this.Dl = 0x5f1d36f1 | 0;
  3683. this.Eh = 0x510e527f | 0;
  3684. this.El = 0xade682d1 | 0;
  3685. this.Fh = 0x9b05688c | 0;
  3686. this.Fl = 0x2b3e6c1f | 0;
  3687. this.Gh = 0x1f83d9ab | 0;
  3688. this.Gl = 0xfb41bd6b | 0;
  3689. this.Hh = 0x5be0cd19 | 0;
  3690. this.Hl = 0x137e2179 | 0;
  3691. }
  3692. // prettier-ignore
  3693. get() {
  3694. const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
  3695. return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
  3696. }
  3697. // prettier-ignore
  3698. set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
  3699. this.Ah = Ah | 0;
  3700. this.Al = Al | 0;
  3701. this.Bh = Bh | 0;
  3702. this.Bl = Bl | 0;
  3703. this.Ch = Ch | 0;
  3704. this.Cl = Cl | 0;
  3705. this.Dh = Dh | 0;
  3706. this.Dl = Dl | 0;
  3707. this.Eh = Eh | 0;
  3708. this.El = El | 0;
  3709. this.Fh = Fh | 0;
  3710. this.Fl = Fl | 0;
  3711. this.Gh = Gh | 0;
  3712. this.Gl = Gl | 0;
  3713. this.Hh = Hh | 0;
  3714. this.Hl = Hl | 0;
  3715. }
  3716. process(view, offset) {
  3717. // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
  3718. for (let i = 0; i < 16; i++, offset += 4) {
  3719. SHA512_W_H[i] = view.getUint32(offset);
  3720. SHA512_W_L[i] = view.getUint32((offset += 4));
  3721. }
  3722. for (let i = 16; i < 80; i++) {
  3723. // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
  3724. const W15h = SHA512_W_H[i - 15] | 0;
  3725. const W15l = SHA512_W_L[i - 15] | 0;
  3726. const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
  3727. const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
  3728. // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
  3729. const W2h = SHA512_W_H[i - 2] | 0;
  3730. const W2l = SHA512_W_L[i - 2] | 0;
  3731. const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
  3732. const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
  3733. // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
  3734. const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
  3735. const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
  3736. SHA512_W_H[i] = SUMh | 0;
  3737. SHA512_W_L[i] = SUMl | 0;
  3738. }
  3739. let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
  3740. // Compression function main loop, 80 rounds
  3741. for (let i = 0; i < 80; i++) {
  3742. // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
  3743. const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
  3744. const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
  3745. //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
  3746. const CHIh = (Eh & Fh) ^ (~Eh & Gh);
  3747. const CHIl = (El & Fl) ^ (~El & Gl);
  3748. // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
  3749. // prettier-ignore
  3750. const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
  3751. const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
  3752. const T1l = T1ll | 0;
  3753. // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
  3754. const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
  3755. const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
  3756. const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
  3757. const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
  3758. Hh = Gh | 0;
  3759. Hl = Gl | 0;
  3760. Gh = Fh | 0;
  3761. Gl = Fl | 0;
  3762. Fh = Eh | 0;
  3763. Fl = El | 0;
  3764. ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
  3765. Dh = Ch | 0;
  3766. Dl = Cl | 0;
  3767. Ch = Bh | 0;
  3768. Cl = Bl | 0;
  3769. Bh = Ah | 0;
  3770. Bl = Al | 0;
  3771. const All = u64.add3L(T1l, sigma0l, MAJl);
  3772. Ah = u64.add3H(All, T1h, sigma0h, MAJh);
  3773. Al = All | 0;
  3774. }
  3775. // Add the compressed chunk to the current hash value
  3776. ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
  3777. ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
  3778. ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
  3779. ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
  3780. ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
  3781. ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
  3782. ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
  3783. ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
  3784. this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
  3785. }
  3786. roundClean() {
  3787. SHA512_W_H.fill(0);
  3788. SHA512_W_L.fill(0);
  3789. }
  3790. destroy() {
  3791. this.buffer.fill(0);
  3792. this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  3793. }
  3794. }
  3795. const sha512$1 = /* @__PURE__ */ wrapConstructor(() => new SHA512());
  3796. /* Browser Crypto Shims */
  3797. function getGlobal$1() {
  3798. if (typeof self !== 'undefined') {
  3799. return self;
  3800. }
  3801. if (typeof window !== 'undefined') {
  3802. return window;
  3803. }
  3804. if (typeof global !== 'undefined') {
  3805. return global;
  3806. }
  3807. throw new Error('unable to locate global object');
  3808. }
  3809. const anyGlobal = getGlobal$1();
  3810. const crypto = anyGlobal.crypto || anyGlobal.msCrypto;
  3811. function createHash(algo) {
  3812. switch (algo) {
  3813. case "sha256": return sha256$1.create();
  3814. case "sha512": return sha512$1.create();
  3815. }
  3816. assertArgument(false, "invalid hashing algorithm name", "algorithm", algo);
  3817. }
  3818. function createHmac(_algo, key) {
  3819. const algo = ({ sha256: sha256$1, sha512: sha512$1 }[_algo]);
  3820. assertArgument(algo != null, "invalid hmac algorithm", "algorithm", _algo);
  3821. return hmac.create(algo, key);
  3822. }
  3823. function pbkdf2Sync(password, salt, iterations, keylen, _algo) {
  3824. const algo = ({ sha256: sha256$1, sha512: sha512$1 }[_algo]);
  3825. assertArgument(algo != null, "invalid pbkdf2 algorithm", "algorithm", _algo);
  3826. return pbkdf2$1(algo, password, salt, { c: iterations, dkLen: keylen });
  3827. }
  3828. function randomBytes$1(length) {
  3829. assert(crypto != null, "platform does not support secure random numbers", "UNSUPPORTED_OPERATION", {
  3830. operation: "randomBytes"
  3831. });
  3832. assertArgument(Number.isInteger(length) && length > 0 && length <= 1024, "invalid length", "length", length);
  3833. const result = new Uint8Array(length);
  3834. crypto.getRandomValues(result);
  3835. return result;
  3836. }
  3837. /**
  3838. * An **HMAC** enables verification that a given key was used
  3839. * to authenticate a payload.
  3840. *
  3841. * See: [[link-wiki-hmac]]
  3842. *
  3843. * @_subsection: api/crypto:HMAC [about-hmac]
  3844. */
  3845. let locked$4 = false;
  3846. const _computeHmac = function (algorithm, key, data) {
  3847. return createHmac(algorithm, key).update(data).digest();
  3848. };
  3849. let __computeHmac = _computeHmac;
  3850. /**
  3851. * Return the HMAC for %%data%% using the %%key%% key with the underlying
  3852. * %%algo%% used for compression.
  3853. *
  3854. * @example:
  3855. * key = id("some-secret")
  3856. *
  3857. * // Compute the HMAC
  3858. * computeHmac("sha256", key, "0x1337")
  3859. * //_result:
  3860. *
  3861. * // To compute the HMAC of UTF-8 data, the data must be
  3862. * // converted to UTF-8 bytes
  3863. * computeHmac("sha256", key, toUtf8Bytes("Hello World"))
  3864. * //_result:
  3865. *
  3866. */
  3867. function computeHmac(algorithm, _key, _data) {
  3868. const key = getBytes(_key, "key");
  3869. const data = getBytes(_data, "data");
  3870. return hexlify(__computeHmac(algorithm, key, data));
  3871. }
  3872. computeHmac._ = _computeHmac;
  3873. computeHmac.lock = function () { locked$4 = true; };
  3874. computeHmac.register = function (func) {
  3875. if (locked$4) {
  3876. throw new Error("computeHmac is locked");
  3877. }
  3878. __computeHmac = func;
  3879. };
  3880. Object.freeze(computeHmac);
  3881. // SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.
  3882. // It's called a sponge function.
  3883. // Various per round constants calculations
  3884. const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []];
  3885. const _0n$4 = /* @__PURE__ */ BigInt(0);
  3886. const _1n$5 = /* @__PURE__ */ BigInt(1);
  3887. const _2n$3 = /* @__PURE__ */ BigInt(2);
  3888. const _7n = /* @__PURE__ */ BigInt(7);
  3889. const _256n = /* @__PURE__ */ BigInt(256);
  3890. const _0x71n = /* @__PURE__ */ BigInt(0x71);
  3891. for (let round = 0, R = _1n$5, x = 1, y = 0; round < 24; round++) {
  3892. // Pi
  3893. [x, y] = [y, (2 * x + 3 * y) % 5];
  3894. SHA3_PI.push(2 * (5 * y + x));
  3895. // Rotational
  3896. SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);
  3897. // Iota
  3898. let t = _0n$4;
  3899. for (let j = 0; j < 7; j++) {
  3900. R = ((R << _1n$5) ^ ((R >> _7n) * _0x71n)) % _256n;
  3901. if (R & _2n$3)
  3902. t ^= _1n$5 << ((_1n$5 << /* @__PURE__ */ BigInt(j)) - _1n$5);
  3903. }
  3904. _SHA3_IOTA.push(t);
  3905. }
  3906. const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split$1(_SHA3_IOTA, true);
  3907. // Left rotation (without 0, 32, 64)
  3908. const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));
  3909. const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));
  3910. // Same as keccakf1600, but allows to skip some rounds
  3911. function keccakP(s, rounds = 24) {
  3912. const B = new Uint32Array(5 * 2);
  3913. // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
  3914. for (let round = 24 - rounds; round < 24; round++) {
  3915. // Theta θ
  3916. for (let x = 0; x < 10; x++)
  3917. B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
  3918. for (let x = 0; x < 10; x += 2) {
  3919. const idx1 = (x + 8) % 10;
  3920. const idx0 = (x + 2) % 10;
  3921. const B0 = B[idx0];
  3922. const B1 = B[idx0 + 1];
  3923. const Th = rotlH(B0, B1, 1) ^ B[idx1];
  3924. const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
  3925. for (let y = 0; y < 50; y += 10) {
  3926. s[x + y] ^= Th;
  3927. s[x + y + 1] ^= Tl;
  3928. }
  3929. }
  3930. // Rho (ρ) and Pi (π)
  3931. let curH = s[2];
  3932. let curL = s[3];
  3933. for (let t = 0; t < 24; t++) {
  3934. const shift = SHA3_ROTL[t];
  3935. const Th = rotlH(curH, curL, shift);
  3936. const Tl = rotlL(curH, curL, shift);
  3937. const PI = SHA3_PI[t];
  3938. curH = s[PI];
  3939. curL = s[PI + 1];
  3940. s[PI] = Th;
  3941. s[PI + 1] = Tl;
  3942. }
  3943. // Chi (χ)
  3944. for (let y = 0; y < 50; y += 10) {
  3945. for (let x = 0; x < 10; x++)
  3946. B[x] = s[y + x];
  3947. for (let x = 0; x < 10; x++)
  3948. s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
  3949. }
  3950. // Iota (ι)
  3951. s[0] ^= SHA3_IOTA_H[round];
  3952. s[1] ^= SHA3_IOTA_L[round];
  3953. }
  3954. B.fill(0);
  3955. }
  3956. class Keccak extends Hash {
  3957. // NOTE: we accept arguments in bytes instead of bits here.
  3958. constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
  3959. super();
  3960. this.blockLen = blockLen;
  3961. this.suffix = suffix;
  3962. this.outputLen = outputLen;
  3963. this.enableXOF = enableXOF;
  3964. this.rounds = rounds;
  3965. this.pos = 0;
  3966. this.posOut = 0;
  3967. this.finished = false;
  3968. this.destroyed = false;
  3969. // Can be passed from user as dkLen
  3970. number(outputLen);
  3971. // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes
  3972. if (0 >= this.blockLen || this.blockLen >= 200)
  3973. throw new Error('Sha3 supports only keccak-f1600 function');
  3974. this.state = new Uint8Array(200);
  3975. this.state32 = u32(this.state);
  3976. }
  3977. keccak() {
  3978. keccakP(this.state32, this.rounds);
  3979. this.posOut = 0;
  3980. this.pos = 0;
  3981. }
  3982. update(data) {
  3983. exists(this);
  3984. const { blockLen, state } = this;
  3985. data = toBytes(data);
  3986. const len = data.length;
  3987. for (let pos = 0; pos < len;) {
  3988. const take = Math.min(blockLen - this.pos, len - pos);
  3989. for (let i = 0; i < take; i++)
  3990. state[this.pos++] ^= data[pos++];
  3991. if (this.pos === blockLen)
  3992. this.keccak();
  3993. }
  3994. return this;
  3995. }
  3996. finish() {
  3997. if (this.finished)
  3998. return;
  3999. this.finished = true;
  4000. const { state, suffix, pos, blockLen } = this;
  4001. // Do the padding
  4002. state[pos] ^= suffix;
  4003. if ((suffix & 0x80) !== 0 && pos === blockLen - 1)
  4004. this.keccak();
  4005. state[blockLen - 1] ^= 0x80;
  4006. this.keccak();
  4007. }
  4008. writeInto(out) {
  4009. exists(this, false);
  4010. bytes(out);
  4011. this.finish();
  4012. const bufferOut = this.state;
  4013. const { blockLen } = this;
  4014. for (let pos = 0, len = out.length; pos < len;) {
  4015. if (this.posOut >= blockLen)
  4016. this.keccak();
  4017. const take = Math.min(blockLen - this.posOut, len - pos);
  4018. out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
  4019. this.posOut += take;
  4020. pos += take;
  4021. }
  4022. return out;
  4023. }
  4024. xofInto(out) {
  4025. // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF
  4026. if (!this.enableXOF)
  4027. throw new Error('XOF is not possible for this instance');
  4028. return this.writeInto(out);
  4029. }
  4030. xof(bytes) {
  4031. number(bytes);
  4032. return this.xofInto(new Uint8Array(bytes));
  4033. }
  4034. digestInto(out) {
  4035. output(out, this);
  4036. if (this.finished)
  4037. throw new Error('digest() was already called');
  4038. this.writeInto(out);
  4039. this.destroy();
  4040. return out;
  4041. }
  4042. digest() {
  4043. return this.digestInto(new Uint8Array(this.outputLen));
  4044. }
  4045. destroy() {
  4046. this.destroyed = true;
  4047. this.state.fill(0);
  4048. }
  4049. _cloneInto(to) {
  4050. const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
  4051. to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
  4052. to.state32.set(this.state32);
  4053. to.pos = this.pos;
  4054. to.posOut = this.posOut;
  4055. to.finished = this.finished;
  4056. to.rounds = rounds;
  4057. // Suffix can change in cSHAKE
  4058. to.suffix = suffix;
  4059. to.outputLen = outputLen;
  4060. to.enableXOF = enableXOF;
  4061. to.destroyed = this.destroyed;
  4062. return to;
  4063. }
  4064. }
  4065. const gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen));
  4066. /**
  4067. * keccak-256 hash function. Different from SHA3-256.
  4068. * @param message - that would be hashed
  4069. */
  4070. const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8);
  4071. /**
  4072. * Cryptographic hashing functions
  4073. *
  4074. * @_subsection: api/crypto:Hash Functions [about-crypto-hashing]
  4075. */
  4076. let locked$3 = false;
  4077. const _keccak256 = function (data) {
  4078. return keccak_256(data);
  4079. };
  4080. let __keccak256 = _keccak256;
  4081. /**
  4082. * Compute the cryptographic KECCAK256 hash of %%data%%.
  4083. *
  4084. * The %%data%% **must** be a data representation, to compute the
  4085. * hash of UTF-8 data use the [[id]] function.
  4086. *
  4087. * @returns DataHexstring
  4088. * @example:
  4089. * keccak256("0x")
  4090. * //_result:
  4091. *
  4092. * keccak256("0x1337")
  4093. * //_result:
  4094. *
  4095. * keccak256(new Uint8Array([ 0x13, 0x37 ]))
  4096. * //_result:
  4097. *
  4098. * // Strings are assumed to be DataHexString, otherwise it will
  4099. * // throw. To hash UTF-8 data, see the note above.
  4100. * keccak256("Hello World")
  4101. * //_error:
  4102. */
  4103. function keccak256(_data) {
  4104. const data = getBytes(_data, "data");
  4105. return hexlify(__keccak256(data));
  4106. }
  4107. keccak256._ = _keccak256;
  4108. keccak256.lock = function () { locked$3 = true; };
  4109. keccak256.register = function (func) {
  4110. if (locked$3) {
  4111. throw new TypeError("keccak256 is locked");
  4112. }
  4113. __keccak256 = func;
  4114. };
  4115. Object.freeze(keccak256);
  4116. // https://homes.esat.kuleuven.be/~bosselae/ripemd160.html
  4117. // https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf
  4118. const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]);
  4119. const Id = /* @__PURE__ */ Uint8Array.from({ length: 16 }, (_, i) => i);
  4120. const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16);
  4121. let idxL = [Id];
  4122. let idxR = [Pi];
  4123. for (let i = 0; i < 4; i++)
  4124. for (let j of [idxL, idxR])
  4125. j.push(j[i].map((k) => Rho[k]));
  4126. const shifts = /* @__PURE__ */ [
  4127. [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],
  4128. [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],
  4129. [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],
  4130. [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],
  4131. [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],
  4132. ].map((i) => new Uint8Array(i));
  4133. const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j]));
  4134. const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j]));
  4135. const Kl = /* @__PURE__ */ new Uint32Array([
  4136. 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,
  4137. ]);
  4138. const Kr = /* @__PURE__ */ new Uint32Array([
  4139. 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,
  4140. ]);
  4141. // The rotate left (circular left shift) operation for uint32
  4142. const rotl$1 = (word, shift) => (word << shift) | (word >>> (32 - shift));
  4143. // It's called f() in spec.
  4144. function f(group, x, y, z) {
  4145. if (group === 0)
  4146. return x ^ y ^ z;
  4147. else if (group === 1)
  4148. return (x & y) | (~x & z);
  4149. else if (group === 2)
  4150. return (x | ~y) ^ z;
  4151. else if (group === 3)
  4152. return (x & z) | (y & ~z);
  4153. else
  4154. return x ^ (y | ~z);
  4155. }
  4156. // Temporary buffer, not used to store anything between runs
  4157. const BUF = /* @__PURE__ */ new Uint32Array(16);
  4158. class RIPEMD160 extends SHA2 {
  4159. constructor() {
  4160. super(64, 20, 8, true);
  4161. this.h0 = 0x67452301 | 0;
  4162. this.h1 = 0xefcdab89 | 0;
  4163. this.h2 = 0x98badcfe | 0;
  4164. this.h3 = 0x10325476 | 0;
  4165. this.h4 = 0xc3d2e1f0 | 0;
  4166. }
  4167. get() {
  4168. const { h0, h1, h2, h3, h4 } = this;
  4169. return [h0, h1, h2, h3, h4];
  4170. }
  4171. set(h0, h1, h2, h3, h4) {
  4172. this.h0 = h0 | 0;
  4173. this.h1 = h1 | 0;
  4174. this.h2 = h2 | 0;
  4175. this.h3 = h3 | 0;
  4176. this.h4 = h4 | 0;
  4177. }
  4178. process(view, offset) {
  4179. for (let i = 0; i < 16; i++, offset += 4)
  4180. BUF[i] = view.getUint32(offset, true);
  4181. // prettier-ignore
  4182. let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;
  4183. // Instead of iterating 0 to 80, we split it into 5 groups
  4184. // And use the groups in constants, functions, etc. Much simpler
  4185. for (let group = 0; group < 5; group++) {
  4186. const rGroup = 4 - group;
  4187. const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore
  4188. const rl = idxL[group], rr = idxR[group]; // prettier-ignore
  4189. const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore
  4190. for (let i = 0; i < 16; i++) {
  4191. const tl = (rotl$1(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0;
  4192. al = el, el = dl, dl = rotl$1(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore
  4193. }
  4194. // 2 loops are 10% faster
  4195. for (let i = 0; i < 16; i++) {
  4196. const tr = (rotl$1(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0;
  4197. ar = er, er = dr, dr = rotl$1(cr, 10) | 0, cr = br, br = tr; // prettier-ignore
  4198. }
  4199. }
  4200. // Add the compressed chunk to the current hash value
  4201. this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);
  4202. }
  4203. roundClean() {
  4204. BUF.fill(0);
  4205. }
  4206. destroy() {
  4207. this.destroyed = true;
  4208. this.buffer.fill(0);
  4209. this.set(0, 0, 0, 0, 0);
  4210. }
  4211. }
  4212. /**
  4213. * RIPEMD-160 - a hash function from 1990s.
  4214. * @param message - msg that would be hashed
  4215. */
  4216. const ripemd160$1 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160());
  4217. let locked$2 = false;
  4218. const _ripemd160 = function (data) {
  4219. return ripemd160$1(data);
  4220. };
  4221. let __ripemd160 = _ripemd160;
  4222. /**
  4223. * Compute the cryptographic RIPEMD-160 hash of %%data%%.
  4224. *
  4225. * @_docloc: api/crypto:Hash Functions
  4226. * @returns DataHexstring
  4227. *
  4228. * @example:
  4229. * ripemd160("0x")
  4230. * //_result:
  4231. *
  4232. * ripemd160("0x1337")
  4233. * //_result:
  4234. *
  4235. * ripemd160(new Uint8Array([ 0x13, 0x37 ]))
  4236. * //_result:
  4237. *
  4238. */
  4239. function ripemd160(_data) {
  4240. const data = getBytes(_data, "data");
  4241. return hexlify(__ripemd160(data));
  4242. }
  4243. ripemd160._ = _ripemd160;
  4244. ripemd160.lock = function () { locked$2 = true; };
  4245. ripemd160.register = function (func) {
  4246. if (locked$2) {
  4247. throw new TypeError("ripemd160 is locked");
  4248. }
  4249. __ripemd160 = func;
  4250. };
  4251. Object.freeze(ripemd160);
  4252. /**
  4253. * A **Password-Based Key-Derivation Function** is designed to create
  4254. * a sequence of bytes suitible as a **key** from a human-rememberable
  4255. * password.
  4256. *
  4257. * @_subsection: api/crypto:Passwords [about-pbkdf]
  4258. */
  4259. let locked$1 = false;
  4260. const _pbkdf2 = function (password, salt, iterations, keylen, algo) {
  4261. return pbkdf2Sync(password, salt, iterations, keylen, algo);
  4262. };
  4263. let __pbkdf2 = _pbkdf2;
  4264. /**
  4265. * Return the [[link-pbkdf2]] for %%keylen%% bytes for %%password%% using
  4266. * the %%salt%% and using %%iterations%% of %%algo%%.
  4267. *
  4268. * This PBKDF is outdated and should not be used in new projects, but is
  4269. * required to decrypt older files.
  4270. *
  4271. * @example:
  4272. * // The password must be converted to bytes, and it is generally
  4273. * // best practices to ensure the string has been normalized. Many
  4274. * // formats explicitly indicate the normalization form to use.
  4275. * password = "hello"
  4276. * passwordBytes = toUtf8Bytes(password, "NFKC")
  4277. *
  4278. * salt = id("some-salt")
  4279. *
  4280. * // Compute the PBKDF2
  4281. * pbkdf2(passwordBytes, salt, 1024, 16, "sha256")
  4282. * //_result:
  4283. */
  4284. function pbkdf2(_password, _salt, iterations, keylen, algo) {
  4285. const password = getBytes(_password, "password");
  4286. const salt = getBytes(_salt, "salt");
  4287. return hexlify(__pbkdf2(password, salt, iterations, keylen, algo));
  4288. }
  4289. pbkdf2._ = _pbkdf2;
  4290. pbkdf2.lock = function () { locked$1 = true; };
  4291. pbkdf2.register = function (func) {
  4292. if (locked$1) {
  4293. throw new Error("pbkdf2 is locked");
  4294. }
  4295. __pbkdf2 = func;
  4296. };
  4297. Object.freeze(pbkdf2);
  4298. /**
  4299. * A **Cryptographically Secure Random Value** is one that has been
  4300. * generated with additional care take to prevent side-channels
  4301. * from allowing others to detect it and prevent others from through
  4302. * coincidence generate the same values.
  4303. *
  4304. * @_subsection: api/crypto:Random Values [about-crypto-random]
  4305. */
  4306. let locked = false;
  4307. const _randomBytes = function (length) {
  4308. return new Uint8Array(randomBytes$1(length));
  4309. };
  4310. let __randomBytes = _randomBytes;
  4311. /**
  4312. * Return %%length%% bytes of cryptographically secure random data.
  4313. *
  4314. * @example:
  4315. * randomBytes(8)
  4316. * //_result:
  4317. */
  4318. function randomBytes(length) {
  4319. return __randomBytes(length);
  4320. }
  4321. randomBytes._ = _randomBytes;
  4322. randomBytes.lock = function () { locked = true; };
  4323. randomBytes.register = function (func) {
  4324. if (locked) {
  4325. throw new Error("randomBytes is locked");
  4326. }
  4327. __randomBytes = func;
  4328. };
  4329. Object.freeze(randomBytes);
  4330. // RFC 7914 Scrypt KDF
  4331. // Left rotate for uint32
  4332. const rotl = (a, b) => (a << b) | (a >>> (32 - b));
  4333. // The main Scrypt loop: uses Salsa extensively.
  4334. // Six versions of the function were tried, this is the fastest one.
  4335. // prettier-ignore
  4336. function XorAndSalsa(prev, pi, input, ii, out, oi) {
  4337. // Based on https://cr.yp.to/salsa20.html
  4338. // Xor blocks
  4339. let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++];
  4340. let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++];
  4341. let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++];
  4342. let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++];
  4343. let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++];
  4344. let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++];
  4345. let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++];
  4346. let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++];
  4347. // Save state to temporary variables (salsa)
  4348. let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
  4349. // Main loop (salsa)
  4350. for (let i = 0; i < 8; i += 2) {
  4351. x04 ^= rotl(x00 + x12 | 0, 7);
  4352. x08 ^= rotl(x04 + x00 | 0, 9);
  4353. x12 ^= rotl(x08 + x04 | 0, 13);
  4354. x00 ^= rotl(x12 + x08 | 0, 18);
  4355. x09 ^= rotl(x05 + x01 | 0, 7);
  4356. x13 ^= rotl(x09 + x05 | 0, 9);
  4357. x01 ^= rotl(x13 + x09 | 0, 13);
  4358. x05 ^= rotl(x01 + x13 | 0, 18);
  4359. x14 ^= rotl(x10 + x06 | 0, 7);
  4360. x02 ^= rotl(x14 + x10 | 0, 9);
  4361. x06 ^= rotl(x02 + x14 | 0, 13);
  4362. x10 ^= rotl(x06 + x02 | 0, 18);
  4363. x03 ^= rotl(x15 + x11 | 0, 7);
  4364. x07 ^= rotl(x03 + x15 | 0, 9);
  4365. x11 ^= rotl(x07 + x03 | 0, 13);
  4366. x15 ^= rotl(x11 + x07 | 0, 18);
  4367. x01 ^= rotl(x00 + x03 | 0, 7);
  4368. x02 ^= rotl(x01 + x00 | 0, 9);
  4369. x03 ^= rotl(x02 + x01 | 0, 13);
  4370. x00 ^= rotl(x03 + x02 | 0, 18);
  4371. x06 ^= rotl(x05 + x04 | 0, 7);
  4372. x07 ^= rotl(x06 + x05 | 0, 9);
  4373. x04 ^= rotl(x07 + x06 | 0, 13);
  4374. x05 ^= rotl(x04 + x07 | 0, 18);
  4375. x11 ^= rotl(x10 + x09 | 0, 7);
  4376. x08 ^= rotl(x11 + x10 | 0, 9);
  4377. x09 ^= rotl(x08 + x11 | 0, 13);
  4378. x10 ^= rotl(x09 + x08 | 0, 18);
  4379. x12 ^= rotl(x15 + x14 | 0, 7);
  4380. x13 ^= rotl(x12 + x15 | 0, 9);
  4381. x14 ^= rotl(x13 + x12 | 0, 13);
  4382. x15 ^= rotl(x14 + x13 | 0, 18);
  4383. }
  4384. // Write output (salsa)
  4385. out[oi++] = (y00 + x00) | 0;
  4386. out[oi++] = (y01 + x01) | 0;
  4387. out[oi++] = (y02 + x02) | 0;
  4388. out[oi++] = (y03 + x03) | 0;
  4389. out[oi++] = (y04 + x04) | 0;
  4390. out[oi++] = (y05 + x05) | 0;
  4391. out[oi++] = (y06 + x06) | 0;
  4392. out[oi++] = (y07 + x07) | 0;
  4393. out[oi++] = (y08 + x08) | 0;
  4394. out[oi++] = (y09 + x09) | 0;
  4395. out[oi++] = (y10 + x10) | 0;
  4396. out[oi++] = (y11 + x11) | 0;
  4397. out[oi++] = (y12 + x12) | 0;
  4398. out[oi++] = (y13 + x13) | 0;
  4399. out[oi++] = (y14 + x14) | 0;
  4400. out[oi++] = (y15 + x15) | 0;
  4401. }
  4402. function BlockMix(input, ii, out, oi, r) {
  4403. // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks)
  4404. let head = oi + 0;
  4405. let tail = oi + 16 * r;
  4406. for (let i = 0; i < 16; i++)
  4407. out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1]
  4408. for (let i = 0; i < r; i++, head += 16, ii += 16) {
  4409. // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1
  4410. XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1])
  4411. if (i > 0)
  4412. tail += 16; // First iteration overwrites tmp value in tail
  4413. XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i])
  4414. }
  4415. }
  4416. // Common prologue and epilogue for sync/async functions
  4417. function scryptInit(password, salt, _opts) {
  4418. // Maxmem - 1GB+1KB by default
  4419. const opts = checkOpts({
  4420. dkLen: 32,
  4421. asyncTick: 10,
  4422. maxmem: 1024 ** 3 + 1024,
  4423. }, _opts);
  4424. const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts;
  4425. number(N);
  4426. number(r);
  4427. number(p);
  4428. number(dkLen);
  4429. number(asyncTick);
  4430. number(maxmem);
  4431. if (onProgress !== undefined && typeof onProgress !== 'function')
  4432. throw new Error('progressCb should be function');
  4433. const blockSize = 128 * r;
  4434. const blockSize32 = blockSize / 4;
  4435. if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) {
  4436. // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function
  4437. // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future.
  4438. throw new Error('Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32');
  4439. }
  4440. if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) {
  4441. throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)');
  4442. }
  4443. if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) {
  4444. throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32');
  4445. }
  4446. const memUsed = blockSize * (N + p);
  4447. if (memUsed > maxmem) {
  4448. throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`);
  4449. }
  4450. // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor)
  4451. // Since it has only one iteration there is no reason to use async variant
  4452. const B = pbkdf2$1(sha256$1, password, salt, { c: 1, dkLen: blockSize * p });
  4453. const B32 = u32(B);
  4454. // Re-used between parallel iterations. Array(iterations) of B
  4455. const V = u32(new Uint8Array(blockSize * N));
  4456. const tmp = u32(new Uint8Array(blockSize));
  4457. let blockMixCb = () => { };
  4458. if (onProgress) {
  4459. const totalBlockMix = 2 * N * p;
  4460. // Invoke callback if progress changes from 10.01 to 10.02
  4461. // Allows to draw smooth progress bar on up to 8K screen
  4462. const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1);
  4463. let blockMixCnt = 0;
  4464. blockMixCb = () => {
  4465. blockMixCnt++;
  4466. if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix))
  4467. onProgress(blockMixCnt / totalBlockMix);
  4468. };
  4469. }
  4470. return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick };
  4471. }
  4472. function scryptOutput(password, dkLen, B, V, tmp) {
  4473. const res = pbkdf2$1(sha256$1, password, B, { c: 1, dkLen });
  4474. B.fill(0);
  4475. V.fill(0);
  4476. tmp.fill(0);
  4477. return res;
  4478. }
  4479. /**
  4480. * Scrypt KDF from RFC 7914.
  4481. * @param password - pass
  4482. * @param salt - salt
  4483. * @param opts - parameters
  4484. * - `N` is cpu/mem work factor (power of 2 e.g. 2**18)
  4485. * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance
  4486. * - `p` is parallelization factor (1 is common)
  4487. * - `dkLen` is output key length in bytes e.g. 32.
  4488. * - `asyncTick` - (default: 10) max time in ms for which async function can block execution
  4489. * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt
  4490. * - `onProgress` - callback function that would be executed for progress report
  4491. * @returns Derived key
  4492. */
  4493. function scrypt$1(password, salt, opts) {
  4494. const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts);
  4495. for (let pi = 0; pi < p; pi++) {
  4496. const Pi = blockSize32 * pi;
  4497. for (let i = 0; i < blockSize32; i++)
  4498. V[i] = B32[Pi + i]; // V[0] = B[i]
  4499. for (let i = 0, pos = 0; i < N - 1; i++) {
  4500. BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);
  4501. blockMixCb();
  4502. }
  4503. BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element
  4504. blockMixCb();
  4505. for (let i = 0; i < N; i++) {
  4506. // First u32 of the last 64-byte block (u32 is LE)
  4507. const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations
  4508. for (let k = 0; k < blockSize32; k++)
  4509. tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]
  4510. BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])
  4511. blockMixCb();
  4512. }
  4513. }
  4514. return scryptOutput(password, dkLen, B, V, tmp);
  4515. }
  4516. /**
  4517. * Scrypt KDF from RFC 7914.
  4518. */
  4519. async function scryptAsync(password, salt, opts) {
  4520. const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts);
  4521. for (let pi = 0; pi < p; pi++) {
  4522. const Pi = blockSize32 * pi;
  4523. for (let i = 0; i < blockSize32; i++)
  4524. V[i] = B32[Pi + i]; // V[0] = B[i]
  4525. let pos = 0;
  4526. await asyncLoop(N - 1, asyncTick, () => {
  4527. BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);
  4528. blockMixCb();
  4529. });
  4530. BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element
  4531. blockMixCb();
  4532. await asyncLoop(N, asyncTick, () => {
  4533. // First u32 of the last 64-byte block (u32 is LE)
  4534. const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations
  4535. for (let k = 0; k < blockSize32; k++)
  4536. tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]
  4537. BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])
  4538. blockMixCb();
  4539. });
  4540. }
  4541. return scryptOutput(password, dkLen, B, V, tmp);
  4542. }
  4543. let lockedSync = false, lockedAsync = false;
  4544. const _scryptAsync = async function (passwd, salt, N, r, p, dkLen, onProgress) {
  4545. return await scryptAsync(passwd, salt, { N, r, p, dkLen, onProgress });
  4546. };
  4547. const _scryptSync = function (passwd, salt, N, r, p, dkLen) {
  4548. return scrypt$1(passwd, salt, { N, r, p, dkLen });
  4549. };
  4550. let __scryptAsync = _scryptAsync;
  4551. let __scryptSync = _scryptSync;
  4552. /**
  4553. * The [[link-wiki-scrypt]] uses a memory and cpu hard method of
  4554. * derivation to increase the resource cost to brute-force a password
  4555. * for a given key.
  4556. *
  4557. * This means this algorithm is intentionally slow, and can be tuned to
  4558. * become slower. As computation and memory speed improve over time,
  4559. * increasing the difficulty maintains the cost of an attacker.
  4560. *
  4561. * For example, if a target time of 5 seconds is used, a legitimate user
  4562. * which knows their password requires only 5 seconds to unlock their
  4563. * account. A 6 character password has 68 billion possibilities, which
  4564. * would require an attacker to invest over 10,000 years of CPU time. This
  4565. * is of course a crude example (as password generally aren't random),
  4566. * but demonstrates to value of imposing large costs to decryption.
  4567. *
  4568. * For this reason, if building a UI which involved decrypting or
  4569. * encrypting datsa using scrypt, it is recommended to use a
  4570. * [[ProgressCallback]] (as event short periods can seem lik an eternity
  4571. * if the UI freezes). Including the phrase //"decrypting"// in the UI
  4572. * can also help, assuring the user their waiting is for a good reason.
  4573. *
  4574. * @_docloc: api/crypto:Passwords
  4575. *
  4576. * @example:
  4577. * // The password must be converted to bytes, and it is generally
  4578. * // best practices to ensure the string has been normalized. Many
  4579. * // formats explicitly indicate the normalization form to use.
  4580. * password = "hello"
  4581. * passwordBytes = toUtf8Bytes(password, "NFKC")
  4582. *
  4583. * salt = id("some-salt")
  4584. *
  4585. * // Compute the scrypt
  4586. * scrypt(passwordBytes, salt, 1024, 8, 1, 16)
  4587. * //_result:
  4588. */
  4589. async function scrypt(_passwd, _salt, N, r, p, dkLen, progress) {
  4590. const passwd = getBytes(_passwd, "passwd");
  4591. const salt = getBytes(_salt, "salt");
  4592. return hexlify(await __scryptAsync(passwd, salt, N, r, p, dkLen, progress));
  4593. }
  4594. scrypt._ = _scryptAsync;
  4595. scrypt.lock = function () { lockedAsync = true; };
  4596. scrypt.register = function (func) {
  4597. if (lockedAsync) {
  4598. throw new Error("scrypt is locked");
  4599. }
  4600. __scryptAsync = func;
  4601. };
  4602. Object.freeze(scrypt);
  4603. /**
  4604. * Provides a synchronous variant of [[scrypt]].
  4605. *
  4606. * This will completely lock up and freeze the UI in a browser and will
  4607. * prevent any event loop from progressing. For this reason, it is
  4608. * preferred to use the [async variant](scrypt).
  4609. *
  4610. * @_docloc: api/crypto:Passwords
  4611. *
  4612. * @example:
  4613. * // The password must be converted to bytes, and it is generally
  4614. * // best practices to ensure the string has been normalized. Many
  4615. * // formats explicitly indicate the normalization form to use.
  4616. * password = "hello"
  4617. * passwordBytes = toUtf8Bytes(password, "NFKC")
  4618. *
  4619. * salt = id("some-salt")
  4620. *
  4621. * // Compute the scrypt
  4622. * scryptSync(passwordBytes, salt, 1024, 8, 1, 16)
  4623. * //_result:
  4624. */
  4625. function scryptSync(_passwd, _salt, N, r, p, dkLen) {
  4626. const passwd = getBytes(_passwd, "passwd");
  4627. const salt = getBytes(_salt, "salt");
  4628. return hexlify(__scryptSync(passwd, salt, N, r, p, dkLen));
  4629. }
  4630. scryptSync._ = _scryptSync;
  4631. scryptSync.lock = function () { lockedSync = true; };
  4632. scryptSync.register = function (func) {
  4633. if (lockedSync) {
  4634. throw new Error("scryptSync is locked");
  4635. }
  4636. __scryptSync = func;
  4637. };
  4638. Object.freeze(scryptSync);
  4639. const _sha256 = function (data) {
  4640. return createHash("sha256").update(data).digest();
  4641. };
  4642. const _sha512 = function (data) {
  4643. return createHash("sha512").update(data).digest();
  4644. };
  4645. let __sha256 = _sha256;
  4646. let __sha512 = _sha512;
  4647. let locked256 = false, locked512 = false;
  4648. /**
  4649. * Compute the cryptographic SHA2-256 hash of %%data%%.
  4650. *
  4651. * @_docloc: api/crypto:Hash Functions
  4652. * @returns DataHexstring
  4653. *
  4654. * @example:
  4655. * sha256("0x")
  4656. * //_result:
  4657. *
  4658. * sha256("0x1337")
  4659. * //_result:
  4660. *
  4661. * sha256(new Uint8Array([ 0x13, 0x37 ]))
  4662. * //_result:
  4663. *
  4664. */
  4665. function sha256(_data) {
  4666. const data = getBytes(_data, "data");
  4667. return hexlify(__sha256(data));
  4668. }
  4669. sha256._ = _sha256;
  4670. sha256.lock = function () { locked256 = true; };
  4671. sha256.register = function (func) {
  4672. if (locked256) {
  4673. throw new Error("sha256 is locked");
  4674. }
  4675. __sha256 = func;
  4676. };
  4677. Object.freeze(sha256);
  4678. /**
  4679. * Compute the cryptographic SHA2-512 hash of %%data%%.
  4680. *
  4681. * @_docloc: api/crypto:Hash Functions
  4682. * @returns DataHexstring
  4683. *
  4684. * @example:
  4685. * sha512("0x")
  4686. * //_result:
  4687. *
  4688. * sha512("0x1337")
  4689. * //_result:
  4690. *
  4691. * sha512(new Uint8Array([ 0x13, 0x37 ]))
  4692. * //_result:
  4693. */
  4694. function sha512(_data) {
  4695. const data = getBytes(_data, "data");
  4696. return hexlify(__sha512(data));
  4697. }
  4698. sha512._ = _sha512;
  4699. sha512.lock = function () { locked512 = true; };
  4700. sha512.register = function (func) {
  4701. if (locked512) {
  4702. throw new Error("sha512 is locked");
  4703. }
  4704. __sha512 = func;
  4705. };
  4706. Object.freeze(sha256);
  4707. /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
  4708. // 100 lines of code in the file are duplicated from noble-hashes (utils).
  4709. // This is OK: `abstract` directory does not use noble-hashes.
  4710. // User may opt-in into using different hashing library. This way, noble-hashes
  4711. // won't be included into their bundle.
  4712. const _0n$3 = BigInt(0);
  4713. const _1n$4 = BigInt(1);
  4714. const _2n$2 = BigInt(2);
  4715. const u8a = (a) => a instanceof Uint8Array;
  4716. const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
  4717. /**
  4718. * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
  4719. */
  4720. function bytesToHex(bytes) {
  4721. if (!u8a(bytes))
  4722. throw new Error('Uint8Array expected');
  4723. // pre-caching improves the speed 6x
  4724. let hex = '';
  4725. for (let i = 0; i < bytes.length; i++) {
  4726. hex += hexes[bytes[i]];
  4727. }
  4728. return hex;
  4729. }
  4730. function numberToHexUnpadded(num) {
  4731. const hex = num.toString(16);
  4732. return hex.length & 1 ? `0${hex}` : hex;
  4733. }
  4734. function hexToNumber(hex) {
  4735. if (typeof hex !== 'string')
  4736. throw new Error('hex string expected, got ' + typeof hex);
  4737. // Big Endian
  4738. return BigInt(hex === '' ? '0' : `0x${hex}`);
  4739. }
  4740. /**
  4741. * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
  4742. */
  4743. function hexToBytes(hex) {
  4744. if (typeof hex !== 'string')
  4745. throw new Error('hex string expected, got ' + typeof hex);
  4746. const len = hex.length;
  4747. if (len % 2)
  4748. throw new Error('padded hex string expected, got unpadded hex of length ' + len);
  4749. const array = new Uint8Array(len / 2);
  4750. for (let i = 0; i < array.length; i++) {
  4751. const j = i * 2;
  4752. const hexByte = hex.slice(j, j + 2);
  4753. const byte = Number.parseInt(hexByte, 16);
  4754. if (Number.isNaN(byte) || byte < 0)
  4755. throw new Error('Invalid byte sequence');
  4756. array[i] = byte;
  4757. }
  4758. return array;
  4759. }
  4760. // BE: Big Endian, LE: Little Endian
  4761. function bytesToNumberBE(bytes) {
  4762. return hexToNumber(bytesToHex(bytes));
  4763. }
  4764. function bytesToNumberLE(bytes) {
  4765. if (!u8a(bytes))
  4766. throw new Error('Uint8Array expected');
  4767. return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
  4768. }
  4769. function numberToBytesBE(n, len) {
  4770. return hexToBytes(n.toString(16).padStart(len * 2, '0'));
  4771. }
  4772. function numberToBytesLE(n, len) {
  4773. return numberToBytesBE(n, len).reverse();
  4774. }
  4775. // Unpadded, rarely used
  4776. function numberToVarBytesBE(n) {
  4777. return hexToBytes(numberToHexUnpadded(n));
  4778. }
  4779. /**
  4780. * Takes hex string or Uint8Array, converts to Uint8Array.
  4781. * Validates output length.
  4782. * Will throw error for other types.
  4783. * @param title descriptive title for an error e.g. 'private key'
  4784. * @param hex hex string or Uint8Array
  4785. * @param expectedLength optional, will compare to result array's length
  4786. * @returns
  4787. */
  4788. function ensureBytes(title, hex, expectedLength) {
  4789. let res;
  4790. if (typeof hex === 'string') {
  4791. try {
  4792. res = hexToBytes(hex);
  4793. }
  4794. catch (e) {
  4795. throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`);
  4796. }
  4797. }
  4798. else if (u8a(hex)) {
  4799. // Uint8Array.from() instead of hash.slice() because node.js Buffer
  4800. // is instance of Uint8Array, and its slice() creates **mutable** copy
  4801. res = Uint8Array.from(hex);
  4802. }
  4803. else {
  4804. throw new Error(`${title} must be hex string or Uint8Array`);
  4805. }
  4806. const len = res.length;
  4807. if (typeof expectedLength === 'number' && len !== expectedLength)
  4808. throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
  4809. return res;
  4810. }
  4811. /**
  4812. * Copies several Uint8Arrays into one.
  4813. */
  4814. function concatBytes(...arrays) {
  4815. const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));
  4816. let pad = 0; // walk through each item, ensure they have proper type
  4817. arrays.forEach((a) => {
  4818. if (!u8a(a))
  4819. throw new Error('Uint8Array expected');
  4820. r.set(a, pad);
  4821. pad += a.length;
  4822. });
  4823. return r;
  4824. }
  4825. function equalBytes(b1, b2) {
  4826. // We don't care about timing attacks here
  4827. if (b1.length !== b2.length)
  4828. return false;
  4829. for (let i = 0; i < b1.length; i++)
  4830. if (b1[i] !== b2[i])
  4831. return false;
  4832. return true;
  4833. }
  4834. /**
  4835. * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
  4836. */
  4837. function utf8ToBytes(str) {
  4838. if (typeof str !== 'string')
  4839. throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
  4840. return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
  4841. }
  4842. // Bit operations
  4843. /**
  4844. * Calculates amount of bits in a bigint.
  4845. * Same as `n.toString(2).length`
  4846. */
  4847. function bitLen(n) {
  4848. let len;
  4849. for (len = 0; n > _0n$3; n >>= _1n$4, len += 1)
  4850. ;
  4851. return len;
  4852. }
  4853. /**
  4854. * Gets single bit at position.
  4855. * NOTE: first bit position is 0 (same as arrays)
  4856. * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
  4857. */
  4858. function bitGet(n, pos) {
  4859. return (n >> BigInt(pos)) & _1n$4;
  4860. }
  4861. /**
  4862. * Sets single bit at position.
  4863. */
  4864. const bitSet = (n, pos, value) => {
  4865. return n | ((value ? _1n$4 : _0n$3) << BigInt(pos));
  4866. };
  4867. /**
  4868. * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
  4869. * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
  4870. */
  4871. const bitMask = (n) => (_2n$2 << BigInt(n - 1)) - _1n$4;
  4872. // DRBG
  4873. const u8n = (data) => new Uint8Array(data); // creates Uint8Array
  4874. const u8fr = (arr) => Uint8Array.from(arr); // another shortcut
  4875. /**
  4876. * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
  4877. * @returns function that will call DRBG until 2nd arg returns something meaningful
  4878. * @example
  4879. * const drbg = createHmacDRBG<Key>(32, 32, hmac);
  4880. * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
  4881. */
  4882. function createHmacDrbg(hashLen, qByteLen, hmacFn) {
  4883. if (typeof hashLen !== 'number' || hashLen < 2)
  4884. throw new Error('hashLen must be a number');
  4885. if (typeof qByteLen !== 'number' || qByteLen < 2)
  4886. throw new Error('qByteLen must be a number');
  4887. if (typeof hmacFn !== 'function')
  4888. throw new Error('hmacFn must be a function');
  4889. // Step B, Step C: set hashLen to 8*ceil(hlen/8)
  4890. let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
  4891. let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
  4892. let i = 0; // Iterations counter, will throw when over 1000
  4893. const reset = () => {
  4894. v.fill(1);
  4895. k.fill(0);
  4896. i = 0;
  4897. };
  4898. const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
  4899. const reseed = (seed = u8n()) => {
  4900. // HMAC-DRBG reseed() function. Steps D-G
  4901. k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)
  4902. v = h(); // v = hmac(k || v)
  4903. if (seed.length === 0)
  4904. return;
  4905. k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)
  4906. v = h(); // v = hmac(k || v)
  4907. };
  4908. const gen = () => {
  4909. // HMAC-DRBG generate() function
  4910. if (i++ >= 1000)
  4911. throw new Error('drbg: tried 1000 values');
  4912. let len = 0;
  4913. const out = [];
  4914. while (len < qByteLen) {
  4915. v = h();
  4916. const sl = v.slice();
  4917. out.push(sl);
  4918. len += v.length;
  4919. }
  4920. return concatBytes(...out);
  4921. };
  4922. const genUntil = (seed, pred) => {
  4923. reset();
  4924. reseed(seed); // Steps D-G
  4925. let res = undefined; // Step H: grind until k is in [1..n-1]
  4926. while (!(res = pred(gen())))
  4927. reseed();
  4928. reset();
  4929. return res;
  4930. };
  4931. return genUntil;
  4932. }
  4933. // Validating curves and fields
  4934. const validatorFns = {
  4935. bigint: (val) => typeof val === 'bigint',
  4936. function: (val) => typeof val === 'function',
  4937. boolean: (val) => typeof val === 'boolean',
  4938. string: (val) => typeof val === 'string',
  4939. stringOrUint8Array: (val) => typeof val === 'string' || val instanceof Uint8Array,
  4940. isSafeInteger: (val) => Number.isSafeInteger(val),
  4941. array: (val) => Array.isArray(val),
  4942. field: (val, object) => object.Fp.isValid(val),
  4943. hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
  4944. };
  4945. // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
  4946. function validateObject(object, validators, optValidators = {}) {
  4947. const checkField = (fieldName, type, isOptional) => {
  4948. const checkVal = validatorFns[type];
  4949. if (typeof checkVal !== 'function')
  4950. throw new Error(`Invalid validator "${type}", expected function`);
  4951. const val = object[fieldName];
  4952. if (isOptional && val === undefined)
  4953. return;
  4954. if (!checkVal(val, object)) {
  4955. throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);
  4956. }
  4957. };
  4958. for (const [fieldName, type] of Object.entries(validators))
  4959. checkField(fieldName, type, false);
  4960. for (const [fieldName, type] of Object.entries(optValidators))
  4961. checkField(fieldName, type, true);
  4962. return object;
  4963. }
  4964. // validate type tests
  4965. // const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
  4966. // const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
  4967. // // Should fail type-check
  4968. // const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
  4969. // const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
  4970. // const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
  4971. // const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
  4972. var ut = /*#__PURE__*/Object.freeze({
  4973. __proto__: null,
  4974. bitGet: bitGet,
  4975. bitLen: bitLen,
  4976. bitMask: bitMask,
  4977. bitSet: bitSet,
  4978. bytesToHex: bytesToHex,
  4979. bytesToNumberBE: bytesToNumberBE,
  4980. bytesToNumberLE: bytesToNumberLE,
  4981. concatBytes: concatBytes,
  4982. createHmacDrbg: createHmacDrbg,
  4983. ensureBytes: ensureBytes,
  4984. equalBytes: equalBytes,
  4985. hexToBytes: hexToBytes,
  4986. hexToNumber: hexToNumber,
  4987. numberToBytesBE: numberToBytesBE,
  4988. numberToBytesLE: numberToBytesLE,
  4989. numberToHexUnpadded: numberToHexUnpadded,
  4990. numberToVarBytesBE: numberToVarBytesBE,
  4991. utf8ToBytes: utf8ToBytes,
  4992. validateObject: validateObject
  4993. });
  4994. /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
  4995. // Utilities for modular arithmetics and finite fields
  4996. // prettier-ignore
  4997. const _0n$2 = BigInt(0), _1n$3 = BigInt(1), _2n$1 = BigInt(2), _3n$1 = BigInt(3);
  4998. // prettier-ignore
  4999. const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);
  5000. // prettier-ignore
  5001. BigInt(9); BigInt(16);
  5002. // Calculates a modulo b
  5003. function mod(a, b) {
  5004. const result = a % b;
  5005. return result >= _0n$2 ? result : b + result;
  5006. }
  5007. /**
  5008. * Efficiently raise num to power and do modular division.
  5009. * Unsafe in some contexts: uses ladder, so can expose bigint bits.
  5010. * @example
  5011. * pow(2n, 6n, 11n) // 64n % 11n == 9n
  5012. */
  5013. // TODO: use field version && remove
  5014. function pow(num, power, modulo) {
  5015. if (modulo <= _0n$2 || power < _0n$2)
  5016. throw new Error('Expected power/modulo > 0');
  5017. if (modulo === _1n$3)
  5018. return _0n$2;
  5019. let res = _1n$3;
  5020. while (power > _0n$2) {
  5021. if (power & _1n$3)
  5022. res = (res * num) % modulo;
  5023. num = (num * num) % modulo;
  5024. power >>= _1n$3;
  5025. }
  5026. return res;
  5027. }
  5028. // Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)
  5029. function pow2(x, power, modulo) {
  5030. let res = x;
  5031. while (power-- > _0n$2) {
  5032. res *= res;
  5033. res %= modulo;
  5034. }
  5035. return res;
  5036. }
  5037. // Inverses number over modulo
  5038. function invert(number, modulo) {
  5039. if (number === _0n$2 || modulo <= _0n$2) {
  5040. throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
  5041. }
  5042. // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/
  5043. // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
  5044. let a = mod(number, modulo);
  5045. let b = modulo;
  5046. // prettier-ignore
  5047. let x = _0n$2, u = _1n$3;
  5048. while (a !== _0n$2) {
  5049. // JIT applies optimization if those two lines follow each other
  5050. const q = b / a;
  5051. const r = b % a;
  5052. const m = x - u * q;
  5053. // prettier-ignore
  5054. b = a, a = r, x = u, u = m;
  5055. }
  5056. const gcd = b;
  5057. if (gcd !== _1n$3)
  5058. throw new Error('invert: does not exist');
  5059. return mod(x, modulo);
  5060. }
  5061. /**
  5062. * Tonelli-Shanks square root search algorithm.
  5063. * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
  5064. * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
  5065. * Will start an infinite loop if field order P is not prime.
  5066. * @param P field order
  5067. * @returns function that takes field Fp (created from P) and number n
  5068. */
  5069. function tonelliShanks(P) {
  5070. // Legendre constant: used to calculate Legendre symbol (a | p),
  5071. // which denotes the value of a^((p-1)/2) (mod p).
  5072. // (a | p) ≡ 1 if a is a square (mod p)
  5073. // (a | p) ≡ -1 if a is not a square (mod p)
  5074. // (a | p) ≡ 0 if a ≡ 0 (mod p)
  5075. const legendreC = (P - _1n$3) / _2n$1;
  5076. let Q, S, Z;
  5077. // Step 1: By factoring out powers of 2 from p - 1,
  5078. // find q and s such that p - 1 = q*(2^s) with q odd
  5079. for (Q = P - _1n$3, S = 0; Q % _2n$1 === _0n$2; Q /= _2n$1, S++)
  5080. ;
  5081. // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq
  5082. for (Z = _2n$1; Z < P && pow(Z, legendreC, P) !== P - _1n$3; Z++)
  5083. ;
  5084. // Fast-path
  5085. if (S === 1) {
  5086. const p1div4 = (P + _1n$3) / _4n;
  5087. return function tonelliFast(Fp, n) {
  5088. const root = Fp.pow(n, p1div4);
  5089. if (!Fp.eql(Fp.sqr(root), n))
  5090. throw new Error('Cannot find square root');
  5091. return root;
  5092. };
  5093. }
  5094. // Slow-path
  5095. const Q1div2 = (Q + _1n$3) / _2n$1;
  5096. return function tonelliSlow(Fp, n) {
  5097. // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1
  5098. if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))
  5099. throw new Error('Cannot find square root');
  5100. let r = S;
  5101. // TODO: will fail at Fp2/etc
  5102. let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b
  5103. let x = Fp.pow(n, Q1div2); // first guess at the square root
  5104. let b = Fp.pow(n, Q); // first guess at the fudge factor
  5105. while (!Fp.eql(b, Fp.ONE)) {
  5106. if (Fp.eql(b, Fp.ZERO))
  5107. return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)
  5108. // Find m such b^(2^m)==1
  5109. let m = 1;
  5110. for (let t2 = Fp.sqr(b); m < r; m++) {
  5111. if (Fp.eql(t2, Fp.ONE))
  5112. break;
  5113. t2 = Fp.sqr(t2); // t2 *= t2
  5114. }
  5115. // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow
  5116. const ge = Fp.pow(g, _1n$3 << BigInt(r - m - 1)); // ge = 2^(r-m-1)
  5117. g = Fp.sqr(ge); // g = ge * ge
  5118. x = Fp.mul(x, ge); // x *= ge
  5119. b = Fp.mul(b, g); // b *= g
  5120. r = m;
  5121. }
  5122. return x;
  5123. };
  5124. }
  5125. function FpSqrt(P) {
  5126. // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.
  5127. // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
  5128. // P ≡ 3 (mod 4)
  5129. // √n = n^((P+1)/4)
  5130. if (P % _4n === _3n$1) {
  5131. // Not all roots possible!
  5132. // const ORDER =
  5133. // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;
  5134. // const NUM = 72057594037927816n;
  5135. const p1div4 = (P + _1n$3) / _4n;
  5136. return function sqrt3mod4(Fp, n) {
  5137. const root = Fp.pow(n, p1div4);
  5138. // Throw if root**2 != n
  5139. if (!Fp.eql(Fp.sqr(root), n))
  5140. throw new Error('Cannot find square root');
  5141. return root;
  5142. };
  5143. }
  5144. // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)
  5145. if (P % _8n === _5n) {
  5146. const c1 = (P - _5n) / _8n;
  5147. return function sqrt5mod8(Fp, n) {
  5148. const n2 = Fp.mul(n, _2n$1);
  5149. const v = Fp.pow(n2, c1);
  5150. const nv = Fp.mul(n, v);
  5151. const i = Fp.mul(Fp.mul(nv, _2n$1), v);
  5152. const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
  5153. if (!Fp.eql(Fp.sqr(root), n))
  5154. throw new Error('Cannot find square root');
  5155. return root;
  5156. };
  5157. }
  5158. // Other cases: Tonelli-Shanks algorithm
  5159. return tonelliShanks(P);
  5160. }
  5161. // prettier-ignore
  5162. const FIELD_FIELDS = [
  5163. 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
  5164. 'eql', 'add', 'sub', 'mul', 'pow', 'div',
  5165. 'addN', 'subN', 'mulN', 'sqrN'
  5166. ];
  5167. function validateField(field) {
  5168. const initial = {
  5169. ORDER: 'bigint',
  5170. MASK: 'bigint',
  5171. BYTES: 'isSafeInteger',
  5172. BITS: 'isSafeInteger',
  5173. };
  5174. const opts = FIELD_FIELDS.reduce((map, val) => {
  5175. map[val] = 'function';
  5176. return map;
  5177. }, initial);
  5178. return validateObject(field, opts);
  5179. }
  5180. // Generic field functions
  5181. /**
  5182. * Same as `pow` but for Fp: non-constant-time.
  5183. * Unsafe in some contexts: uses ladder, so can expose bigint bits.
  5184. */
  5185. function FpPow(f, num, power) {
  5186. // Should have same speed as pow for bigints
  5187. // TODO: benchmark!
  5188. if (power < _0n$2)
  5189. throw new Error('Expected power > 0');
  5190. if (power === _0n$2)
  5191. return f.ONE;
  5192. if (power === _1n$3)
  5193. return num;
  5194. let p = f.ONE;
  5195. let d = num;
  5196. while (power > _0n$2) {
  5197. if (power & _1n$3)
  5198. p = f.mul(p, d);
  5199. d = f.sqr(d);
  5200. power >>= _1n$3;
  5201. }
  5202. return p;
  5203. }
  5204. /**
  5205. * Efficiently invert an array of Field elements.
  5206. * `inv(0)` will return `undefined` here: make sure to throw an error.
  5207. */
  5208. function FpInvertBatch(f, nums) {
  5209. const tmp = new Array(nums.length);
  5210. // Walk from first to last, multiply them by each other MOD p
  5211. const lastMultiplied = nums.reduce((acc, num, i) => {
  5212. if (f.is0(num))
  5213. return acc;
  5214. tmp[i] = acc;
  5215. return f.mul(acc, num);
  5216. }, f.ONE);
  5217. // Invert last element
  5218. const inverted = f.inv(lastMultiplied);
  5219. // Walk from last to first, multiply them by inverted each other MOD p
  5220. nums.reduceRight((acc, num, i) => {
  5221. if (f.is0(num))
  5222. return acc;
  5223. tmp[i] = f.mul(acc, tmp[i]);
  5224. return f.mul(acc, num);
  5225. }, inverted);
  5226. return tmp;
  5227. }
  5228. // CURVE.n lengths
  5229. function nLength(n, nBitLength) {
  5230. // Bit size, byte size of CURVE.n
  5231. const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
  5232. const nByteLength = Math.ceil(_nBitLength / 8);
  5233. return { nBitLength: _nBitLength, nByteLength };
  5234. }
  5235. /**
  5236. * Initializes a finite field over prime. **Non-primes are not supported.**
  5237. * Do not init in loop: slow. Very fragile: always run a benchmark on a change.
  5238. * Major performance optimizations:
  5239. * * a) denormalized operations like mulN instead of mul
  5240. * * b) same object shape: never add or remove keys
  5241. * * c) Object.freeze
  5242. * @param ORDER prime positive bigint
  5243. * @param bitLen how many bits the field consumes
  5244. * @param isLE (def: false) if encoding / decoding should be in little-endian
  5245. * @param redef optional faster redefinitions of sqrt and other methods
  5246. */
  5247. function Field(ORDER, bitLen, isLE = false, redef = {}) {
  5248. if (ORDER <= _0n$2)
  5249. throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);
  5250. const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);
  5251. if (BYTES > 2048)
  5252. throw new Error('Field lengths over 2048 bytes are not supported');
  5253. const sqrtP = FpSqrt(ORDER);
  5254. const f = Object.freeze({
  5255. ORDER,
  5256. BITS,
  5257. BYTES,
  5258. MASK: bitMask(BITS),
  5259. ZERO: _0n$2,
  5260. ONE: _1n$3,
  5261. create: (num) => mod(num, ORDER),
  5262. isValid: (num) => {
  5263. if (typeof num !== 'bigint')
  5264. throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
  5265. return _0n$2 <= num && num < ORDER; // 0 is valid element, but it's not invertible
  5266. },
  5267. is0: (num) => num === _0n$2,
  5268. isOdd: (num) => (num & _1n$3) === _1n$3,
  5269. neg: (num) => mod(-num, ORDER),
  5270. eql: (lhs, rhs) => lhs === rhs,
  5271. sqr: (num) => mod(num * num, ORDER),
  5272. add: (lhs, rhs) => mod(lhs + rhs, ORDER),
  5273. sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
  5274. mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
  5275. pow: (num, power) => FpPow(f, num, power),
  5276. div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
  5277. // Same as above, but doesn't normalize
  5278. sqrN: (num) => num * num,
  5279. addN: (lhs, rhs) => lhs + rhs,
  5280. subN: (lhs, rhs) => lhs - rhs,
  5281. mulN: (lhs, rhs) => lhs * rhs,
  5282. inv: (num) => invert(num, ORDER),
  5283. sqrt: redef.sqrt || ((n) => sqrtP(f, n)),
  5284. invertBatch: (lst) => FpInvertBatch(f, lst),
  5285. // TODO: do we really need constant cmov?
  5286. // We don't have const-time bigints anyway, so probably will be not very useful
  5287. cmov: (a, b, c) => (c ? b : a),
  5288. toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
  5289. fromBytes: (bytes) => {
  5290. if (bytes.length !== BYTES)
  5291. throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);
  5292. return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
  5293. },
  5294. });
  5295. return Object.freeze(f);
  5296. }
  5297. /**
  5298. * Returns total number of bytes consumed by the field element.
  5299. * For example, 32 bytes for usual 256-bit weierstrass curve.
  5300. * @param fieldOrder number of field elements, usually CURVE.n
  5301. * @returns byte length of field
  5302. */
  5303. function getFieldBytesLength(fieldOrder) {
  5304. if (typeof fieldOrder !== 'bigint')
  5305. throw new Error('field order must be bigint');
  5306. const bitLength = fieldOrder.toString(2).length;
  5307. return Math.ceil(bitLength / 8);
  5308. }
  5309. /**
  5310. * Returns minimal amount of bytes that can be safely reduced
  5311. * by field order.
  5312. * Should be 2^-128 for 128-bit curve such as P256.
  5313. * @param fieldOrder number of field elements, usually CURVE.n
  5314. * @returns byte length of target hash
  5315. */
  5316. function getMinHashLength(fieldOrder) {
  5317. const length = getFieldBytesLength(fieldOrder);
  5318. return length + Math.ceil(length / 2);
  5319. }
  5320. /**
  5321. * "Constant-time" private key generation utility.
  5322. * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
  5323. * and convert them into private scalar, with the modulo bias being negligible.
  5324. * Needs at least 48 bytes of input for 32-byte private key.
  5325. * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
  5326. * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
  5327. * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
  5328. * @param hash hash output from SHA3 or a similar function
  5329. * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
  5330. * @param isLE interpret hash bytes as LE num
  5331. * @returns valid private scalar
  5332. */
  5333. function mapHashToField(key, fieldOrder, isLE = false) {
  5334. const len = key.length;
  5335. const fieldLen = getFieldBytesLength(fieldOrder);
  5336. const minLen = getMinHashLength(fieldOrder);
  5337. // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
  5338. if (len < 16 || len < minLen || len > 1024)
  5339. throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);
  5340. const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);
  5341. // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
  5342. const reduced = mod(num, fieldOrder - _1n$3) + _1n$3;
  5343. return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
  5344. }
  5345. /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
  5346. // Abelian group utilities
  5347. const _0n$1 = BigInt(0);
  5348. const _1n$2 = BigInt(1);
  5349. // Elliptic curve multiplication of Point by scalar. Fragile.
  5350. // Scalars should always be less than curve order: this should be checked inside of a curve itself.
  5351. // Creates precomputation tables for fast multiplication:
  5352. // - private scalar is split by fixed size windows of W bits
  5353. // - every window point is collected from window's table & added to accumulator
  5354. // - since windows are different, same point inside tables won't be accessed more than once per calc
  5355. // - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
  5356. // - +1 window is neccessary for wNAF
  5357. // - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
  5358. // TODO: Research returning 2d JS array of windows, instead of a single window. This would allow
  5359. // windows to be in different memory locations
  5360. function wNAF(c, bits) {
  5361. const constTimeNegate = (condition, item) => {
  5362. const neg = item.negate();
  5363. return condition ? neg : item;
  5364. };
  5365. const opts = (W) => {
  5366. const windows = Math.ceil(bits / W) + 1; // +1, because
  5367. const windowSize = 2 ** (W - 1); // -1 because we skip zero
  5368. return { windows, windowSize };
  5369. };
  5370. return {
  5371. constTimeNegate,
  5372. // non-const time multiplication ladder
  5373. unsafeLadder(elm, n) {
  5374. let p = c.ZERO;
  5375. let d = elm;
  5376. while (n > _0n$1) {
  5377. if (n & _1n$2)
  5378. p = p.add(d);
  5379. d = d.double();
  5380. n >>= _1n$2;
  5381. }
  5382. return p;
  5383. },
  5384. /**
  5385. * Creates a wNAF precomputation window. Used for caching.
  5386. * Default window size is set by `utils.precompute()` and is equal to 8.
  5387. * Number of precomputed points depends on the curve size:
  5388. * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
  5389. * - 𝑊 is the window size
  5390. * - 𝑛 is the bitlength of the curve order.
  5391. * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
  5392. * @returns precomputed point tables flattened to a single array
  5393. */
  5394. precomputeWindow(elm, W) {
  5395. const { windows, windowSize } = opts(W);
  5396. const points = [];
  5397. let p = elm;
  5398. let base = p;
  5399. for (let window = 0; window < windows; window++) {
  5400. base = p;
  5401. points.push(base);
  5402. // =1, because we skip zero
  5403. for (let i = 1; i < windowSize; i++) {
  5404. base = base.add(p);
  5405. points.push(base);
  5406. }
  5407. p = base.double();
  5408. }
  5409. return points;
  5410. },
  5411. /**
  5412. * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
  5413. * @param W window size
  5414. * @param precomputes precomputed tables
  5415. * @param n scalar (we don't check here, but should be less than curve order)
  5416. * @returns real and fake (for const-time) points
  5417. */
  5418. wNAF(W, precomputes, n) {
  5419. // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise
  5420. // But need to carefully remove other checks before wNAF. ORDER == bits here
  5421. const { windows, windowSize } = opts(W);
  5422. let p = c.ZERO;
  5423. let f = c.BASE;
  5424. const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.
  5425. const maxNumber = 2 ** W;
  5426. const shiftBy = BigInt(W);
  5427. for (let window = 0; window < windows; window++) {
  5428. const offset = window * windowSize;
  5429. // Extract W bits.
  5430. let wbits = Number(n & mask);
  5431. // Shift number by W bits.
  5432. n >>= shiftBy;
  5433. // If the bits are bigger than max size, we'll split those.
  5434. // +224 => 256 - 32
  5435. if (wbits > windowSize) {
  5436. wbits -= maxNumber;
  5437. n += _1n$2;
  5438. }
  5439. // This code was first written with assumption that 'f' and 'p' will never be infinity point:
  5440. // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
  5441. // there is negate now: it is possible that negated element from low value
  5442. // would be the same as high element, which will create carry into next window.
  5443. // It's not obvious how this can fail, but still worth investigating later.
  5444. // Check if we're onto Zero point.
  5445. // Add random point inside current window to f.
  5446. const offset1 = offset;
  5447. const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero
  5448. const cond1 = window % 2 !== 0;
  5449. const cond2 = wbits < 0;
  5450. if (wbits === 0) {
  5451. // The most important part for const-time getPublicKey
  5452. f = f.add(constTimeNegate(cond1, precomputes[offset1]));
  5453. }
  5454. else {
  5455. p = p.add(constTimeNegate(cond2, precomputes[offset2]));
  5456. }
  5457. }
  5458. // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()
  5459. // Even if the variable is still unused, there are some checks which will
  5460. // throw an exception, so compiler needs to prove they won't happen, which is hard.
  5461. // At this point there is a way to F be infinity-point even if p is not,
  5462. // which makes it less const-time: around 1 bigint multiply.
  5463. return { p, f };
  5464. },
  5465. wNAFCached(P, precomputesMap, n, transform) {
  5466. // @ts-ignore
  5467. const W = P._WINDOW_SIZE || 1;
  5468. // Calculate precomputes on a first run, reuse them after
  5469. let comp = precomputesMap.get(P);
  5470. if (!comp) {
  5471. comp = this.precomputeWindow(P, W);
  5472. if (W !== 1) {
  5473. precomputesMap.set(P, transform(comp));
  5474. }
  5475. }
  5476. return this.wNAF(W, comp, n);
  5477. },
  5478. };
  5479. }
  5480. function validateBasic(curve) {
  5481. validateField(curve.Fp);
  5482. validateObject(curve, {
  5483. n: 'bigint',
  5484. h: 'bigint',
  5485. Gx: 'field',
  5486. Gy: 'field',
  5487. }, {
  5488. nBitLength: 'isSafeInteger',
  5489. nByteLength: 'isSafeInteger',
  5490. });
  5491. // Set defaults
  5492. return Object.freeze({
  5493. ...nLength(curve.n, curve.nBitLength),
  5494. ...curve,
  5495. ...{ p: curve.Fp.ORDER },
  5496. });
  5497. }
  5498. /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
  5499. // Short Weierstrass curve. The formula is: y² = x³ + ax + b
  5500. function validatePointOpts(curve) {
  5501. const opts = validateBasic(curve);
  5502. validateObject(opts, {
  5503. a: 'field',
  5504. b: 'field',
  5505. }, {
  5506. allowedPrivateKeyLengths: 'array',
  5507. wrapPrivateKey: 'boolean',
  5508. isTorsionFree: 'function',
  5509. clearCofactor: 'function',
  5510. allowInfinityPoint: 'boolean',
  5511. fromBytes: 'function',
  5512. toBytes: 'function',
  5513. });
  5514. const { endo, Fp, a } = opts;
  5515. if (endo) {
  5516. if (!Fp.eql(a, Fp.ZERO)) {
  5517. throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');
  5518. }
  5519. if (typeof endo !== 'object' ||
  5520. typeof endo.beta !== 'bigint' ||
  5521. typeof endo.splitScalar !== 'function') {
  5522. throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');
  5523. }
  5524. }
  5525. return Object.freeze({ ...opts });
  5526. }
  5527. // ASN.1 DER encoding utilities
  5528. const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
  5529. const DER = {
  5530. // asn.1 DER encoding utils
  5531. Err: class DERErr extends Error {
  5532. constructor(m = '') {
  5533. super(m);
  5534. }
  5535. },
  5536. _parseInt(data) {
  5537. const { Err: E } = DER;
  5538. if (data.length < 2 || data[0] !== 0x02)
  5539. throw new E('Invalid signature integer tag');
  5540. const len = data[1];
  5541. const res = data.subarray(2, len + 2);
  5542. if (!len || res.length !== len)
  5543. throw new E('Invalid signature integer: wrong length');
  5544. // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
  5545. // since we always use positive integers here. It must always be empty:
  5546. // - add zero byte if exists
  5547. // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
  5548. if (res[0] & 0b10000000)
  5549. throw new E('Invalid signature integer: negative');
  5550. if (res[0] === 0x00 && !(res[1] & 0b10000000))
  5551. throw new E('Invalid signature integer: unnecessary leading zero');
  5552. return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left
  5553. },
  5554. toSig(hex) {
  5555. // parse DER signature
  5556. const { Err: E } = DER;
  5557. const data = typeof hex === 'string' ? h2b(hex) : hex;
  5558. if (!(data instanceof Uint8Array))
  5559. throw new Error('ui8a expected');
  5560. let l = data.length;
  5561. if (l < 2 || data[0] != 0x30)
  5562. throw new E('Invalid signature tag');
  5563. if (data[1] !== l - 2)
  5564. throw new E('Invalid signature: incorrect length');
  5565. const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));
  5566. const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);
  5567. if (rBytesLeft.length)
  5568. throw new E('Invalid signature: left bytes after parsing');
  5569. return { r, s };
  5570. },
  5571. hexFromSig(sig) {
  5572. // Add leading zero if first byte has negative bit enabled. More details in '_parseInt'
  5573. const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s);
  5574. const h = (num) => {
  5575. const hex = num.toString(16);
  5576. return hex.length & 1 ? `0${hex}` : hex;
  5577. };
  5578. const s = slice(h(sig.s));
  5579. const r = slice(h(sig.r));
  5580. const shl = s.length / 2;
  5581. const rhl = r.length / 2;
  5582. const sl = h(shl);
  5583. const rl = h(rhl);
  5584. return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;
  5585. },
  5586. };
  5587. // Be friendly to bad ECMAScript parsers by not using bigint literals
  5588. // prettier-ignore
  5589. const _0n = BigInt(0), _1n$1 = BigInt(1); BigInt(2); const _3n = BigInt(3); BigInt(4);
  5590. function weierstrassPoints(opts) {
  5591. const CURVE = validatePointOpts(opts);
  5592. const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ
  5593. const toBytes = CURVE.toBytes ||
  5594. ((_c, point, _isCompressed) => {
  5595. const a = point.toAffine();
  5596. return concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));
  5597. });
  5598. const fromBytes = CURVE.fromBytes ||
  5599. ((bytes) => {
  5600. // const head = bytes[0];
  5601. const tail = bytes.subarray(1);
  5602. // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');
  5603. const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
  5604. const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
  5605. return { x, y };
  5606. });
  5607. /**
  5608. * y² = x³ + ax + b: Short weierstrass curve formula
  5609. * @returns y²
  5610. */
  5611. function weierstrassEquation(x) {
  5612. const { a, b } = CURVE;
  5613. const x2 = Fp.sqr(x); // x * x
  5614. const x3 = Fp.mul(x2, x); // x2 * x
  5615. return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b
  5616. }
  5617. // Validate whether the passed curve params are valid.
  5618. // We check if curve equation works for generator point.
  5619. // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.
  5620. // ProjectivePoint class has not been initialized yet.
  5621. if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))
  5622. throw new Error('bad generator point: equation left != right');
  5623. // Valid group elements reside in range 1..n-1
  5624. function isWithinCurveOrder(num) {
  5625. return typeof num === 'bigint' && _0n < num && num < CURVE.n;
  5626. }
  5627. function assertGE(num) {
  5628. if (!isWithinCurveOrder(num))
  5629. throw new Error('Expected valid bigint: 0 < bigint < curve.n');
  5630. }
  5631. // Validates if priv key is valid and converts it to bigint.
  5632. // Supports options allowedPrivateKeyLengths and wrapPrivateKey.
  5633. function normPrivateKeyToScalar(key) {
  5634. const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;
  5635. if (lengths && typeof key !== 'bigint') {
  5636. if (key instanceof Uint8Array)
  5637. key = bytesToHex(key);
  5638. // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes
  5639. if (typeof key !== 'string' || !lengths.includes(key.length))
  5640. throw new Error('Invalid key');
  5641. key = key.padStart(nByteLength * 2, '0');
  5642. }
  5643. let num;
  5644. try {
  5645. num =
  5646. typeof key === 'bigint'
  5647. ? key
  5648. : bytesToNumberBE(ensureBytes('private key', key, nByteLength));
  5649. }
  5650. catch (error) {
  5651. throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);
  5652. }
  5653. if (wrapPrivateKey)
  5654. num = mod(num, n); // disabled by default, enabled for BLS
  5655. assertGE(num); // num in range [1..N-1]
  5656. return num;
  5657. }
  5658. const pointPrecomputes = new Map();
  5659. function assertPrjPoint(other) {
  5660. if (!(other instanceof Point))
  5661. throw new Error('ProjectivePoint expected');
  5662. }
  5663. /**
  5664. * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)
  5665. * Default Point works in 2d / affine coordinates: (x, y)
  5666. * We're doing calculations in projective, because its operations don't require costly inversion.
  5667. */
  5668. class Point {
  5669. constructor(px, py, pz) {
  5670. this.px = px;
  5671. this.py = py;
  5672. this.pz = pz;
  5673. if (px == null || !Fp.isValid(px))
  5674. throw new Error('x required');
  5675. if (py == null || !Fp.isValid(py))
  5676. throw new Error('y required');
  5677. if (pz == null || !Fp.isValid(pz))
  5678. throw new Error('z required');
  5679. }
  5680. // Does not validate if the point is on-curve.
  5681. // Use fromHex instead, or call assertValidity() later.
  5682. static fromAffine(p) {
  5683. const { x, y } = p || {};
  5684. if (!p || !Fp.isValid(x) || !Fp.isValid(y))
  5685. throw new Error('invalid affine point');
  5686. if (p instanceof Point)
  5687. throw new Error('projective point not allowed');
  5688. const is0 = (i) => Fp.eql(i, Fp.ZERO);
  5689. // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)
  5690. if (is0(x) && is0(y))
  5691. return Point.ZERO;
  5692. return new Point(x, y, Fp.ONE);
  5693. }
  5694. get x() {
  5695. return this.toAffine().x;
  5696. }
  5697. get y() {
  5698. return this.toAffine().y;
  5699. }
  5700. /**
  5701. * Takes a bunch of Projective Points but executes only one
  5702. * inversion on all of them. Inversion is very slow operation,
  5703. * so this improves performance massively.
  5704. * Optimization: converts a list of projective points to a list of identical points with Z=1.
  5705. */
  5706. static normalizeZ(points) {
  5707. const toInv = Fp.invertBatch(points.map((p) => p.pz));
  5708. return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
  5709. }
  5710. /**
  5711. * Converts hash string or Uint8Array to Point.
  5712. * @param hex short/long ECDSA hex
  5713. */
  5714. static fromHex(hex) {
  5715. const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));
  5716. P.assertValidity();
  5717. return P;
  5718. }
  5719. // Multiplies generator point by privateKey.
  5720. static fromPrivateKey(privateKey) {
  5721. return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
  5722. }
  5723. // "Private method", don't use it directly
  5724. _setWindowSize(windowSize) {
  5725. this._WINDOW_SIZE = windowSize;
  5726. pointPrecomputes.delete(this);
  5727. }
  5728. // A point on curve is valid if it conforms to equation.
  5729. assertValidity() {
  5730. if (this.is0()) {
  5731. // (0, 1, 0) aka ZERO is invalid in most contexts.
  5732. // In BLS, ZERO can be serialized, so we allow it.
  5733. // (0, 0, 0) is wrong representation of ZERO and is always invalid.
  5734. if (CURVE.allowInfinityPoint && !Fp.is0(this.py))
  5735. return;
  5736. throw new Error('bad point: ZERO');
  5737. }
  5738. // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
  5739. const { x, y } = this.toAffine();
  5740. // Check if x, y are valid field elements
  5741. if (!Fp.isValid(x) || !Fp.isValid(y))
  5742. throw new Error('bad point: x or y not FE');
  5743. const left = Fp.sqr(y); // y²
  5744. const right = weierstrassEquation(x); // x³ + ax + b
  5745. if (!Fp.eql(left, right))
  5746. throw new Error('bad point: equation left != right');
  5747. if (!this.isTorsionFree())
  5748. throw new Error('bad point: not in prime-order subgroup');
  5749. }
  5750. hasEvenY() {
  5751. const { y } = this.toAffine();
  5752. if (Fp.isOdd)
  5753. return !Fp.isOdd(y);
  5754. throw new Error("Field doesn't support isOdd");
  5755. }
  5756. /**
  5757. * Compare one point to another.
  5758. */
  5759. equals(other) {
  5760. assertPrjPoint(other);
  5761. const { px: X1, py: Y1, pz: Z1 } = this;
  5762. const { px: X2, py: Y2, pz: Z2 } = other;
  5763. const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
  5764. const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
  5765. return U1 && U2;
  5766. }
  5767. /**
  5768. * Flips point to one corresponding to (x, -y) in Affine coordinates.
  5769. */
  5770. negate() {
  5771. return new Point(this.px, Fp.neg(this.py), this.pz);
  5772. }
  5773. // Renes-Costello-Batina exception-free doubling formula.
  5774. // There is 30% faster Jacobian formula, but it is not complete.
  5775. // https://eprint.iacr.org/2015/1060, algorithm 3
  5776. // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
  5777. double() {
  5778. const { a, b } = CURVE;
  5779. const b3 = Fp.mul(b, _3n);
  5780. const { px: X1, py: Y1, pz: Z1 } = this;
  5781. let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
  5782. let t0 = Fp.mul(X1, X1); // step 1
  5783. let t1 = Fp.mul(Y1, Y1);
  5784. let t2 = Fp.mul(Z1, Z1);
  5785. let t3 = Fp.mul(X1, Y1);
  5786. t3 = Fp.add(t3, t3); // step 5
  5787. Z3 = Fp.mul(X1, Z1);
  5788. Z3 = Fp.add(Z3, Z3);
  5789. X3 = Fp.mul(a, Z3);
  5790. Y3 = Fp.mul(b3, t2);
  5791. Y3 = Fp.add(X3, Y3); // step 10
  5792. X3 = Fp.sub(t1, Y3);
  5793. Y3 = Fp.add(t1, Y3);
  5794. Y3 = Fp.mul(X3, Y3);
  5795. X3 = Fp.mul(t3, X3);
  5796. Z3 = Fp.mul(b3, Z3); // step 15
  5797. t2 = Fp.mul(a, t2);
  5798. t3 = Fp.sub(t0, t2);
  5799. t3 = Fp.mul(a, t3);
  5800. t3 = Fp.add(t3, Z3);
  5801. Z3 = Fp.add(t0, t0); // step 20
  5802. t0 = Fp.add(Z3, t0);
  5803. t0 = Fp.add(t0, t2);
  5804. t0 = Fp.mul(t0, t3);
  5805. Y3 = Fp.add(Y3, t0);
  5806. t2 = Fp.mul(Y1, Z1); // step 25
  5807. t2 = Fp.add(t2, t2);
  5808. t0 = Fp.mul(t2, t3);
  5809. X3 = Fp.sub(X3, t0);
  5810. Z3 = Fp.mul(t2, t1);
  5811. Z3 = Fp.add(Z3, Z3); // step 30
  5812. Z3 = Fp.add(Z3, Z3);
  5813. return new Point(X3, Y3, Z3);
  5814. }
  5815. // Renes-Costello-Batina exception-free addition formula.
  5816. // There is 30% faster Jacobian formula, but it is not complete.
  5817. // https://eprint.iacr.org/2015/1060, algorithm 1
  5818. // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
  5819. add(other) {
  5820. assertPrjPoint(other);
  5821. const { px: X1, py: Y1, pz: Z1 } = this;
  5822. const { px: X2, py: Y2, pz: Z2 } = other;
  5823. let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
  5824. const a = CURVE.a;
  5825. const b3 = Fp.mul(CURVE.b, _3n);
  5826. let t0 = Fp.mul(X1, X2); // step 1
  5827. let t1 = Fp.mul(Y1, Y2);
  5828. let t2 = Fp.mul(Z1, Z2);
  5829. let t3 = Fp.add(X1, Y1);
  5830. let t4 = Fp.add(X2, Y2); // step 5
  5831. t3 = Fp.mul(t3, t4);
  5832. t4 = Fp.add(t0, t1);
  5833. t3 = Fp.sub(t3, t4);
  5834. t4 = Fp.add(X1, Z1);
  5835. let t5 = Fp.add(X2, Z2); // step 10
  5836. t4 = Fp.mul(t4, t5);
  5837. t5 = Fp.add(t0, t2);
  5838. t4 = Fp.sub(t4, t5);
  5839. t5 = Fp.add(Y1, Z1);
  5840. X3 = Fp.add(Y2, Z2); // step 15
  5841. t5 = Fp.mul(t5, X3);
  5842. X3 = Fp.add(t1, t2);
  5843. t5 = Fp.sub(t5, X3);
  5844. Z3 = Fp.mul(a, t4);
  5845. X3 = Fp.mul(b3, t2); // step 20
  5846. Z3 = Fp.add(X3, Z3);
  5847. X3 = Fp.sub(t1, Z3);
  5848. Z3 = Fp.add(t1, Z3);
  5849. Y3 = Fp.mul(X3, Z3);
  5850. t1 = Fp.add(t0, t0); // step 25
  5851. t1 = Fp.add(t1, t0);
  5852. t2 = Fp.mul(a, t2);
  5853. t4 = Fp.mul(b3, t4);
  5854. t1 = Fp.add(t1, t2);
  5855. t2 = Fp.sub(t0, t2); // step 30
  5856. t2 = Fp.mul(a, t2);
  5857. t4 = Fp.add(t4, t2);
  5858. t0 = Fp.mul(t1, t4);
  5859. Y3 = Fp.add(Y3, t0);
  5860. t0 = Fp.mul(t5, t4); // step 35
  5861. X3 = Fp.mul(t3, X3);
  5862. X3 = Fp.sub(X3, t0);
  5863. t0 = Fp.mul(t3, t1);
  5864. Z3 = Fp.mul(t5, Z3);
  5865. Z3 = Fp.add(Z3, t0); // step 40
  5866. return new Point(X3, Y3, Z3);
  5867. }
  5868. subtract(other) {
  5869. return this.add(other.negate());
  5870. }
  5871. is0() {
  5872. return this.equals(Point.ZERO);
  5873. }
  5874. wNAF(n) {
  5875. return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => {
  5876. const toInv = Fp.invertBatch(comp.map((p) => p.pz));
  5877. return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
  5878. });
  5879. }
  5880. /**
  5881. * Non-constant-time multiplication. Uses double-and-add algorithm.
  5882. * It's faster, but should only be used when you don't care about
  5883. * an exposed private key e.g. sig verification, which works over *public* keys.
  5884. */
  5885. multiplyUnsafe(n) {
  5886. const I = Point.ZERO;
  5887. if (n === _0n)
  5888. return I;
  5889. assertGE(n); // Will throw on 0
  5890. if (n === _1n$1)
  5891. return this;
  5892. const { endo } = CURVE;
  5893. if (!endo)
  5894. return wnaf.unsafeLadder(this, n);
  5895. // Apply endomorphism
  5896. let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
  5897. let k1p = I;
  5898. let k2p = I;
  5899. let d = this;
  5900. while (k1 > _0n || k2 > _0n) {
  5901. if (k1 & _1n$1)
  5902. k1p = k1p.add(d);
  5903. if (k2 & _1n$1)
  5904. k2p = k2p.add(d);
  5905. d = d.double();
  5906. k1 >>= _1n$1;
  5907. k2 >>= _1n$1;
  5908. }
  5909. if (k1neg)
  5910. k1p = k1p.negate();
  5911. if (k2neg)
  5912. k2p = k2p.negate();
  5913. k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
  5914. return k1p.add(k2p);
  5915. }
  5916. /**
  5917. * Constant time multiplication.
  5918. * Uses wNAF method. Windowed method may be 10% faster,
  5919. * but takes 2x longer to generate and consumes 2x memory.
  5920. * Uses precomputes when available.
  5921. * Uses endomorphism for Koblitz curves.
  5922. * @param scalar by which the point would be multiplied
  5923. * @returns New point
  5924. */
  5925. multiply(scalar) {
  5926. assertGE(scalar);
  5927. let n = scalar;
  5928. let point, fake; // Fake point is used to const-time mult
  5929. const { endo } = CURVE;
  5930. if (endo) {
  5931. const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
  5932. let { p: k1p, f: f1p } = this.wNAF(k1);
  5933. let { p: k2p, f: f2p } = this.wNAF(k2);
  5934. k1p = wnaf.constTimeNegate(k1neg, k1p);
  5935. k2p = wnaf.constTimeNegate(k2neg, k2p);
  5936. k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
  5937. point = k1p.add(k2p);
  5938. fake = f1p.add(f2p);
  5939. }
  5940. else {
  5941. const { p, f } = this.wNAF(n);
  5942. point = p;
  5943. fake = f;
  5944. }
  5945. // Normalize `z` for both points, but return only real one
  5946. return Point.normalizeZ([point, fake])[0];
  5947. }
  5948. /**
  5949. * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
  5950. * Not using Strauss-Shamir trick: precomputation tables are faster.
  5951. * The trick could be useful if both P and Q are not G (not in our case).
  5952. * @returns non-zero affine point
  5953. */
  5954. multiplyAndAddUnsafe(Q, a, b) {
  5955. const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes
  5956. const mul = (P, a // Select faster multiply() method
  5957. ) => (a === _0n || a === _1n$1 || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));
  5958. const sum = mul(this, a).add(mul(Q, b));
  5959. return sum.is0() ? undefined : sum;
  5960. }
  5961. // Converts Projective point to affine (x, y) coordinates.
  5962. // Can accept precomputed Z^-1 - for example, from invertBatch.
  5963. // (x, y, z) ∋ (x=x/z, y=y/z)
  5964. toAffine(iz) {
  5965. const { px: x, py: y, pz: z } = this;
  5966. const is0 = this.is0();
  5967. // If invZ was 0, we return zero point. However we still want to execute
  5968. // all operations, so we replace invZ with a random number, 1.
  5969. if (iz == null)
  5970. iz = is0 ? Fp.ONE : Fp.inv(z);
  5971. const ax = Fp.mul(x, iz);
  5972. const ay = Fp.mul(y, iz);
  5973. const zz = Fp.mul(z, iz);
  5974. if (is0)
  5975. return { x: Fp.ZERO, y: Fp.ZERO };
  5976. if (!Fp.eql(zz, Fp.ONE))
  5977. throw new Error('invZ was invalid');
  5978. return { x: ax, y: ay };
  5979. }
  5980. isTorsionFree() {
  5981. const { h: cofactor, isTorsionFree } = CURVE;
  5982. if (cofactor === _1n$1)
  5983. return true; // No subgroups, always torsion-free
  5984. if (isTorsionFree)
  5985. return isTorsionFree(Point, this);
  5986. throw new Error('isTorsionFree() has not been declared for the elliptic curve');
  5987. }
  5988. clearCofactor() {
  5989. const { h: cofactor, clearCofactor } = CURVE;
  5990. if (cofactor === _1n$1)
  5991. return this; // Fast-path
  5992. if (clearCofactor)
  5993. return clearCofactor(Point, this);
  5994. return this.multiplyUnsafe(CURVE.h);
  5995. }
  5996. toRawBytes(isCompressed = true) {
  5997. this.assertValidity();
  5998. return toBytes(Point, this, isCompressed);
  5999. }
  6000. toHex(isCompressed = true) {
  6001. return bytesToHex(this.toRawBytes(isCompressed));
  6002. }
  6003. }
  6004. Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
  6005. Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
  6006. const _bits = CURVE.nBitLength;
  6007. const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
  6008. // Validate if generator point is on curve
  6009. return {
  6010. CURVE,
  6011. ProjectivePoint: Point,
  6012. normPrivateKeyToScalar,
  6013. weierstrassEquation,
  6014. isWithinCurveOrder,
  6015. };
  6016. }
  6017. function validateOpts(curve) {
  6018. const opts = validateBasic(curve);
  6019. validateObject(opts, {
  6020. hash: 'hash',
  6021. hmac: 'function',
  6022. randomBytes: 'function',
  6023. }, {
  6024. bits2int: 'function',
  6025. bits2int_modN: 'function',
  6026. lowS: 'boolean',
  6027. });
  6028. return Object.freeze({ lowS: true, ...opts });
  6029. }
  6030. function weierstrass(curveDef) {
  6031. const CURVE = validateOpts(curveDef);
  6032. const { Fp, n: CURVE_ORDER } = CURVE;
  6033. const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32
  6034. const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32
  6035. function isValidFieldElement(num) {
  6036. return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE
  6037. }
  6038. function modN(a) {
  6039. return mod(a, CURVE_ORDER);
  6040. }
  6041. function invN(a) {
  6042. return invert(a, CURVE_ORDER);
  6043. }
  6044. const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({
  6045. ...CURVE,
  6046. toBytes(_c, point, isCompressed) {
  6047. const a = point.toAffine();
  6048. const x = Fp.toBytes(a.x);
  6049. const cat = concatBytes;
  6050. if (isCompressed) {
  6051. return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);
  6052. }
  6053. else {
  6054. return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));
  6055. }
  6056. },
  6057. fromBytes(bytes) {
  6058. const len = bytes.length;
  6059. const head = bytes[0];
  6060. const tail = bytes.subarray(1);
  6061. // this.assertValidity() is done inside of fromHex
  6062. if (len === compressedLen && (head === 0x02 || head === 0x03)) {
  6063. const x = bytesToNumberBE(tail);
  6064. if (!isValidFieldElement(x))
  6065. throw new Error('Point is not on curve');
  6066. const y2 = weierstrassEquation(x); // y² = x³ + ax + b
  6067. let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
  6068. const isYOdd = (y & _1n$1) === _1n$1;
  6069. // ECDSA
  6070. const isHeadOdd = (head & 1) === 1;
  6071. if (isHeadOdd !== isYOdd)
  6072. y = Fp.neg(y);
  6073. return { x, y };
  6074. }
  6075. else if (len === uncompressedLen && head === 0x04) {
  6076. const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
  6077. const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
  6078. return { x, y };
  6079. }
  6080. else {
  6081. throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);
  6082. }
  6083. },
  6084. });
  6085. const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength));
  6086. function isBiggerThanHalfOrder(number) {
  6087. const HALF = CURVE_ORDER >> _1n$1;
  6088. return number > HALF;
  6089. }
  6090. function normalizeS(s) {
  6091. return isBiggerThanHalfOrder(s) ? modN(-s) : s;
  6092. }
  6093. // slice bytes num
  6094. const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to));
  6095. /**
  6096. * ECDSA signature with its (r, s) properties. Supports DER & compact representations.
  6097. */
  6098. class Signature {
  6099. constructor(r, s, recovery) {
  6100. this.r = r;
  6101. this.s = s;
  6102. this.recovery = recovery;
  6103. this.assertValidity();
  6104. }
  6105. // pair (bytes of r, bytes of s)
  6106. static fromCompact(hex) {
  6107. const l = CURVE.nByteLength;
  6108. hex = ensureBytes('compactSignature', hex, l * 2);
  6109. return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));
  6110. }
  6111. // DER encoded ECDSA signature
  6112. // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
  6113. static fromDER(hex) {
  6114. const { r, s } = DER.toSig(ensureBytes('DER', hex));
  6115. return new Signature(r, s);
  6116. }
  6117. assertValidity() {
  6118. // can use assertGE here
  6119. if (!isWithinCurveOrder(this.r))
  6120. throw new Error('r must be 0 < r < CURVE.n');
  6121. if (!isWithinCurveOrder(this.s))
  6122. throw new Error('s must be 0 < s < CURVE.n');
  6123. }
  6124. addRecoveryBit(recovery) {
  6125. return new Signature(this.r, this.s, recovery);
  6126. }
  6127. recoverPublicKey(msgHash) {
  6128. const { r, s, recovery: rec } = this;
  6129. const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash
  6130. if (rec == null || ![0, 1, 2, 3].includes(rec))
  6131. throw new Error('recovery id invalid');
  6132. const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
  6133. if (radj >= Fp.ORDER)
  6134. throw new Error('recovery id 2 or 3 invalid');
  6135. const prefix = (rec & 1) === 0 ? '02' : '03';
  6136. const R = Point.fromHex(prefix + numToNByteStr(radj));
  6137. const ir = invN(radj); // r^-1
  6138. const u1 = modN(-h * ir); // -hr^-1
  6139. const u2 = modN(s * ir); // sr^-1
  6140. const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)
  6141. if (!Q)
  6142. throw new Error('point at infinify'); // unsafe is fine: no priv data leaked
  6143. Q.assertValidity();
  6144. return Q;
  6145. }
  6146. // Signatures should be low-s, to prevent malleability.
  6147. hasHighS() {
  6148. return isBiggerThanHalfOrder(this.s);
  6149. }
  6150. normalizeS() {
  6151. return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;
  6152. }
  6153. // DER-encoded
  6154. toDERRawBytes() {
  6155. return hexToBytes(this.toDERHex());
  6156. }
  6157. toDERHex() {
  6158. return DER.hexFromSig({ r: this.r, s: this.s });
  6159. }
  6160. // padded bytes of r, then padded bytes of s
  6161. toCompactRawBytes() {
  6162. return hexToBytes(this.toCompactHex());
  6163. }
  6164. toCompactHex() {
  6165. return numToNByteStr(this.r) + numToNByteStr(this.s);
  6166. }
  6167. }
  6168. const utils = {
  6169. isValidPrivateKey(privateKey) {
  6170. try {
  6171. normPrivateKeyToScalar(privateKey);
  6172. return true;
  6173. }
  6174. catch (error) {
  6175. return false;
  6176. }
  6177. },
  6178. normPrivateKeyToScalar: normPrivateKeyToScalar,
  6179. /**
  6180. * Produces cryptographically secure private key from random of size
  6181. * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
  6182. */
  6183. randomPrivateKey: () => {
  6184. const length = getMinHashLength(CURVE.n);
  6185. return mapHashToField(CURVE.randomBytes(length), CURVE.n);
  6186. },
  6187. /**
  6188. * Creates precompute table for an arbitrary EC point. Makes point "cached".
  6189. * Allows to massively speed-up `point.multiply(scalar)`.
  6190. * @returns cached point
  6191. * @example
  6192. * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
  6193. * fast.multiply(privKey); // much faster ECDH now
  6194. */
  6195. precompute(windowSize = 8, point = Point.BASE) {
  6196. point._setWindowSize(windowSize);
  6197. point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here
  6198. return point;
  6199. },
  6200. };
  6201. /**
  6202. * Computes public key for a private key. Checks for validity of the private key.
  6203. * @param privateKey private key
  6204. * @param isCompressed whether to return compact (default), or full key
  6205. * @returns Public key, full when isCompressed=false; short when isCompressed=true
  6206. */
  6207. function getPublicKey(privateKey, isCompressed = true) {
  6208. return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);
  6209. }
  6210. /**
  6211. * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
  6212. */
  6213. function isProbPub(item) {
  6214. const arr = item instanceof Uint8Array;
  6215. const str = typeof item === 'string';
  6216. const len = (arr || str) && item.length;
  6217. if (arr)
  6218. return len === compressedLen || len === uncompressedLen;
  6219. if (str)
  6220. return len === 2 * compressedLen || len === 2 * uncompressedLen;
  6221. if (item instanceof Point)
  6222. return true;
  6223. return false;
  6224. }
  6225. /**
  6226. * ECDH (Elliptic Curve Diffie Hellman).
  6227. * Computes shared public key from private key and public key.
  6228. * Checks: 1) private key validity 2) shared key is on-curve.
  6229. * Does NOT hash the result.
  6230. * @param privateA private key
  6231. * @param publicB different public key
  6232. * @param isCompressed whether to return compact (default), or full key
  6233. * @returns shared public key
  6234. */
  6235. function getSharedSecret(privateA, publicB, isCompressed = true) {
  6236. if (isProbPub(privateA))
  6237. throw new Error('first arg must be private key');
  6238. if (!isProbPub(publicB))
  6239. throw new Error('second arg must be public key');
  6240. const b = Point.fromHex(publicB); // check for being on-curve
  6241. return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
  6242. }
  6243. // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
  6244. // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
  6245. // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
  6246. // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
  6247. const bits2int = CURVE.bits2int ||
  6248. function (bytes) {
  6249. // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
  6250. // for some cases, since bytes.length * 8 is not actual bitLength.
  6251. const num = bytesToNumberBE(bytes); // check for == u8 done here
  6252. const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits
  6253. return delta > 0 ? num >> BigInt(delta) : num;
  6254. };
  6255. const bits2int_modN = CURVE.bits2int_modN ||
  6256. function (bytes) {
  6257. return modN(bits2int(bytes)); // can't use bytesToNumberBE here
  6258. };
  6259. // NOTE: pads output with zero as per spec
  6260. const ORDER_MASK = bitMask(CURVE.nBitLength);
  6261. /**
  6262. * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
  6263. */
  6264. function int2octets(num) {
  6265. if (typeof num !== 'bigint')
  6266. throw new Error('bigint expected');
  6267. if (!(_0n <= num && num < ORDER_MASK))
  6268. throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);
  6269. // works with order, can have different size than numToField!
  6270. return numberToBytesBE(num, CURVE.nByteLength);
  6271. }
  6272. // Steps A, D of RFC6979 3.2
  6273. // Creates RFC6979 seed; converts msg/privKey to numbers.
  6274. // Used only in sign, not in verify.
  6275. // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.
  6276. // Also it can be bigger for P224 + SHA256
  6277. function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
  6278. if (['recovered', 'canonical'].some((k) => k in opts))
  6279. throw new Error('sign() legacy options not supported');
  6280. const { hash, randomBytes } = CURVE;
  6281. let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default
  6282. if (lowS == null)
  6283. lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash
  6284. msgHash = ensureBytes('msgHash', msgHash);
  6285. if (prehash)
  6286. msgHash = ensureBytes('prehashed msgHash', hash(msgHash));
  6287. // We can't later call bits2octets, since nested bits2int is broken for curves
  6288. // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.
  6289. // const bits2octets = (bits) => int2octets(bits2int_modN(bits))
  6290. const h1int = bits2int_modN(msgHash);
  6291. const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint
  6292. const seedArgs = [int2octets(d), int2octets(h1int)];
  6293. // extraEntropy. RFC6979 3.6: additional k' (optional).
  6294. if (ent != null) {
  6295. // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
  6296. const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is
  6297. seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes
  6298. }
  6299. const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2
  6300. const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
  6301. // Converts signature params into point w r/s, checks result for validity.
  6302. function k2sig(kBytes) {
  6303. // RFC 6979 Section 3.2, step 3: k = bits2int(T)
  6304. const k = bits2int(kBytes); // Cannot use fields methods, since it is group element
  6305. if (!isWithinCurveOrder(k))
  6306. return; // Important: all mod() calls here must be done over N
  6307. const ik = invN(k); // k^-1 mod n
  6308. const q = Point.BASE.multiply(k).toAffine(); // q = Gk
  6309. const r = modN(q.x); // r = q.x mod n
  6310. if (r === _0n)
  6311. return;
  6312. // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
  6313. // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
  6314. // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
  6315. const s = modN(ik * modN(m + r * d)); // Not using blinding here
  6316. if (s === _0n)
  6317. return;
  6318. let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n$1); // recovery bit (2 or 3, when q.x > n)
  6319. let normS = s;
  6320. if (lowS && isBiggerThanHalfOrder(s)) {
  6321. normS = normalizeS(s); // if lowS was passed, ensure s is always
  6322. recovery ^= 1; // // in the bottom half of N
  6323. }
  6324. return new Signature(r, normS, recovery); // use normS, not s
  6325. }
  6326. return { seed, k2sig };
  6327. }
  6328. const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };
  6329. const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };
  6330. /**
  6331. * Signs message hash with a private key.
  6332. * ```
  6333. * sign(m, d, k) where
  6334. * (x, y) = G × k
  6335. * r = x mod n
  6336. * s = (m + dr)/k mod n
  6337. * ```
  6338. * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.
  6339. * @param privKey private key
  6340. * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.
  6341. * @returns signature with recovery param
  6342. */
  6343. function sign(msgHash, privKey, opts = defaultSigOpts) {
  6344. const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.
  6345. const C = CURVE;
  6346. const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);
  6347. return drbg(seed, k2sig); // Steps B, C, D, E, F, G
  6348. }
  6349. // Enable precomputes. Slows down first publicKey computation by 20ms.
  6350. Point.BASE._setWindowSize(8);
  6351. // utils.precompute(8, ProjectivePoint.BASE)
  6352. /**
  6353. * Verifies a signature against message hash and public key.
  6354. * Rejects lowS signatures by default: to override,
  6355. * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
  6356. *
  6357. * ```
  6358. * verify(r, s, h, P) where
  6359. * U1 = hs^-1 mod n
  6360. * U2 = rs^-1 mod n
  6361. * R = U1⋅G - U2⋅P
  6362. * mod(R.x, n) == r
  6363. * ```
  6364. */
  6365. function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {
  6366. const sg = signature;
  6367. msgHash = ensureBytes('msgHash', msgHash);
  6368. publicKey = ensureBytes('publicKey', publicKey);
  6369. if ('strict' in opts)
  6370. throw new Error('options.strict was renamed to lowS');
  6371. const { lowS, prehash } = opts;
  6372. let _sig = undefined;
  6373. let P;
  6374. try {
  6375. if (typeof sg === 'string' || sg instanceof Uint8Array) {
  6376. // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).
  6377. // Since DER can also be 2*nByteLength bytes, we check for it first.
  6378. try {
  6379. _sig = Signature.fromDER(sg);
  6380. }
  6381. catch (derError) {
  6382. if (!(derError instanceof DER.Err))
  6383. throw derError;
  6384. _sig = Signature.fromCompact(sg);
  6385. }
  6386. }
  6387. else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {
  6388. const { r, s } = sg;
  6389. _sig = new Signature(r, s);
  6390. }
  6391. else {
  6392. throw new Error('PARSE');
  6393. }
  6394. P = Point.fromHex(publicKey);
  6395. }
  6396. catch (error) {
  6397. if (error.message === 'PARSE')
  6398. throw new Error(`signature must be Signature instance, Uint8Array or hex string`);
  6399. return false;
  6400. }
  6401. if (lowS && _sig.hasHighS())
  6402. return false;
  6403. if (prehash)
  6404. msgHash = CURVE.hash(msgHash);
  6405. const { r, s } = _sig;
  6406. const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element
  6407. const is = invN(s); // s^-1
  6408. const u1 = modN(h * is); // u1 = hs^-1 mod n
  6409. const u2 = modN(r * is); // u2 = rs^-1 mod n
  6410. const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P
  6411. if (!R)
  6412. return false;
  6413. const v = modN(R.x);
  6414. return v === r;
  6415. }
  6416. return {
  6417. CURVE,
  6418. getPublicKey,
  6419. getSharedSecret,
  6420. sign,
  6421. verify,
  6422. ProjectivePoint: Point,
  6423. Signature,
  6424. utils,
  6425. };
  6426. }
  6427. /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
  6428. // connects noble-curves to noble-hashes
  6429. function getHash(hash) {
  6430. return {
  6431. hash,
  6432. hmac: (key, ...msgs) => hmac(hash, key, concatBytes$1(...msgs)),
  6433. randomBytes: randomBytes$2,
  6434. };
  6435. }
  6436. function createCurve(curveDef, defHash) {
  6437. const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });
  6438. return Object.freeze({ ...create(defHash), create });
  6439. }
  6440. /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
  6441. const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');
  6442. const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');
  6443. const _1n = BigInt(1);
  6444. const _2n = BigInt(2);
  6445. const divNearest = (a, b) => (a + b / _2n) / b;
  6446. /**
  6447. * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
  6448. * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
  6449. */
  6450. function sqrtMod(y) {
  6451. const P = secp256k1P;
  6452. // prettier-ignore
  6453. const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
  6454. // prettier-ignore
  6455. const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
  6456. const b2 = (y * y * y) % P; // x^3, 11
  6457. const b3 = (b2 * b2 * y) % P; // x^7
  6458. const b6 = (pow2(b3, _3n, P) * b3) % P;
  6459. const b9 = (pow2(b6, _3n, P) * b3) % P;
  6460. const b11 = (pow2(b9, _2n, P) * b2) % P;
  6461. const b22 = (pow2(b11, _11n, P) * b11) % P;
  6462. const b44 = (pow2(b22, _22n, P) * b22) % P;
  6463. const b88 = (pow2(b44, _44n, P) * b44) % P;
  6464. const b176 = (pow2(b88, _88n, P) * b88) % P;
  6465. const b220 = (pow2(b176, _44n, P) * b44) % P;
  6466. const b223 = (pow2(b220, _3n, P) * b3) % P;
  6467. const t1 = (pow2(b223, _23n, P) * b22) % P;
  6468. const t2 = (pow2(t1, _6n, P) * b2) % P;
  6469. const root = pow2(t2, _2n, P);
  6470. if (!Fp.eql(Fp.sqr(root), y))
  6471. throw new Error('Cannot find square root');
  6472. return root;
  6473. }
  6474. const Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
  6475. const secp256k1 = createCurve({
  6476. a: BigInt(0),
  6477. b: BigInt(7),
  6478. Fp,
  6479. n: secp256k1N,
  6480. // Base point (x, y) aka generator point
  6481. Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),
  6482. Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
  6483. h: BigInt(1),
  6484. lowS: true,
  6485. /**
  6486. * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
  6487. * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
  6488. * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
  6489. * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066
  6490. */
  6491. endo: {
  6492. beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
  6493. splitScalar: (k) => {
  6494. const n = secp256k1N;
  6495. const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');
  6496. const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');
  6497. const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');
  6498. const b2 = a1;
  6499. const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)
  6500. const c1 = divNearest(b2 * k, n);
  6501. const c2 = divNearest(-b1 * k, n);
  6502. let k1 = mod(k - c1 * a1 - c2 * a2, n);
  6503. let k2 = mod(-c1 * b1 - c2 * b2, n);
  6504. const k1neg = k1 > POW_2_128;
  6505. const k2neg = k2 > POW_2_128;
  6506. if (k1neg)
  6507. k1 = n - k1;
  6508. if (k2neg)
  6509. k2 = n - k2;
  6510. if (k1 > POW_2_128 || k2 > POW_2_128) {
  6511. throw new Error('splitScalar: Endomorphism failed, k=' + k);
  6512. }
  6513. return { k1neg, k1, k2neg, k2 };
  6514. },
  6515. },
  6516. }, sha256$1);
  6517. // Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
  6518. // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
  6519. BigInt(0);
  6520. secp256k1.ProjectivePoint;
  6521. /**
  6522. * A constant for the zero address.
  6523. *
  6524. * (**i.e.** ``"0x0000000000000000000000000000000000000000"``)
  6525. */
  6526. const ZeroAddress = "0x0000000000000000000000000000000000000000";
  6527. /**
  6528. * A constant for the zero hash.
  6529. *
  6530. * (**i.e.** ``"0x0000000000000000000000000000000000000000000000000000000000000000"``)
  6531. */
  6532. const ZeroHash = "0x0000000000000000000000000000000000000000000000000000000000000000";
  6533. /**
  6534. * A constant for the order N for the secp256k1 curve.
  6535. *
  6536. * (**i.e.** ``0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n``)
  6537. */
  6538. const N$1 = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");
  6539. /**
  6540. * A constant for the number of wei in a single ether.
  6541. *
  6542. * (**i.e.** ``1000000000000000000n``)
  6543. */
  6544. const WeiPerEther = BigInt("1000000000000000000");
  6545. /**
  6546. * A constant for the maximum value for a ``uint256``.
  6547. *
  6548. * (**i.e.** ``0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn``)
  6549. */
  6550. const MaxUint256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
  6551. /**
  6552. * A constant for the minimum value for an ``int256``.
  6553. *
  6554. * (**i.e.** ``-8000000000000000000000000000000000000000000000000000000000000000n``)
  6555. */
  6556. const MinInt256 = BigInt("0x8000000000000000000000000000000000000000000000000000000000000000") * BigInt(-1);
  6557. /**
  6558. * A constant for the maximum value for an ``int256``.
  6559. *
  6560. * (**i.e.** ``0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn``)
  6561. */
  6562. const MaxInt256 = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
  6563. // NFKC (composed) // (decomposed)
  6564. /**
  6565. * A constant for the ether symbol (normalized using NFKC).
  6566. *
  6567. * (**i.e.** ``"\\u039e"``)
  6568. */
  6569. const EtherSymbol = "\u039e"; // "\uD835\uDF63";
  6570. /**
  6571. * A constant for the [[link-eip-191]] personal message prefix.
  6572. *
  6573. * (**i.e.** ``"\\x19Ethereum Signed Message:\\n"``)
  6574. */
  6575. const MessagePrefix = "\x19Ethereum Signed Message:\n";
  6576. // Constants
  6577. const BN_0$7 = BigInt(0);
  6578. const BN_1$3 = BigInt(1);
  6579. const BN_2$3 = BigInt(2);
  6580. const BN_27$1 = BigInt(27);
  6581. const BN_28$1 = BigInt(28);
  6582. const BN_35$1 = BigInt(35);
  6583. const _guard$3 = {};
  6584. function toUint256(value) {
  6585. return zeroPadValue(toBeArray(value), 32);
  6586. }
  6587. /**
  6588. * A Signature @TODO
  6589. *
  6590. *
  6591. * @_docloc: api/crypto:Signing
  6592. */
  6593. class Signature {
  6594. #r;
  6595. #s;
  6596. #v;
  6597. #networkV;
  6598. /**
  6599. * The ``r`` value for a signautre.
  6600. *
  6601. * This represents the ``x`` coordinate of a "reference" or
  6602. * challenge point, from which the ``y`` can be computed.
  6603. */
  6604. get r() { return this.#r; }
  6605. set r(value) {
  6606. assertArgument(dataLength(value) === 32, "invalid r", "value", value);
  6607. this.#r = hexlify(value);
  6608. }
  6609. /**
  6610. * The ``s`` value for a signature.
  6611. */
  6612. get s() { return this.#s; }
  6613. set s(_value) {
  6614. assertArgument(dataLength(_value) === 32, "invalid s", "value", _value);
  6615. const value = hexlify(_value);
  6616. assertArgument(parseInt(value.substring(0, 3)) < 8, "non-canonical s", "value", value);
  6617. this.#s = value;
  6618. }
  6619. /**
  6620. * The ``v`` value for a signature.
  6621. *
  6622. * Since a given ``x`` value for ``r`` has two possible values for
  6623. * its correspondin ``y``, the ``v`` indicates which of the two ``y``
  6624. * values to use.
  6625. *
  6626. * It is normalized to the values ``27`` or ``28`` for legacy
  6627. * purposes.
  6628. */
  6629. get v() { return this.#v; }
  6630. set v(value) {
  6631. const v = getNumber(value, "value");
  6632. assertArgument(v === 27 || v === 28, "invalid v", "v", value);
  6633. this.#v = v;
  6634. }
  6635. /**
  6636. * The EIP-155 ``v`` for legacy transactions. For non-legacy
  6637. * transactions, this value is ``null``.
  6638. */
  6639. get networkV() { return this.#networkV; }
  6640. /**
  6641. * The chain ID for EIP-155 legacy transactions. For non-legacy
  6642. * transactions, this value is ``null``.
  6643. */
  6644. get legacyChainId() {
  6645. const v = this.networkV;
  6646. if (v == null) {
  6647. return null;
  6648. }
  6649. return Signature.getChainId(v);
  6650. }
  6651. /**
  6652. * The ``yParity`` for the signature.
  6653. *
  6654. * See ``v`` for more details on how this value is used.
  6655. */
  6656. get yParity() {
  6657. return (this.v === 27) ? 0 : 1;
  6658. }
  6659. /**
  6660. * The [[link-eip-2098]] compact representation of the ``yParity``
  6661. * and ``s`` compacted into a single ``bytes32``.
  6662. */
  6663. get yParityAndS() {
  6664. // The EIP-2098 compact representation
  6665. const yParityAndS = getBytes(this.s);
  6666. if (this.yParity) {
  6667. yParityAndS[0] |= 0x80;
  6668. }
  6669. return hexlify(yParityAndS);
  6670. }
  6671. /**
  6672. * The [[link-eip-2098]] compact representation.
  6673. */
  6674. get compactSerialized() {
  6675. return concat([this.r, this.yParityAndS]);
  6676. }
  6677. /**
  6678. * The serialized representation.
  6679. */
  6680. get serialized() {
  6681. return concat([this.r, this.s, (this.yParity ? "0x1c" : "0x1b")]);
  6682. }
  6683. /**
  6684. * @private
  6685. */
  6686. constructor(guard, r, s, v) {
  6687. assertPrivate(guard, _guard$3, "Signature");
  6688. this.#r = r;
  6689. this.#s = s;
  6690. this.#v = v;
  6691. this.#networkV = null;
  6692. }
  6693. [Symbol.for('nodejs.util.inspect.custom')]() {
  6694. return `Signature { r: "${this.r}", s: "${this.s}", yParity: ${this.yParity}, networkV: ${this.networkV} }`;
  6695. }
  6696. /**
  6697. * Returns a new identical [[Signature]].
  6698. */
  6699. clone() {
  6700. const clone = new Signature(_guard$3, this.r, this.s, this.v);
  6701. if (this.networkV) {
  6702. clone.#networkV = this.networkV;
  6703. }
  6704. return clone;
  6705. }
  6706. /**
  6707. * Returns a representation that is compatible with ``JSON.stringify``.
  6708. */
  6709. toJSON() {
  6710. const networkV = this.networkV;
  6711. return {
  6712. _type: "signature",
  6713. networkV: ((networkV != null) ? networkV.toString() : null),
  6714. r: this.r, s: this.s, v: this.v,
  6715. };
  6716. }
  6717. /**
  6718. * Compute the chain ID from the ``v`` in a legacy EIP-155 transactions.
  6719. *
  6720. * @example:
  6721. * Signature.getChainId(45)
  6722. * //_result:
  6723. *
  6724. * Signature.getChainId(46)
  6725. * //_result:
  6726. */
  6727. static getChainId(v) {
  6728. const bv = getBigInt(v, "v");
  6729. // The v is not an EIP-155 v, so it is the unspecified chain ID
  6730. if ((bv == BN_27$1) || (bv == BN_28$1)) {
  6731. return BN_0$7;
  6732. }
  6733. // Bad value for an EIP-155 v
  6734. assertArgument(bv >= BN_35$1, "invalid EIP-155 v", "v", v);
  6735. return (bv - BN_35$1) / BN_2$3;
  6736. }
  6737. /**
  6738. * Compute the ``v`` for a chain ID for a legacy EIP-155 transactions.
  6739. *
  6740. * Legacy transactions which use [[link-eip-155]] hijack the ``v``
  6741. * property to include the chain ID.
  6742. *
  6743. * @example:
  6744. * Signature.getChainIdV(5, 27)
  6745. * //_result:
  6746. *
  6747. * Signature.getChainIdV(5, 28)
  6748. * //_result:
  6749. *
  6750. */
  6751. static getChainIdV(chainId, v) {
  6752. return (getBigInt(chainId) * BN_2$3) + BigInt(35 + v - 27);
  6753. }
  6754. /**
  6755. * Compute the normalized legacy transaction ``v`` from a ``yParirty``,
  6756. * a legacy transaction ``v`` or a legacy [[link-eip-155]] transaction.
  6757. *
  6758. * @example:
  6759. * // The values 0 and 1 imply v is actually yParity
  6760. * Signature.getNormalizedV(0)
  6761. * //_result:
  6762. *
  6763. * // Legacy non-EIP-1559 transaction (i.e. 27 or 28)
  6764. * Signature.getNormalizedV(27)
  6765. * //_result:
  6766. *
  6767. * // Legacy EIP-155 transaction (i.e. >= 35)
  6768. * Signature.getNormalizedV(46)
  6769. * //_result:
  6770. *
  6771. * // Invalid values throw
  6772. * Signature.getNormalizedV(5)
  6773. * //_error:
  6774. */
  6775. static getNormalizedV(v) {
  6776. const bv = getBigInt(v);
  6777. if (bv === BN_0$7 || bv === BN_27$1) {
  6778. return 27;
  6779. }
  6780. if (bv === BN_1$3 || bv === BN_28$1) {
  6781. return 28;
  6782. }
  6783. assertArgument(bv >= BN_35$1, "invalid v", "v", v);
  6784. // Otherwise, EIP-155 v means odd is 27 and even is 28
  6785. return (bv & BN_1$3) ? 27 : 28;
  6786. }
  6787. /**
  6788. * Creates a new [[Signature]].
  6789. *
  6790. * If no %%sig%% is provided, a new [[Signature]] is created
  6791. * with default values.
  6792. *
  6793. * If %%sig%% is a string, it is parsed.
  6794. */
  6795. static from(sig) {
  6796. function assertError(check, message) {
  6797. assertArgument(check, message, "signature", sig);
  6798. }
  6799. if (sig == null) {
  6800. return new Signature(_guard$3, ZeroHash, ZeroHash, 27);
  6801. }
  6802. if (typeof (sig) === "string") {
  6803. const bytes = getBytes(sig, "signature");
  6804. if (bytes.length === 64) {
  6805. const r = hexlify(bytes.slice(0, 32));
  6806. const s = bytes.slice(32, 64);
  6807. const v = (s[0] & 0x80) ? 28 : 27;
  6808. s[0] &= 0x7f;
  6809. return new Signature(_guard$3, r, hexlify(s), v);
  6810. }
  6811. if (bytes.length === 65) {
  6812. const r = hexlify(bytes.slice(0, 32));
  6813. const s = bytes.slice(32, 64);
  6814. assertError((s[0] & 0x80) === 0, "non-canonical s");
  6815. const v = Signature.getNormalizedV(bytes[64]);
  6816. return new Signature(_guard$3, r, hexlify(s), v);
  6817. }
  6818. assertError(false, "invalid raw signature length");
  6819. }
  6820. if (sig instanceof Signature) {
  6821. return sig.clone();
  6822. }
  6823. // Get r
  6824. const _r = sig.r;
  6825. assertError(_r != null, "missing r");
  6826. const r = toUint256(_r);
  6827. // Get s; by any means necessary (we check consistency below)
  6828. const s = (function (s, yParityAndS) {
  6829. if (s != null) {
  6830. return toUint256(s);
  6831. }
  6832. if (yParityAndS != null) {
  6833. assertError(isHexString(yParityAndS, 32), "invalid yParityAndS");
  6834. const bytes = getBytes(yParityAndS);
  6835. bytes[0] &= 0x7f;
  6836. return hexlify(bytes);
  6837. }
  6838. assertError(false, "missing s");
  6839. })(sig.s, sig.yParityAndS);
  6840. assertError((getBytes(s)[0] & 0x80) == 0, "non-canonical s");
  6841. // Get v; by any means necessary (we check consistency below)
  6842. const { networkV, v } = (function (_v, yParityAndS, yParity) {
  6843. if (_v != null) {
  6844. const v = getBigInt(_v);
  6845. return {
  6846. networkV: ((v >= BN_35$1) ? v : undefined),
  6847. v: Signature.getNormalizedV(v)
  6848. };
  6849. }
  6850. if (yParityAndS != null) {
  6851. assertError(isHexString(yParityAndS, 32), "invalid yParityAndS");
  6852. return { v: ((getBytes(yParityAndS)[0] & 0x80) ? 28 : 27) };
  6853. }
  6854. if (yParity != null) {
  6855. switch (getNumber(yParity, "sig.yParity")) {
  6856. case 0: return { v: 27 };
  6857. case 1: return { v: 28 };
  6858. }
  6859. assertError(false, "invalid yParity");
  6860. }
  6861. assertError(false, "missing v");
  6862. })(sig.v, sig.yParityAndS, sig.yParity);
  6863. const result = new Signature(_guard$3, r, s, v);
  6864. if (networkV) {
  6865. result.#networkV = networkV;
  6866. }
  6867. // If multiple of v, yParity, yParityAndS we given, check they match
  6868. assertError(sig.yParity == null || getNumber(sig.yParity, "sig.yParity") === result.yParity, "yParity mismatch");
  6869. assertError(sig.yParityAndS == null || sig.yParityAndS === result.yParityAndS, "yParityAndS mismatch");
  6870. return result;
  6871. }
  6872. }
  6873. /**
  6874. * Add details about signing here.
  6875. *
  6876. * @_subsection: api/crypto:Signing [about-signing]
  6877. */
  6878. /**
  6879. * A **SigningKey** provides high-level access to the elliptic curve
  6880. * cryptography (ECC) operations and key management.
  6881. */
  6882. class SigningKey {
  6883. #privateKey;
  6884. /**
  6885. * Creates a new **SigningKey** for %%privateKey%%.
  6886. */
  6887. constructor(privateKey) {
  6888. assertArgument(dataLength(privateKey) === 32, "invalid private key", "privateKey", "[REDACTED]");
  6889. this.#privateKey = hexlify(privateKey);
  6890. }
  6891. /**
  6892. * The private key.
  6893. */
  6894. get privateKey() { return this.#privateKey; }
  6895. /**
  6896. * The uncompressed public key.
  6897. *
  6898. * This will always begin with the prefix ``0x04`` and be 132
  6899. * characters long (the ``0x`` prefix and 130 hexadecimal nibbles).
  6900. */
  6901. get publicKey() { return SigningKey.computePublicKey(this.#privateKey); }
  6902. /**
  6903. * The compressed public key.
  6904. *
  6905. * This will always begin with either the prefix ``0x02`` or ``0x03``
  6906. * and be 68 characters long (the ``0x`` prefix and 33 hexadecimal
  6907. * nibbles)
  6908. */
  6909. get compressedPublicKey() { return SigningKey.computePublicKey(this.#privateKey, true); }
  6910. /**
  6911. * Return the signature of the signed %%digest%%.
  6912. */
  6913. sign(digest) {
  6914. assertArgument(dataLength(digest) === 32, "invalid digest length", "digest", digest);
  6915. const sig = secp256k1.sign(getBytesCopy(digest), getBytesCopy(this.#privateKey), {
  6916. lowS: true
  6917. });
  6918. return Signature.from({
  6919. r: toBeHex(sig.r, 32),
  6920. s: toBeHex(sig.s, 32),
  6921. v: (sig.recovery ? 0x1c : 0x1b)
  6922. });
  6923. }
  6924. /**
  6925. * Returns the [[link-wiki-ecdh]] shared secret between this
  6926. * private key and the %%other%% key.
  6927. *
  6928. * The %%other%% key may be any type of key, a raw public key,
  6929. * a compressed/uncompressed pubic key or aprivate key.
  6930. *
  6931. * Best practice is usually to use a cryptographic hash on the
  6932. * returned value before using it as a symetric secret.
  6933. *
  6934. * @example:
  6935. * sign1 = new SigningKey(id("some-secret-1"))
  6936. * sign2 = new SigningKey(id("some-secret-2"))
  6937. *
  6938. * // Notice that privA.computeSharedSecret(pubB)...
  6939. * sign1.computeSharedSecret(sign2.publicKey)
  6940. * //_result:
  6941. *
  6942. * // ...is equal to privB.computeSharedSecret(pubA).
  6943. * sign2.computeSharedSecret(sign1.publicKey)
  6944. * //_result:
  6945. */
  6946. computeSharedSecret(other) {
  6947. const pubKey = SigningKey.computePublicKey(other);
  6948. return hexlify(secp256k1.getSharedSecret(getBytesCopy(this.#privateKey), getBytes(pubKey), false));
  6949. }
  6950. /**
  6951. * Compute the public key for %%key%%, optionally %%compressed%%.
  6952. *
  6953. * The %%key%% may be any type of key, a raw public key, a
  6954. * compressed/uncompressed public key or private key.
  6955. *
  6956. * @example:
  6957. * sign = new SigningKey(id("some-secret"));
  6958. *
  6959. * // Compute the uncompressed public key for a private key
  6960. * SigningKey.computePublicKey(sign.privateKey)
  6961. * //_result:
  6962. *
  6963. * // Compute the compressed public key for a private key
  6964. * SigningKey.computePublicKey(sign.privateKey, true)
  6965. * //_result:
  6966. *
  6967. * // Compute the uncompressed public key
  6968. * SigningKey.computePublicKey(sign.publicKey, false);
  6969. * //_result:
  6970. *
  6971. * // Compute the Compressed a public key
  6972. * SigningKey.computePublicKey(sign.publicKey, true);
  6973. * //_result:
  6974. */
  6975. static computePublicKey(key, compressed) {
  6976. let bytes = getBytes(key, "key");
  6977. // private key
  6978. if (bytes.length === 32) {
  6979. const pubKey = secp256k1.getPublicKey(bytes, !!compressed);
  6980. return hexlify(pubKey);
  6981. }
  6982. // raw public key; use uncompressed key with 0x04 prefix
  6983. if (bytes.length === 64) {
  6984. const pub = new Uint8Array(65);
  6985. pub[0] = 0x04;
  6986. pub.set(bytes, 1);
  6987. bytes = pub;
  6988. }
  6989. const point = secp256k1.ProjectivePoint.fromHex(bytes);
  6990. return hexlify(point.toRawBytes(compressed));
  6991. }
  6992. /**
  6993. * Returns the public key for the private key which produced the
  6994. * %%signature%% for the given %%digest%%.
  6995. *
  6996. * @example:
  6997. * key = new SigningKey(id("some-secret"))
  6998. * digest = id("hello world")
  6999. * sig = key.sign(digest)
  7000. *
  7001. * // Notice the signer public key...
  7002. * key.publicKey
  7003. * //_result:
  7004. *
  7005. * // ...is equal to the recovered public key
  7006. * SigningKey.recoverPublicKey(digest, sig)
  7007. * //_result:
  7008. *
  7009. */
  7010. static recoverPublicKey(digest, signature) {
  7011. assertArgument(dataLength(digest) === 32, "invalid digest length", "digest", digest);
  7012. const sig = Signature.from(signature);
  7013. let secpSig = secp256k1.Signature.fromCompact(getBytesCopy(concat([sig.r, sig.s])));
  7014. secpSig = secpSig.addRecoveryBit(sig.yParity);
  7015. const pubKey = secpSig.recoverPublicKey(getBytesCopy(digest));
  7016. assertArgument(pubKey != null, "invalid signautre for digest", "signature", signature);
  7017. return "0x" + pubKey.toHex(false);
  7018. }
  7019. /**
  7020. * Returns the point resulting from adding the ellipic curve points
  7021. * %%p0%% and %%p1%%.
  7022. *
  7023. * This is not a common function most developers should require, but
  7024. * can be useful for certain privacy-specific techniques.
  7025. *
  7026. * For example, it is used by [[HDNodeWallet]] to compute child
  7027. * addresses from parent public keys and chain codes.
  7028. */
  7029. static addPoints(p0, p1, compressed) {
  7030. const pub0 = secp256k1.ProjectivePoint.fromHex(SigningKey.computePublicKey(p0).substring(2));
  7031. const pub1 = secp256k1.ProjectivePoint.fromHex(SigningKey.computePublicKey(p1).substring(2));
  7032. return "0x" + pub0.add(pub1).toHex(!!compressed);
  7033. }
  7034. }
  7035. /**
  7036. * A fundamental building block of Ethereum is the underlying
  7037. * cryptographic primitives.
  7038. *
  7039. * @_section: api/crypto:Cryptographic Functions [about-crypto]
  7040. */
  7041. /**
  7042. * Once called, prevents any future change to the underlying cryptographic
  7043. * primitives using the ``.register`` feature for hooks.
  7044. */
  7045. function lock() {
  7046. computeHmac.lock();
  7047. keccak256.lock();
  7048. pbkdf2.lock();
  7049. randomBytes.lock();
  7050. ripemd160.lock();
  7051. scrypt.lock();
  7052. scryptSync.lock();
  7053. sha256.lock();
  7054. sha512.lock();
  7055. randomBytes.lock();
  7056. }
  7057. const BN_0$6 = BigInt(0);
  7058. const BN_36 = BigInt(36);
  7059. function getChecksumAddress(address) {
  7060. // if (!isHexString(address, 20)) {
  7061. // logger.throwArgumentError("invalid address", "address", address);
  7062. // }
  7063. address = address.toLowerCase();
  7064. const chars = address.substring(2).split("");
  7065. const expanded = new Uint8Array(40);
  7066. for (let i = 0; i < 40; i++) {
  7067. expanded[i] = chars[i].charCodeAt(0);
  7068. }
  7069. const hashed = getBytes(keccak256(expanded));
  7070. for (let i = 0; i < 40; i += 2) {
  7071. if ((hashed[i >> 1] >> 4) >= 8) {
  7072. chars[i] = chars[i].toUpperCase();
  7073. }
  7074. if ((hashed[i >> 1] & 0x0f) >= 8) {
  7075. chars[i + 1] = chars[i + 1].toUpperCase();
  7076. }
  7077. }
  7078. return "0x" + chars.join("");
  7079. }
  7080. // See: https://en.wikipedia.org/wiki/International_Bank_Account_Number
  7081. // Create lookup table
  7082. const ibanLookup = {};
  7083. for (let i = 0; i < 10; i++) {
  7084. ibanLookup[String(i)] = String(i);
  7085. }
  7086. for (let i = 0; i < 26; i++) {
  7087. ibanLookup[String.fromCharCode(65 + i)] = String(10 + i);
  7088. }
  7089. // How many decimal digits can we process? (for 64-bit float, this is 15)
  7090. // i.e. Math.floor(Math.log10(Number.MAX_SAFE_INTEGER));
  7091. const safeDigits = 15;
  7092. function ibanChecksum(address) {
  7093. address = address.toUpperCase();
  7094. address = address.substring(4) + address.substring(0, 2) + "00";
  7095. let expanded = address.split("").map((c) => { return ibanLookup[c]; }).join("");
  7096. // Javascript can handle integers safely up to 15 (decimal) digits
  7097. while (expanded.length >= safeDigits) {
  7098. let block = expanded.substring(0, safeDigits);
  7099. expanded = parseInt(block, 10) % 97 + expanded.substring(block.length);
  7100. }
  7101. let checksum = String(98 - (parseInt(expanded, 10) % 97));
  7102. while (checksum.length < 2) {
  7103. checksum = "0" + checksum;
  7104. }
  7105. return checksum;
  7106. }
  7107. const Base36 = (function () {
  7108. const result = {};
  7109. for (let i = 0; i < 36; i++) {
  7110. const key = "0123456789abcdefghijklmnopqrstuvwxyz"[i];
  7111. result[key] = BigInt(i);
  7112. }
  7113. return result;
  7114. })();
  7115. function fromBase36(value) {
  7116. value = value.toLowerCase();
  7117. let result = BN_0$6;
  7118. for (let i = 0; i < value.length; i++) {
  7119. result = result * BN_36 + Base36[value[i]];
  7120. }
  7121. return result;
  7122. }
  7123. /**
  7124. * Returns a normalized and checksumed address for %%address%%.
  7125. * This accepts non-checksum addresses, checksum addresses and
  7126. * [[getIcapAddress]] formats.
  7127. *
  7128. * The checksum in Ethereum uses the capitalization (upper-case
  7129. * vs lower-case) of the characters within an address to encode
  7130. * its checksum, which offers, on average, a checksum of 15-bits.
  7131. *
  7132. * If %%address%% contains both upper-case and lower-case, it is
  7133. * assumed to already be a checksum address and its checksum is
  7134. * validated, and if the address fails its expected checksum an
  7135. * error is thrown.
  7136. *
  7137. * If you wish the checksum of %%address%% to be ignore, it should
  7138. * be converted to lower-case (i.e. ``.toLowercase()``) before
  7139. * being passed in. This should be a very rare situation though,
  7140. * that you wish to bypass the safegaurds in place to protect
  7141. * against an address that has been incorrectly copied from another
  7142. * source.
  7143. *
  7144. * @example:
  7145. * // Adds the checksum (via upper-casing specific letters)
  7146. * getAddress("0x8ba1f109551bd432803012645ac136ddd64dba72")
  7147. * //_result:
  7148. *
  7149. * // Converts ICAP address and adds checksum
  7150. * getAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36");
  7151. * //_result:
  7152. *
  7153. * // Throws an error if an address contains mixed case,
  7154. * // but the checksum fails
  7155. * getAddress("0x8Ba1f109551bD432803012645Ac136ddd64DBA72")
  7156. * //_error:
  7157. */
  7158. function getAddress(address) {
  7159. assertArgument(typeof (address) === "string", "invalid address", "address", address);
  7160. if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) {
  7161. // Missing the 0x prefix
  7162. if (!address.startsWith("0x")) {
  7163. address = "0x" + address;
  7164. }
  7165. const result = getChecksumAddress(address);
  7166. // It is a checksummed address with a bad checksum
  7167. assertArgument(!address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) || result === address, "bad address checksum", "address", address);
  7168. return result;
  7169. }
  7170. // Maybe ICAP? (we only support direct mode)
  7171. if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) {
  7172. // It is an ICAP address with a bad checksum
  7173. assertArgument(address.substring(2, 4) === ibanChecksum(address), "bad icap checksum", "address", address);
  7174. let result = fromBase36(address.substring(4)).toString(16);
  7175. while (result.length < 40) {
  7176. result = "0" + result;
  7177. }
  7178. return getChecksumAddress("0x" + result);
  7179. }
  7180. assertArgument(false, "invalid address", "address", address);
  7181. }
  7182. /**
  7183. * The [ICAP Address format](link-icap) format is an early checksum
  7184. * format which attempts to be compatible with the banking
  7185. * industry [IBAN format](link-wiki-iban) for bank accounts.
  7186. *
  7187. * It is no longer common or a recommended format.
  7188. *
  7189. * @example:
  7190. * getIcapAddress("0x8ba1f109551bd432803012645ac136ddd64dba72");
  7191. * //_result:
  7192. *
  7193. * getIcapAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36");
  7194. * //_result:
  7195. *
  7196. * // Throws an error if the ICAP checksum is wrong
  7197. * getIcapAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK37");
  7198. * //_error:
  7199. */
  7200. function getIcapAddress(address) {
  7201. //let base36 = _base16To36(getAddress(address).substring(2)).toUpperCase();
  7202. let base36 = BigInt(getAddress(address)).toString(36).toUpperCase();
  7203. while (base36.length < 30) {
  7204. base36 = "0" + base36;
  7205. }
  7206. return "XE" + ibanChecksum("XE00" + base36) + base36;
  7207. }
  7208. // http://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed
  7209. /**
  7210. * Returns the address that would result from a ``CREATE`` for %%tx%%.
  7211. *
  7212. * This can be used to compute the address a contract will be
  7213. * deployed to by an EOA when sending a deployment transaction (i.e.
  7214. * when the ``to`` address is ``null``).
  7215. *
  7216. * This can also be used to compute the address a contract will be
  7217. * deployed to by a contract, by using the contract's address as the
  7218. * ``to`` and the contract's nonce.
  7219. *
  7220. * @example
  7221. * from = "0x8ba1f109551bD432803012645Ac136ddd64DBA72";
  7222. * nonce = 5;
  7223. *
  7224. * getCreateAddress({ from, nonce });
  7225. * //_result:
  7226. */
  7227. function getCreateAddress(tx) {
  7228. const from = getAddress(tx.from);
  7229. const nonce = getBigInt(tx.nonce, "tx.nonce");
  7230. let nonceHex = nonce.toString(16);
  7231. if (nonceHex === "0") {
  7232. nonceHex = "0x";
  7233. }
  7234. else if (nonceHex.length % 2) {
  7235. nonceHex = "0x0" + nonceHex;
  7236. }
  7237. else {
  7238. nonceHex = "0x" + nonceHex;
  7239. }
  7240. return getAddress(dataSlice(keccak256(encodeRlp([from, nonceHex])), 12));
  7241. }
  7242. /**
  7243. * Returns the address that would result from a ``CREATE2`` operation
  7244. * with the given %%from%%, %%salt%% and %%initCodeHash%%.
  7245. *
  7246. * To compute the %%initCodeHash%% from a contract's init code, use
  7247. * the [[keccak256]] function.
  7248. *
  7249. * For a quick overview and example of ``CREATE2``, see [[link-ricmoo-wisps]].
  7250. *
  7251. * @example
  7252. * // The address of the contract
  7253. * from = "0x8ba1f109551bD432803012645Ac136ddd64DBA72"
  7254. *
  7255. * // The salt
  7256. * salt = id("HelloWorld")
  7257. *
  7258. * // The hash of the initCode
  7259. * initCode = "0x6394198df16000526103ff60206004601c335afa6040516060f3";
  7260. * initCodeHash = keccak256(initCode)
  7261. *
  7262. * getCreate2Address(from, salt, initCodeHash)
  7263. * //_result:
  7264. */
  7265. function getCreate2Address(_from, _salt, _initCodeHash) {
  7266. const from = getAddress(_from);
  7267. const salt = getBytes(_salt, "salt");
  7268. const initCodeHash = getBytes(_initCodeHash, "initCodeHash");
  7269. assertArgument(salt.length === 32, "salt must be 32 bytes", "salt", _salt);
  7270. assertArgument(initCodeHash.length === 32, "initCodeHash must be 32 bytes", "initCodeHash", _initCodeHash);
  7271. return getAddress(dataSlice(keccak256(concat(["0xff", from, salt, initCodeHash])), 12));
  7272. }
  7273. /**
  7274. * Returns true if %%value%% is an object which implements the
  7275. * [[Addressable]] interface.
  7276. *
  7277. * @example:
  7278. * // Wallets and AbstractSigner sub-classes
  7279. * isAddressable(Wallet.createRandom())
  7280. * //_result:
  7281. *
  7282. * // Contracts
  7283. * contract = new Contract("dai.tokens.ethers.eth", [ ], provider)
  7284. * isAddressable(contract)
  7285. * //_result:
  7286. */
  7287. function isAddressable(value) {
  7288. return (value && typeof (value.getAddress) === "function");
  7289. }
  7290. /**
  7291. * Returns true if %%value%% is a valid address.
  7292. *
  7293. * @example:
  7294. * // Valid address
  7295. * isAddress("0x8ba1f109551bD432803012645Ac136ddd64DBA72")
  7296. * //_result:
  7297. *
  7298. * // Valid ICAP address
  7299. * isAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36")
  7300. * //_result:
  7301. *
  7302. * // Invalid checksum
  7303. * isAddress("0x8Ba1f109551bD432803012645Ac136ddd64DBa72")
  7304. * //_result:
  7305. *
  7306. * // Invalid ICAP checksum
  7307. * isAddress("0x8Ba1f109551bD432803012645Ac136ddd64DBA72")
  7308. * //_result:
  7309. *
  7310. * // Not an address (an ENS name requires a provided and an
  7311. * // asynchronous API to access)
  7312. * isAddress("ricmoo.eth")
  7313. * //_result:
  7314. */
  7315. function isAddress(value) {
  7316. try {
  7317. getAddress(value);
  7318. return true;
  7319. }
  7320. catch (error) { }
  7321. return false;
  7322. }
  7323. async function checkAddress(target, promise) {
  7324. const result = await promise;
  7325. if (result == null || result === "0x0000000000000000000000000000000000000000") {
  7326. assert(typeof (target) !== "string", "unconfigured name", "UNCONFIGURED_NAME", { value: target });
  7327. assertArgument(false, "invalid AddressLike value; did not resolve to a value address", "target", target);
  7328. }
  7329. return getAddress(result);
  7330. }
  7331. /**
  7332. * Resolves to an address for the %%target%%, which may be any
  7333. * supported address type, an [[Addressable]] or a Promise which
  7334. * resolves to an address.
  7335. *
  7336. * If an ENS name is provided, but that name has not been correctly
  7337. * configured a [[UnconfiguredNameError]] is thrown.
  7338. *
  7339. * @example:
  7340. * addr = "0x6B175474E89094C44Da98b954EedeAC495271d0F"
  7341. *
  7342. * // Addresses are return synchronously
  7343. * resolveAddress(addr, provider)
  7344. * //_result:
  7345. *
  7346. * // Address promises are resolved asynchronously
  7347. * resolveAddress(Promise.resolve(addr))
  7348. * //_result:
  7349. *
  7350. * // ENS names are resolved asynchronously
  7351. * resolveAddress("dai.tokens.ethers.eth", provider)
  7352. * //_result:
  7353. *
  7354. * // Addressable objects are resolved asynchronously
  7355. * contract = new Contract(addr, [ ])
  7356. * resolveAddress(contract, provider)
  7357. * //_result:
  7358. *
  7359. * // Unconfigured ENS names reject
  7360. * resolveAddress("nothing-here.ricmoo.eth", provider)
  7361. * //_error:
  7362. *
  7363. * // ENS names require a NameResolver object passed in
  7364. * // (notice the provider was omitted)
  7365. * resolveAddress("nothing-here.ricmoo.eth")
  7366. * //_error:
  7367. */
  7368. function resolveAddress(target, resolver) {
  7369. if (typeof (target) === "string") {
  7370. if (target.match(/^0x[0-9a-f]{40}$/i)) {
  7371. return getAddress(target);
  7372. }
  7373. assert(resolver != null, "ENS resolution requires a provider", "UNSUPPORTED_OPERATION", { operation: "resolveName" });
  7374. return checkAddress(target, resolver.resolveName(target));
  7375. }
  7376. else if (isAddressable(target)) {
  7377. return checkAddress(target, target.getAddress());
  7378. }
  7379. else if (target && typeof (target.then) === "function") {
  7380. return checkAddress(target, target);
  7381. }
  7382. assertArgument(false, "unsupported addressable value", "target", target);
  7383. }
  7384. /**
  7385. * A Typed object allows a value to have its type explicitly
  7386. * specified.
  7387. *
  7388. * For example, in Solidity, the value ``45`` could represent a
  7389. * ``uint8`` or a ``uint256``. The value ``0x1234`` could represent
  7390. * a ``bytes2`` or ``bytes``.
  7391. *
  7392. * Since JavaScript has no meaningful way to explicitly inform any
  7393. * APIs which what the type is, this allows transparent interoperation
  7394. * with Soldity.
  7395. *
  7396. * @_subsection: api/abi:Typed Values
  7397. */
  7398. const _gaurd = {};
  7399. function n(value, width) {
  7400. let signed = false;
  7401. if (width < 0) {
  7402. signed = true;
  7403. width *= -1;
  7404. }
  7405. // @TODO: Check range is valid for value
  7406. return new Typed(_gaurd, `${signed ? "" : "u"}int${width}`, value, { signed, width });
  7407. }
  7408. function b(value, size) {
  7409. // @TODO: Check range is valid for value
  7410. return new Typed(_gaurd, `bytes${(size) ? size : ""}`, value, { size });
  7411. }
  7412. const _typedSymbol = Symbol.for("_ethers_typed");
  7413. /**
  7414. * The **Typed** class to wrap values providing explicit type information.
  7415. */
  7416. class Typed {
  7417. /**
  7418. * The type, as a Solidity-compatible type.
  7419. */
  7420. type;
  7421. /**
  7422. * The actual value.
  7423. */
  7424. value;
  7425. #options;
  7426. /**
  7427. * @_ignore:
  7428. */
  7429. _typedSymbol;
  7430. /**
  7431. * @_ignore:
  7432. */
  7433. constructor(gaurd, type, value, options) {
  7434. if (options == null) {
  7435. options = null;
  7436. }
  7437. assertPrivate(_gaurd, gaurd, "Typed");
  7438. defineProperties(this, { _typedSymbol, type, value });
  7439. this.#options = options;
  7440. // Check the value is valid
  7441. this.format();
  7442. }
  7443. /**
  7444. * Format the type as a Human-Readable type.
  7445. */
  7446. format() {
  7447. if (this.type === "array") {
  7448. throw new Error("");
  7449. }
  7450. else if (this.type === "dynamicArray") {
  7451. throw new Error("");
  7452. }
  7453. else if (this.type === "tuple") {
  7454. return `tuple(${this.value.map((v) => v.format()).join(",")})`;
  7455. }
  7456. return this.type;
  7457. }
  7458. /**
  7459. * The default value returned by this type.
  7460. */
  7461. defaultValue() {
  7462. return 0;
  7463. }
  7464. /**
  7465. * The minimum value for numeric types.
  7466. */
  7467. minValue() {
  7468. return 0;
  7469. }
  7470. /**
  7471. * The maximum value for numeric types.
  7472. */
  7473. maxValue() {
  7474. return 0;
  7475. }
  7476. /**
  7477. * Returns ``true`` and provides a type guard is this is a [[TypedBigInt]].
  7478. */
  7479. isBigInt() {
  7480. return !!(this.type.match(/^u?int[0-9]+$/));
  7481. }
  7482. /**
  7483. * Returns ``true`` and provides a type guard is this is a [[TypedData]].
  7484. */
  7485. isData() {
  7486. return this.type.startsWith("bytes");
  7487. }
  7488. /**
  7489. * Returns ``true`` and provides a type guard is this is a [[TypedString]].
  7490. */
  7491. isString() {
  7492. return (this.type === "string");
  7493. }
  7494. /**
  7495. * Returns the tuple name, if this is a tuple. Throws otherwise.
  7496. */
  7497. get tupleName() {
  7498. if (this.type !== "tuple") {
  7499. throw TypeError("not a tuple");
  7500. }
  7501. return this.#options;
  7502. }
  7503. // Returns the length of this type as an array
  7504. // - `null` indicates the length is unforced, it could be dynamic
  7505. // - `-1` indicates the length is dynamic
  7506. // - any other value indicates it is a static array and is its length
  7507. /**
  7508. * Returns the length of the array type or ``-1`` if it is dynamic.
  7509. *
  7510. * Throws if the type is not an array.
  7511. */
  7512. get arrayLength() {
  7513. if (this.type !== "array") {
  7514. throw TypeError("not an array");
  7515. }
  7516. if (this.#options === true) {
  7517. return -1;
  7518. }
  7519. if (this.#options === false) {
  7520. return (this.value).length;
  7521. }
  7522. return null;
  7523. }
  7524. /**
  7525. * Returns a new **Typed** of %%type%% with the %%value%%.
  7526. */
  7527. static from(type, value) {
  7528. return new Typed(_gaurd, type, value);
  7529. }
  7530. /**
  7531. * Return a new ``uint8`` type for %%v%%.
  7532. */
  7533. static uint8(v) { return n(v, 8); }
  7534. /**
  7535. * Return a new ``uint16`` type for %%v%%.
  7536. */
  7537. static uint16(v) { return n(v, 16); }
  7538. /**
  7539. * Return a new ``uint24`` type for %%v%%.
  7540. */
  7541. static uint24(v) { return n(v, 24); }
  7542. /**
  7543. * Return a new ``uint32`` type for %%v%%.
  7544. */
  7545. static uint32(v) { return n(v, 32); }
  7546. /**
  7547. * Return a new ``uint40`` type for %%v%%.
  7548. */
  7549. static uint40(v) { return n(v, 40); }
  7550. /**
  7551. * Return a new ``uint48`` type for %%v%%.
  7552. */
  7553. static uint48(v) { return n(v, 48); }
  7554. /**
  7555. * Return a new ``uint56`` type for %%v%%.
  7556. */
  7557. static uint56(v) { return n(v, 56); }
  7558. /**
  7559. * Return a new ``uint64`` type for %%v%%.
  7560. */
  7561. static uint64(v) { return n(v, 64); }
  7562. /**
  7563. * Return a new ``uint72`` type for %%v%%.
  7564. */
  7565. static uint72(v) { return n(v, 72); }
  7566. /**
  7567. * Return a new ``uint80`` type for %%v%%.
  7568. */
  7569. static uint80(v) { return n(v, 80); }
  7570. /**
  7571. * Return a new ``uint88`` type for %%v%%.
  7572. */
  7573. static uint88(v) { return n(v, 88); }
  7574. /**
  7575. * Return a new ``uint96`` type for %%v%%.
  7576. */
  7577. static uint96(v) { return n(v, 96); }
  7578. /**
  7579. * Return a new ``uint104`` type for %%v%%.
  7580. */
  7581. static uint104(v) { return n(v, 104); }
  7582. /**
  7583. * Return a new ``uint112`` type for %%v%%.
  7584. */
  7585. static uint112(v) { return n(v, 112); }
  7586. /**
  7587. * Return a new ``uint120`` type for %%v%%.
  7588. */
  7589. static uint120(v) { return n(v, 120); }
  7590. /**
  7591. * Return a new ``uint128`` type for %%v%%.
  7592. */
  7593. static uint128(v) { return n(v, 128); }
  7594. /**
  7595. * Return a new ``uint136`` type for %%v%%.
  7596. */
  7597. static uint136(v) { return n(v, 136); }
  7598. /**
  7599. * Return a new ``uint144`` type for %%v%%.
  7600. */
  7601. static uint144(v) { return n(v, 144); }
  7602. /**
  7603. * Return a new ``uint152`` type for %%v%%.
  7604. */
  7605. static uint152(v) { return n(v, 152); }
  7606. /**
  7607. * Return a new ``uint160`` type for %%v%%.
  7608. */
  7609. static uint160(v) { return n(v, 160); }
  7610. /**
  7611. * Return a new ``uint168`` type for %%v%%.
  7612. */
  7613. static uint168(v) { return n(v, 168); }
  7614. /**
  7615. * Return a new ``uint176`` type for %%v%%.
  7616. */
  7617. static uint176(v) { return n(v, 176); }
  7618. /**
  7619. * Return a new ``uint184`` type for %%v%%.
  7620. */
  7621. static uint184(v) { return n(v, 184); }
  7622. /**
  7623. * Return a new ``uint192`` type for %%v%%.
  7624. */
  7625. static uint192(v) { return n(v, 192); }
  7626. /**
  7627. * Return a new ``uint200`` type for %%v%%.
  7628. */
  7629. static uint200(v) { return n(v, 200); }
  7630. /**
  7631. * Return a new ``uint208`` type for %%v%%.
  7632. */
  7633. static uint208(v) { return n(v, 208); }
  7634. /**
  7635. * Return a new ``uint216`` type for %%v%%.
  7636. */
  7637. static uint216(v) { return n(v, 216); }
  7638. /**
  7639. * Return a new ``uint224`` type for %%v%%.
  7640. */
  7641. static uint224(v) { return n(v, 224); }
  7642. /**
  7643. * Return a new ``uint232`` type for %%v%%.
  7644. */
  7645. static uint232(v) { return n(v, 232); }
  7646. /**
  7647. * Return a new ``uint240`` type for %%v%%.
  7648. */
  7649. static uint240(v) { return n(v, 240); }
  7650. /**
  7651. * Return a new ``uint248`` type for %%v%%.
  7652. */
  7653. static uint248(v) { return n(v, 248); }
  7654. /**
  7655. * Return a new ``uint256`` type for %%v%%.
  7656. */
  7657. static uint256(v) { return n(v, 256); }
  7658. /**
  7659. * Return a new ``uint256`` type for %%v%%.
  7660. */
  7661. static uint(v) { return n(v, 256); }
  7662. /**
  7663. * Return a new ``int8`` type for %%v%%.
  7664. */
  7665. static int8(v) { return n(v, -8); }
  7666. /**
  7667. * Return a new ``int16`` type for %%v%%.
  7668. */
  7669. static int16(v) { return n(v, -16); }
  7670. /**
  7671. * Return a new ``int24`` type for %%v%%.
  7672. */
  7673. static int24(v) { return n(v, -24); }
  7674. /**
  7675. * Return a new ``int32`` type for %%v%%.
  7676. */
  7677. static int32(v) { return n(v, -32); }
  7678. /**
  7679. * Return a new ``int40`` type for %%v%%.
  7680. */
  7681. static int40(v) { return n(v, -40); }
  7682. /**
  7683. * Return a new ``int48`` type for %%v%%.
  7684. */
  7685. static int48(v) { return n(v, -48); }
  7686. /**
  7687. * Return a new ``int56`` type for %%v%%.
  7688. */
  7689. static int56(v) { return n(v, -56); }
  7690. /**
  7691. * Return a new ``int64`` type for %%v%%.
  7692. */
  7693. static int64(v) { return n(v, -64); }
  7694. /**
  7695. * Return a new ``int72`` type for %%v%%.
  7696. */
  7697. static int72(v) { return n(v, -72); }
  7698. /**
  7699. * Return a new ``int80`` type for %%v%%.
  7700. */
  7701. static int80(v) { return n(v, -80); }
  7702. /**
  7703. * Return a new ``int88`` type for %%v%%.
  7704. */
  7705. static int88(v) { return n(v, -88); }
  7706. /**
  7707. * Return a new ``int96`` type for %%v%%.
  7708. */
  7709. static int96(v) { return n(v, -96); }
  7710. /**
  7711. * Return a new ``int104`` type for %%v%%.
  7712. */
  7713. static int104(v) { return n(v, -104); }
  7714. /**
  7715. * Return a new ``int112`` type for %%v%%.
  7716. */
  7717. static int112(v) { return n(v, -112); }
  7718. /**
  7719. * Return a new ``int120`` type for %%v%%.
  7720. */
  7721. static int120(v) { return n(v, -120); }
  7722. /**
  7723. * Return a new ``int128`` type for %%v%%.
  7724. */
  7725. static int128(v) { return n(v, -128); }
  7726. /**
  7727. * Return a new ``int136`` type for %%v%%.
  7728. */
  7729. static int136(v) { return n(v, -136); }
  7730. /**
  7731. * Return a new ``int144`` type for %%v%%.
  7732. */
  7733. static int144(v) { return n(v, -144); }
  7734. /**
  7735. * Return a new ``int52`` type for %%v%%.
  7736. */
  7737. static int152(v) { return n(v, -152); }
  7738. /**
  7739. * Return a new ``int160`` type for %%v%%.
  7740. */
  7741. static int160(v) { return n(v, -160); }
  7742. /**
  7743. * Return a new ``int168`` type for %%v%%.
  7744. */
  7745. static int168(v) { return n(v, -168); }
  7746. /**
  7747. * Return a new ``int176`` type for %%v%%.
  7748. */
  7749. static int176(v) { return n(v, -176); }
  7750. /**
  7751. * Return a new ``int184`` type for %%v%%.
  7752. */
  7753. static int184(v) { return n(v, -184); }
  7754. /**
  7755. * Return a new ``int92`` type for %%v%%.
  7756. */
  7757. static int192(v) { return n(v, -192); }
  7758. /**
  7759. * Return a new ``int200`` type for %%v%%.
  7760. */
  7761. static int200(v) { return n(v, -200); }
  7762. /**
  7763. * Return a new ``int208`` type for %%v%%.
  7764. */
  7765. static int208(v) { return n(v, -208); }
  7766. /**
  7767. * Return a new ``int216`` type for %%v%%.
  7768. */
  7769. static int216(v) { return n(v, -216); }
  7770. /**
  7771. * Return a new ``int224`` type for %%v%%.
  7772. */
  7773. static int224(v) { return n(v, -224); }
  7774. /**
  7775. * Return a new ``int232`` type for %%v%%.
  7776. */
  7777. static int232(v) { return n(v, -232); }
  7778. /**
  7779. * Return a new ``int240`` type for %%v%%.
  7780. */
  7781. static int240(v) { return n(v, -240); }
  7782. /**
  7783. * Return a new ``int248`` type for %%v%%.
  7784. */
  7785. static int248(v) { return n(v, -248); }
  7786. /**
  7787. * Return a new ``int256`` type for %%v%%.
  7788. */
  7789. static int256(v) { return n(v, -256); }
  7790. /**
  7791. * Return a new ``int256`` type for %%v%%.
  7792. */
  7793. static int(v) { return n(v, -256); }
  7794. /**
  7795. * Return a new ``bytes1`` type for %%v%%.
  7796. */
  7797. static bytes1(v) { return b(v, 1); }
  7798. /**
  7799. * Return a new ``bytes2`` type for %%v%%.
  7800. */
  7801. static bytes2(v) { return b(v, 2); }
  7802. /**
  7803. * Return a new ``bytes3`` type for %%v%%.
  7804. */
  7805. static bytes3(v) { return b(v, 3); }
  7806. /**
  7807. * Return a new ``bytes4`` type for %%v%%.
  7808. */
  7809. static bytes4(v) { return b(v, 4); }
  7810. /**
  7811. * Return a new ``bytes5`` type for %%v%%.
  7812. */
  7813. static bytes5(v) { return b(v, 5); }
  7814. /**
  7815. * Return a new ``bytes6`` type for %%v%%.
  7816. */
  7817. static bytes6(v) { return b(v, 6); }
  7818. /**
  7819. * Return a new ``bytes7`` type for %%v%%.
  7820. */
  7821. static bytes7(v) { return b(v, 7); }
  7822. /**
  7823. * Return a new ``bytes8`` type for %%v%%.
  7824. */
  7825. static bytes8(v) { return b(v, 8); }
  7826. /**
  7827. * Return a new ``bytes9`` type for %%v%%.
  7828. */
  7829. static bytes9(v) { return b(v, 9); }
  7830. /**
  7831. * Return a new ``bytes10`` type for %%v%%.
  7832. */
  7833. static bytes10(v) { return b(v, 10); }
  7834. /**
  7835. * Return a new ``bytes11`` type for %%v%%.
  7836. */
  7837. static bytes11(v) { return b(v, 11); }
  7838. /**
  7839. * Return a new ``bytes12`` type for %%v%%.
  7840. */
  7841. static bytes12(v) { return b(v, 12); }
  7842. /**
  7843. * Return a new ``bytes13`` type for %%v%%.
  7844. */
  7845. static bytes13(v) { return b(v, 13); }
  7846. /**
  7847. * Return a new ``bytes14`` type for %%v%%.
  7848. */
  7849. static bytes14(v) { return b(v, 14); }
  7850. /**
  7851. * Return a new ``bytes15`` type for %%v%%.
  7852. */
  7853. static bytes15(v) { return b(v, 15); }
  7854. /**
  7855. * Return a new ``bytes16`` type for %%v%%.
  7856. */
  7857. static bytes16(v) { return b(v, 16); }
  7858. /**
  7859. * Return a new ``bytes17`` type for %%v%%.
  7860. */
  7861. static bytes17(v) { return b(v, 17); }
  7862. /**
  7863. * Return a new ``bytes18`` type for %%v%%.
  7864. */
  7865. static bytes18(v) { return b(v, 18); }
  7866. /**
  7867. * Return a new ``bytes19`` type for %%v%%.
  7868. */
  7869. static bytes19(v) { return b(v, 19); }
  7870. /**
  7871. * Return a new ``bytes20`` type for %%v%%.
  7872. */
  7873. static bytes20(v) { return b(v, 20); }
  7874. /**
  7875. * Return a new ``bytes21`` type for %%v%%.
  7876. */
  7877. static bytes21(v) { return b(v, 21); }
  7878. /**
  7879. * Return a new ``bytes22`` type for %%v%%.
  7880. */
  7881. static bytes22(v) { return b(v, 22); }
  7882. /**
  7883. * Return a new ``bytes23`` type for %%v%%.
  7884. */
  7885. static bytes23(v) { return b(v, 23); }
  7886. /**
  7887. * Return a new ``bytes24`` type for %%v%%.
  7888. */
  7889. static bytes24(v) { return b(v, 24); }
  7890. /**
  7891. * Return a new ``bytes25`` type for %%v%%.
  7892. */
  7893. static bytes25(v) { return b(v, 25); }
  7894. /**
  7895. * Return a new ``bytes26`` type for %%v%%.
  7896. */
  7897. static bytes26(v) { return b(v, 26); }
  7898. /**
  7899. * Return a new ``bytes27`` type for %%v%%.
  7900. */
  7901. static bytes27(v) { return b(v, 27); }
  7902. /**
  7903. * Return a new ``bytes28`` type for %%v%%.
  7904. */
  7905. static bytes28(v) { return b(v, 28); }
  7906. /**
  7907. * Return a new ``bytes29`` type for %%v%%.
  7908. */
  7909. static bytes29(v) { return b(v, 29); }
  7910. /**
  7911. * Return a new ``bytes30`` type for %%v%%.
  7912. */
  7913. static bytes30(v) { return b(v, 30); }
  7914. /**
  7915. * Return a new ``bytes31`` type for %%v%%.
  7916. */
  7917. static bytes31(v) { return b(v, 31); }
  7918. /**
  7919. * Return a new ``bytes32`` type for %%v%%.
  7920. */
  7921. static bytes32(v) { return b(v, 32); }
  7922. /**
  7923. * Return a new ``address`` type for %%v%%.
  7924. */
  7925. static address(v) { return new Typed(_gaurd, "address", v); }
  7926. /**
  7927. * Return a new ``bool`` type for %%v%%.
  7928. */
  7929. static bool(v) { return new Typed(_gaurd, "bool", !!v); }
  7930. /**
  7931. * Return a new ``bytes`` type for %%v%%.
  7932. */
  7933. static bytes(v) { return new Typed(_gaurd, "bytes", v); }
  7934. /**
  7935. * Return a new ``string`` type for %%v%%.
  7936. */
  7937. static string(v) { return new Typed(_gaurd, "string", v); }
  7938. /**
  7939. * Return a new ``array`` type for %%v%%, allowing %%dynamic%% length.
  7940. */
  7941. static array(v, dynamic) {
  7942. throw new Error("not implemented yet");
  7943. }
  7944. /**
  7945. * Return a new ``tuple`` type for %%v%%, with the optional %%name%%.
  7946. */
  7947. static tuple(v, name) {
  7948. throw new Error("not implemented yet");
  7949. }
  7950. /**
  7951. * Return a new ``uint8`` type for %%v%%.
  7952. */
  7953. static overrides(v) {
  7954. return new Typed(_gaurd, "overrides", Object.assign({}, v));
  7955. }
  7956. /**
  7957. * Returns true only if %%value%% is a [[Typed]] instance.
  7958. */
  7959. static isTyped(value) {
  7960. return (value
  7961. && typeof (value) === "object"
  7962. && "_typedSymbol" in value
  7963. && value._typedSymbol === _typedSymbol);
  7964. }
  7965. /**
  7966. * If the value is a [[Typed]] instance, validates the underlying value
  7967. * and returns it, otherwise returns value directly.
  7968. *
  7969. * This is useful for functions that with to accept either a [[Typed]]
  7970. * object or values.
  7971. */
  7972. static dereference(value, type) {
  7973. if (Typed.isTyped(value)) {
  7974. if (value.type !== type) {
  7975. throw new Error(`invalid type: expecetd ${type}, got ${value.type}`);
  7976. }
  7977. return value.value;
  7978. }
  7979. return value;
  7980. }
  7981. }
  7982. /**
  7983. * @_ignore
  7984. */
  7985. class AddressCoder extends Coder {
  7986. constructor(localName) {
  7987. super("address", "address", localName, false);
  7988. }
  7989. defaultValue() {
  7990. return "0x0000000000000000000000000000000000000000";
  7991. }
  7992. encode(writer, _value) {
  7993. let value = Typed.dereference(_value, "string");
  7994. try {
  7995. value = getAddress(value);
  7996. }
  7997. catch (error) {
  7998. return this._throwError(error.message, _value);
  7999. }
  8000. return writer.writeValue(value);
  8001. }
  8002. decode(reader) {
  8003. return getAddress(toBeHex(reader.readValue(), 20));
  8004. }
  8005. }
  8006. /**
  8007. * Clones the functionality of an existing Coder, but without a localName
  8008. *
  8009. * @_ignore
  8010. */
  8011. class AnonymousCoder extends Coder {
  8012. coder;
  8013. constructor(coder) {
  8014. super(coder.name, coder.type, "_", coder.dynamic);
  8015. this.coder = coder;
  8016. }
  8017. defaultValue() {
  8018. return this.coder.defaultValue();
  8019. }
  8020. encode(writer, value) {
  8021. return this.coder.encode(writer, value);
  8022. }
  8023. decode(reader) {
  8024. return this.coder.decode(reader);
  8025. }
  8026. }
  8027. /**
  8028. * @_ignore
  8029. */
  8030. function pack(writer, coders, values) {
  8031. let arrayValues = [];
  8032. if (Array.isArray(values)) {
  8033. arrayValues = values;
  8034. }
  8035. else if (values && typeof (values) === "object") {
  8036. let unique = {};
  8037. arrayValues = coders.map((coder) => {
  8038. const name = coder.localName;
  8039. assert(name, "cannot encode object for signature with missing names", "INVALID_ARGUMENT", { argument: "values", info: { coder }, value: values });
  8040. assert(!unique[name], "cannot encode object for signature with duplicate names", "INVALID_ARGUMENT", { argument: "values", info: { coder }, value: values });
  8041. unique[name] = true;
  8042. return values[name];
  8043. });
  8044. }
  8045. else {
  8046. assertArgument(false, "invalid tuple value", "tuple", values);
  8047. }
  8048. assertArgument(coders.length === arrayValues.length, "types/value length mismatch", "tuple", values);
  8049. let staticWriter = new Writer();
  8050. let dynamicWriter = new Writer();
  8051. let updateFuncs = [];
  8052. coders.forEach((coder, index) => {
  8053. let value = arrayValues[index];
  8054. if (coder.dynamic) {
  8055. // Get current dynamic offset (for the future pointer)
  8056. let dynamicOffset = dynamicWriter.length;
  8057. // Encode the dynamic value into the dynamicWriter
  8058. coder.encode(dynamicWriter, value);
  8059. // Prepare to populate the correct offset once we are done
  8060. let updateFunc = staticWriter.writeUpdatableValue();
  8061. updateFuncs.push((baseOffset) => {
  8062. updateFunc(baseOffset + dynamicOffset);
  8063. });
  8064. }
  8065. else {
  8066. coder.encode(staticWriter, value);
  8067. }
  8068. });
  8069. // Backfill all the dynamic offsets, now that we know the static length
  8070. updateFuncs.forEach((func) => { func(staticWriter.length); });
  8071. let length = writer.appendWriter(staticWriter);
  8072. length += writer.appendWriter(dynamicWriter);
  8073. return length;
  8074. }
  8075. /**
  8076. * @_ignore
  8077. */
  8078. function unpack(reader, coders) {
  8079. let values = [];
  8080. let keys = [];
  8081. // A reader anchored to this base
  8082. let baseReader = reader.subReader(0);
  8083. coders.forEach((coder) => {
  8084. let value = null;
  8085. if (coder.dynamic) {
  8086. let offset = reader.readIndex();
  8087. let offsetReader = baseReader.subReader(offset);
  8088. try {
  8089. value = coder.decode(offsetReader);
  8090. }
  8091. catch (error) {
  8092. // Cannot recover from this
  8093. if (isError(error, "BUFFER_OVERRUN")) {
  8094. throw error;
  8095. }
  8096. value = error;
  8097. value.baseType = coder.name;
  8098. value.name = coder.localName;
  8099. value.type = coder.type;
  8100. }
  8101. }
  8102. else {
  8103. try {
  8104. value = coder.decode(reader);
  8105. }
  8106. catch (error) {
  8107. // Cannot recover from this
  8108. if (isError(error, "BUFFER_OVERRUN")) {
  8109. throw error;
  8110. }
  8111. value = error;
  8112. value.baseType = coder.name;
  8113. value.name = coder.localName;
  8114. value.type = coder.type;
  8115. }
  8116. }
  8117. if (value == undefined) {
  8118. throw new Error("investigate");
  8119. }
  8120. values.push(value);
  8121. keys.push(coder.localName || null);
  8122. });
  8123. return Result.fromItems(values, keys);
  8124. }
  8125. /**
  8126. * @_ignore
  8127. */
  8128. class ArrayCoder extends Coder {
  8129. coder;
  8130. length;
  8131. constructor(coder, length, localName) {
  8132. const type = (coder.type + "[" + (length >= 0 ? length : "") + "]");
  8133. const dynamic = (length === -1 || coder.dynamic);
  8134. super("array", type, localName, dynamic);
  8135. defineProperties(this, { coder, length });
  8136. }
  8137. defaultValue() {
  8138. // Verifies the child coder is valid (even if the array is dynamic or 0-length)
  8139. const defaultChild = this.coder.defaultValue();
  8140. const result = [];
  8141. for (let i = 0; i < this.length; i++) {
  8142. result.push(defaultChild);
  8143. }
  8144. return result;
  8145. }
  8146. encode(writer, _value) {
  8147. const value = Typed.dereference(_value, "array");
  8148. if (!Array.isArray(value)) {
  8149. this._throwError("expected array value", value);
  8150. }
  8151. let count = this.length;
  8152. if (count === -1) {
  8153. count = value.length;
  8154. writer.writeValue(value.length);
  8155. }
  8156. assertArgumentCount(value.length, count, "coder array" + (this.localName ? (" " + this.localName) : ""));
  8157. let coders = [];
  8158. for (let i = 0; i < value.length; i++) {
  8159. coders.push(this.coder);
  8160. }
  8161. return pack(writer, coders, value);
  8162. }
  8163. decode(reader) {
  8164. let count = this.length;
  8165. if (count === -1) {
  8166. count = reader.readIndex();
  8167. // Check that there is *roughly* enough data to ensure
  8168. // stray random data is not being read as a length. Each
  8169. // slot requires at least 32 bytes for their value (or 32
  8170. // bytes as a link to the data). This could use a much
  8171. // tighter bound, but we are erroring on the side of safety.
  8172. assert(count * WordSize <= reader.dataLength, "insufficient data length", "BUFFER_OVERRUN", { buffer: reader.bytes, offset: count * WordSize, length: reader.dataLength });
  8173. }
  8174. let coders = [];
  8175. for (let i = 0; i < count; i++) {
  8176. coders.push(new AnonymousCoder(this.coder));
  8177. }
  8178. return unpack(reader, coders);
  8179. }
  8180. }
  8181. /**
  8182. * @_ignore
  8183. */
  8184. class BooleanCoder extends Coder {
  8185. constructor(localName) {
  8186. super("bool", "bool", localName, false);
  8187. }
  8188. defaultValue() {
  8189. return false;
  8190. }
  8191. encode(writer, _value) {
  8192. const value = Typed.dereference(_value, "bool");
  8193. return writer.writeValue(value ? 1 : 0);
  8194. }
  8195. decode(reader) {
  8196. return !!reader.readValue();
  8197. }
  8198. }
  8199. /**
  8200. * @_ignore
  8201. */
  8202. class DynamicBytesCoder extends Coder {
  8203. constructor(type, localName) {
  8204. super(type, type, localName, true);
  8205. }
  8206. defaultValue() {
  8207. return "0x";
  8208. }
  8209. encode(writer, value) {
  8210. value = getBytesCopy(value);
  8211. let length = writer.writeValue(value.length);
  8212. length += writer.writeBytes(value);
  8213. return length;
  8214. }
  8215. decode(reader) {
  8216. return reader.readBytes(reader.readIndex(), true);
  8217. }
  8218. }
  8219. /**
  8220. * @_ignore
  8221. */
  8222. class BytesCoder extends DynamicBytesCoder {
  8223. constructor(localName) {
  8224. super("bytes", localName);
  8225. }
  8226. decode(reader) {
  8227. return hexlify(super.decode(reader));
  8228. }
  8229. }
  8230. /**
  8231. * @_ignore
  8232. */
  8233. class FixedBytesCoder extends Coder {
  8234. size;
  8235. constructor(size, localName) {
  8236. let name = "bytes" + String(size);
  8237. super(name, name, localName, false);
  8238. defineProperties(this, { size }, { size: "number" });
  8239. }
  8240. defaultValue() {
  8241. return ("0x0000000000000000000000000000000000000000000000000000000000000000").substring(0, 2 + this.size * 2);
  8242. }
  8243. encode(writer, _value) {
  8244. let data = getBytesCopy(Typed.dereference(_value, this.type));
  8245. if (data.length !== this.size) {
  8246. this._throwError("incorrect data length", _value);
  8247. }
  8248. return writer.writeBytes(data);
  8249. }
  8250. decode(reader) {
  8251. return hexlify(reader.readBytes(this.size));
  8252. }
  8253. }
  8254. const Empty = new Uint8Array([]);
  8255. /**
  8256. * @_ignore
  8257. */
  8258. class NullCoder extends Coder {
  8259. constructor(localName) {
  8260. super("null", "", localName, false);
  8261. }
  8262. defaultValue() {
  8263. return null;
  8264. }
  8265. encode(writer, value) {
  8266. if (value != null) {
  8267. this._throwError("not null", value);
  8268. }
  8269. return writer.writeBytes(Empty);
  8270. }
  8271. decode(reader) {
  8272. reader.readBytes(0);
  8273. return null;
  8274. }
  8275. }
  8276. const BN_0$5 = BigInt(0);
  8277. const BN_1$2 = BigInt(1);
  8278. const BN_MAX_UINT256$1 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
  8279. /**
  8280. * @_ignore
  8281. */
  8282. class NumberCoder extends Coder {
  8283. size;
  8284. signed;
  8285. constructor(size, signed, localName) {
  8286. const name = ((signed ? "int" : "uint") + (size * 8));
  8287. super(name, name, localName, false);
  8288. defineProperties(this, { size, signed }, { size: "number", signed: "boolean" });
  8289. }
  8290. defaultValue() {
  8291. return 0;
  8292. }
  8293. encode(writer, _value) {
  8294. let value = getBigInt(Typed.dereference(_value, this.type));
  8295. // Check bounds are safe for encoding
  8296. let maxUintValue = mask(BN_MAX_UINT256$1, WordSize * 8);
  8297. if (this.signed) {
  8298. let bounds = mask(maxUintValue, (this.size * 8) - 1);
  8299. if (value > bounds || value < -(bounds + BN_1$2)) {
  8300. this._throwError("value out-of-bounds", _value);
  8301. }
  8302. value = toTwos(value, 8 * WordSize);
  8303. }
  8304. else if (value < BN_0$5 || value > mask(maxUintValue, this.size * 8)) {
  8305. this._throwError("value out-of-bounds", _value);
  8306. }
  8307. return writer.writeValue(value);
  8308. }
  8309. decode(reader) {
  8310. let value = mask(reader.readValue(), this.size * 8);
  8311. if (this.signed) {
  8312. value = fromTwos(value, this.size * 8);
  8313. }
  8314. return value;
  8315. }
  8316. }
  8317. /**
  8318. * @_ignore
  8319. */
  8320. class StringCoder extends DynamicBytesCoder {
  8321. constructor(localName) {
  8322. super("string", localName);
  8323. }
  8324. defaultValue() {
  8325. return "";
  8326. }
  8327. encode(writer, _value) {
  8328. return super.encode(writer, toUtf8Bytes(Typed.dereference(_value, "string")));
  8329. }
  8330. decode(reader) {
  8331. return toUtf8String(super.decode(reader));
  8332. }
  8333. }
  8334. /**
  8335. * @_ignore
  8336. */
  8337. class TupleCoder extends Coder {
  8338. coders;
  8339. constructor(coders, localName) {
  8340. let dynamic = false;
  8341. const types = [];
  8342. coders.forEach((coder) => {
  8343. if (coder.dynamic) {
  8344. dynamic = true;
  8345. }
  8346. types.push(coder.type);
  8347. });
  8348. const type = ("tuple(" + types.join(",") + ")");
  8349. super("tuple", type, localName, dynamic);
  8350. defineProperties(this, { coders: Object.freeze(coders.slice()) });
  8351. }
  8352. defaultValue() {
  8353. const values = [];
  8354. this.coders.forEach((coder) => {
  8355. values.push(coder.defaultValue());
  8356. });
  8357. // We only output named properties for uniquely named coders
  8358. const uniqueNames = this.coders.reduce((accum, coder) => {
  8359. const name = coder.localName;
  8360. if (name) {
  8361. if (!accum[name]) {
  8362. accum[name] = 0;
  8363. }
  8364. accum[name]++;
  8365. }
  8366. return accum;
  8367. }, {});
  8368. // Add named values
  8369. this.coders.forEach((coder, index) => {
  8370. let name = coder.localName;
  8371. if (!name || uniqueNames[name] !== 1) {
  8372. return;
  8373. }
  8374. if (name === "length") {
  8375. name = "_length";
  8376. }
  8377. if (values[name] != null) {
  8378. return;
  8379. }
  8380. values[name] = values[index];
  8381. });
  8382. return Object.freeze(values);
  8383. }
  8384. encode(writer, _value) {
  8385. const value = Typed.dereference(_value, "tuple");
  8386. return pack(writer, this.coders, value);
  8387. }
  8388. decode(reader) {
  8389. return unpack(reader, this.coders);
  8390. }
  8391. }
  8392. /**
  8393. * A simple hashing function which operates on UTF-8 strings to
  8394. * compute an 32-byte identifier.
  8395. *
  8396. * This simply computes the [UTF-8 bytes](toUtf8Bytes) and computes
  8397. * the [[keccak256]].
  8398. *
  8399. * @example:
  8400. * id("hello world")
  8401. * //_result:
  8402. */
  8403. function id(value) {
  8404. return keccak256(toUtf8Bytes(value));
  8405. }
  8406. // created 2023-09-25T01:01:55.148Z
  8407. // compressed base64-encoded blob for include-ens data
  8408. // source: https://github.com/adraffy/ens-normalize.js/blob/main/src/make.js
  8409. // see: https://github.com/adraffy/ens-normalize.js#security
  8410. // SHA-256: 0565ed049b9cf1614bb9e11ba7d8ac6a6fb96c893253d890f7e2b2884b9ded32
  8411. var COMPRESSED$1 = 'AEEUdwmgDS8BxQKKAP4BOgDjATAAngDUAIMAoABoAOAAagCOAEQAhABMAHIAOwA9ACsANgAmAGIAHgAuACgAJwAXAC0AGgAjAB8ALwAUACkAEgAeAAkAGwARABkAFgA5ACgALQArADcAFQApABAAHgAiABAAGgAeABMAGAUhBe8BFxREN8sF2wC5AK5HAW8ArQkDzQCuhzc3NzcBP68NEfMABQdHBuw5BV8FYAA9MzkI9r4ZBg7QyQAWA9CeOwLNCjcCjqkChuA/lm+RAsXTAoP6ASfnEQDytQFJAjWVCkeXAOsA6godAB/cwdAUE0WlBCN/AQUCQRjFD/MRBjHxDQSJbw0jBzUAswBxme+tnIcAYwabAysG8QAjAEMMmxcDqgPKQyDXCMMxA7kUQwD3NXOrAKmFIAAfBC0D3x4BJQDBGdUFAhEgVD8JnwmQJiNWYUzrg0oAGwAUAB0AFnNcACkAFgBP9h3gPfsDOWDKneY2ChglX1UDYD30ABsAFAAdABZzIGRAnwDD8wAjAEEMzRbDqgMB2sAFYwXqAtCnAsS4AwpUJKRtFHsadUz9AMMVbwLpABM1NJEX0ZkCgYMBEyMAxRVvAukAEzUBUFAtmUwSAy4DBTER33EftQHfSwB5MxJ/AjkWKQLzL8E/cwBB6QH9LQDPDtO9ASNriQC5DQANAwCK21EFI91zHwCoL9kBqQcHBwcHKzUDowBvAQohPvU3fAQgHwCyAc8CKQMA5zMSezr7ULgFmDp/LzVQBgEGAi8FYQVgt8AFcTtlQhpCWEmfe5tmZ6IAExsDzQ8t+X8rBKtTAltbAn0jsy8Bl6utPWMDTR8Ei2kRANkDBrNHNysDBzECQWUAcwFpJ3kAiyUhAJ0BUb8AL3EfAbfNAz81KUsFWwF3YQZtAm0A+VEfAzEJDQBRSQCzAQBlAHsAM70GD/v3IZWHBwARKQAxALsjTwHZAeMPEzmXgIHwABIAGQA8AEUAQDt3gdvIEGcQZAkGTRFMdEIVEwK0D64L7REdDNkq09PgADSxB/MDWwfzA1sDWwfzB/MDWwfzA1sDWwNbA1scEvAi28gQZw9QBHUFlgWTBN4IiyZREYkHMAjaVBV0JhxPA00BBCMtSSQ7mzMTJUpMFE0LCAQ2SmyvfUADTzGzVP2QqgPTMlc5dAkGHnkSqAAyD3skNb1OhnpPcagKU0+2tYdJak5vAsY6sEAACikJm2/Dd1YGRRAfJ6kQ+ww3AbkBPw3xS9wE9QY/BM0fgRkdD9GVoAipLeEM8SbnLqWAXiP5KocF8Uv4POELUVFsD10LaQnnOmeBUgMlAREijwrhDT0IcRD3Cs1vDekRSQc9A9lJngCpBwULFR05FbkmFGKwCw05ewb/GvoLkyazEy17AAXXGiUGUQEtGwMA0y7rhbRaNVwgT2MGBwspI8sUrFAkDSlAu3hMGh8HGSWtApVDdEqLUToelyH6PEENai4XUYAH+TwJGVMLhTyiRq9FEhHWPpE9TCJNTDAEOYMsMyePCdMPiQy9fHYBXQklCbUMdRM1ERs3yQg9Bx0xlygnGQglRplgngT7owP3E9UDDwVDCUUHFwO5HDETMhUtBRGBKNsC9zbZLrcCk1aEARsFzw8pH+MQVEfkDu0InwJpA4cl7wAxFSUAGyKfCEdnAGOP3FMJLs8Iy2pwI3gDaxTrZRF3B5UOWwerHDcVwxzlcMxeD4YMKKezCV8BeQmdAWME5wgNNV+MpCBFZ1eLXBifIGVBQ14AAjUMaRWjRMGHfAKPD28SHwE5AXcHPQ0FAnsR8RFvEJkI74YINbkz/DopBFMhhyAVCisDU2zSCysm/Qz8bQGnEmYDEDRBd/Jnr2C6KBgBBx0yyUFkIfULlk/RDKAaxRhGVDIZ6AfDA/ca9yfuQVsGAwOnBxc6UTPyBMELbQiPCUMATQ6nGwfbGG4KdYzUATWPAbudA1uVhwJzkwY7Bw8Aaw+LBX3pACECqwinAAkA0wNbAD0CsQehAB0AiUUBQQMrMwEl6QKTA5cINc8BmTMB9y0EH8cMGQD7O25OAsO1AoBuZqYF4VwCkgJNOQFRKQQJUktVA7N15QDfAE8GF+NLARmvTs8e50cB43MvAMsA/wAJOQcJRQHRAfdxALsBYws1Caa3uQFR7S0AhwAZbwHbAo0A4QA5AIP1AVcAUQVd/QXXAlNNARU1HC9bZQG/AyMBNwERAH0Gz5GpzQsjBHEH1wIQHxXlAu8yB7kFAyLjE9FCyQK94lkAMhoKPAqrCqpgX2Q3CjV2PVQAEh+sPss/UgVVO1c7XDtXO1w7VztcO1c7XDtXO1wDm8Pmw+YKcF9JYe8Mqg3YRMw6TRPfYFVgNhPMLbsUxRXSJVoZQRrAJwkl6FUNDwgt12Y0CDA0eRfAAEMpbINFY4oeNApPHOtTlVT8LR8AtUumM7MNsBsZREQFS3XxYi4WEgomAmSFAmJGX1GzAV83JAKh+wJonAJmDQKfiDgfDwJmPwJmKgRyBIMDfxcDfpY5Cjl7GzmGOicnAmwhAjI6OA4CbcsCbbLzjgM3a0kvAWsA4gDlAE4JB5wMkQECD8YAEbkCdzMCdqZDAnlPRwJ4viFg30WyRvcCfEMCeswCfQ0CfPRIBEiBZygALxlJXEpfGRtK0ALRBQLQ0EsrA4hTA4fqRMmRNgLypV0HAwOyS9JMMSkH001QTbMCi0MCitzFHwshR2sJuwKOOwKOYESbhQKO3QKOYHxRuFM5AQ5S2FSJApP/ApMQAO0AIFUiVbNV1AosHymZijLleGpFPz0Cl6MC77ZYJawAXSkClpMCloCgAK1ZsFoNhVEAPwKWuQKWUlxIXNUCmc8CmWhczl0LHQKcnznGOqECnBoCn58CnryOACETNS4TAp31Ap6WALlBYThh8wKe1wKgcgGtAp6jIwKeUqljzGQrKS8CJ7MCJoICoP8CoFDbAqYzAqXSAqgDAIECp/ZogGi1AAdNaiBq1QKs5wKssgKtawKtBgJXIQJV4AKx5dsDH1JsmwKywRECsuwbbORtZ21MYwMl0QK2YD9DbpQDKUkCuGICuUsZArkue3A6cOUCvR0DLbYDMhUCvoxyBgMzdQK+HnMmc1MCw88CwwhzhnRPOUl05AM8qwEDPJ4DPcMCxYACxksCxhSNAshtVQLISALJUwLJMgJkoQLd1nh9ZXiyeSlL1AMYp2cGAmH4GfeVKHsPXpZevxUCz28Cz3AzT1fW9xejAMqxAs93AS3uA04Wfk8JAtwrAtuOAtJTA1JgA1NjAQUDVZCAjUMEzxrxZEl5A4LSg5EC2ssC2eKEFIRNp0ADhqkAMwNkEoZ1Xf0AWQLfaQLevHd7AuIz7RgB8zQrAfSfAfLWiwLr9wLpdH0DAur9AuroAP1LAb0C7o0C66CWrpcHAu5DA4XkmH1w5HGlAvMHAG0DjhqZlwL3FwORcgOSiwL3nAL53QL4apogmq+/O5siA52HAv7+AR8APZ8gAZ+3AwWRA6ZuA6bdANXJAwZuoYyiCQ0DDE0BEwEjB3EGZb1rCQC/BG/DFY8etxEAG3k9ACcDNxJRA42DAWcrJQCM8wAlAOanC6OVCLsGI6fJBgCvBRnDBvElRUYFFoAFcD9GSDNCKUK8X3kZX8QAls0FOgCQVCGbwTsuYDoZutcONxjOGJHJ/gVfBWAFXwVgBWsFYAVfBWAFXwVgBV8FYAVfBWBOHQjfjW8KCgoKbF7xMwTRA7kGN8PDAMMEr8MA70gxFroFTj5xPnhCR0K+X30/X/AAWBkzswCNBsxzzASm70aCRS4rDDMeLz49fnXfcsH5GcoscQFz13Y4HwVnBXLJycnACNdRYwgICAqEXoWTxgA7P4kACxbZBu21Kw0AjMsTAwkVAOVtJUUsJ1JCuULESUArXy9gPi9AKwnJRQYKTD9LPoA+iT54PnkCkULEUUpDX9NWV3JVEjQAc1w3A3IBE3YnX+g7QiMJb6MKaiszRCUuQrNCxDPMCcwEX9EWJzYREBEEBwIHKn6l33JCNVIfybPJtAltydPUCmhBZw/tEKsZAJOVJU1CLRuxbUHOQAo7P0s+eEJHHA8SJVRPdGM0NVrpvBoKhfUlM0JHHGUQUhEWO1xLSj8MO0ucNAqJIzVCRxv9EFsqKyA4OQgNj2nwZgp5ZNFgE2A1K3YHS2AhQQojJmC7DgpzGG1WYFUZCQYHZO9gHWCdYIVgu2BTYJlwFh8GvRbcXbG8YgtDHrMBwzPVyQonHQgkCyYBgQJ0Ajc4nVqIAwGSCsBPIgDsK3SWEtIVBa5N8gGjAo+kVwVIZwD/AEUSCDweX4ITrRQsJ8K3TwBXFDwEAB0TvzVcAtoTS20RIwDgVgZ9BBImYgA5AL4Coi8LFnezOkCnIQFjAY4KBAPh9RcGsgZSBsEAJctdsWIRu2kTkQstRw7DAcMBKgpPBGIGMDAwKCYnKTQaLg4AKRSVAFwCdl+YUZ0JdicFD3lPAdt1F9ZZKCGxuE3yBxkFVGcA/wBFEgiCBwAOLHQSjxOtQDg1z7deFRMAZ8QTAGtKb1ApIiPHADkAvgKiLy1DFtYCmBiDAlDDWNB0eo7fpaMO/aEVRRv0ATEQZBIODyMEAc8JQhCbDRgzFD4TAEMAu9YBCgCsAOkAm5I3ABwAYxvONnR+MhXJAxgKQyxL2+kkJhMbhQKDBMkSsvF0AD9BNQ6uQC7WqSQHwxEAEEIu1hkhAH2z4iQPwyJPHNWpdyYBRSpnJALzoBAEVPPsH20MxA0CCEQKRgAFyAtFAlMNwwjEDUQJRArELtapMg7DDZgJIw+TGukEIwvDFkMAqAtDEMMMBhioe+QAO3MMRAACrgnEBSPY9Q0FDnbSBoMAB8MSYxkSxAEJAPIJAAB8FWMOFtMc/HcXwxhDAC7DAvOowwAewwJdKDKHAAHDAALrFUQVwwAbwyvzpWMWv8wA/ABpAy++bcYDUKPD0KhDCwKmJ1MAAmMA5+UZwxAagwipBRL/eADfw6fDGOMCGsOjk3l6BwOpo4sAEsMOGxMAA5sAbcMOAAvDp0MJGkMDwgipnNIPAwfIqUMGAOGDAAPzABXDAAcDAAnDAGmTABrDAA7DChjDjnEWAwABYwAOcwAuUyYABsMAF8MIKQANUgC6wy4AA8MADqMq8wCyYgAcIwAB8wqpAAXOCx0V4wAHowBCwwEKAGnDAAuDAB3DAAjDCakABdIAbqcZ3QCZCCkABdIAAAFDAAfjAB2jCCkABqIACYMAGzMAbSMA5sOIAAhjAAhDABTDBAkpAAbSAOOTAAlDC6kOzPtnAAdDAG6kQFAATwAKwwwAA0MACbUDPwAHIwAZgwACE6cDAAojAApDAAoDp/MGwwAJIwADEwAQQwgAFEMAEXMAD5MADfMADcMAGRMOFiMAFUMAbqMWuwHDAMIAE0MLAGkzEgDhUwACQwAEWgAXgwUjAAbYABjDBSYBgzBaAEFNALcQBxUMegAwMngBrA0IZgJ0KxQHBREPd1N0ZzKRJwaIHAZqNT4DqQq8BwngAB4DAwt2AX56T1ocKQNXAh1GATQGC3tOxYNagkgAMQA5CQADAQEAWxLjAIOYNAEzAH7tFRk6TglSAF8NAAlYAQ+S1ACAQwQorQBiAN4dAJ1wPyeTANVzuQDX3AIeEMp9eyMgXiUAEdkBkJizKltbVVAaRMqRAAEAhyQ/SDEz6BmfVwB6ATEsOClKIRcDOF0E/832AFNt5AByAnkCRxGCOs94NjXdAwINGBonDBwPALW2AwICAgAAAAAAAAYDBQMDARrUAwAtAAAAAgEGBgYGBgYFBQUFBQUEBQYHCAkEBQUFBQQAAAICAAAAIgCNAJAAlT0A6gC7ANwApEQAwgCyAK0AqADuAKYA2gCjAOcBCAEDAMcAgQBiANIA1AEDAN4A8gCQAKkBMQDqAN8A3AsBCQ8yO9ra2tq8xuLT1tRJOB0BUgFcNU0BWgFpAWgBWwFMUUlLbhMBUxsNEAs6PhMOACcUKy0vMj5AQENDQ0RFFEYGJFdXV1dZWVhZL1pbXVxcI2NnZ2ZoZypsbnZ1eHh4eHh4enp6enp6enp6enp8fH18e2IARPIASQCaAHgAMgBm+ACOAFcAVwA3AnbvAIsABfj4AGQAk/IAnwBPAGIAZP//sACFAIUAaQBWALEAJAC2AIMCQAJDAPwA5wD+AP4A6AD/AOkA6QDoAOYALwJ7AVEBQAE+AVQBPgE+AT4BOQE4ATgBOAEcAVgXADEQCAEAUx8SHgsdHhYAjgCWAKYAUQBqIAIxAHYAbwCXAxUDJzIDIUlGTzEAkQJPAMcCVwKkAMAClgKWApYClgKWApYCiwKWApYClgKWApYClgKVApUCmAKgApcClgKWApQClAKUApQCkgKVAnUB1AKXAp8ClgKWApUeAIETBQD+DQOfAmECOh8BVBg9AuIZEjMbAU4/G1WZAXusRAFpYQEFA0FPAQYAmTEeIJdyADFoAHEANgCRA5zMk/C2jGINwjMWygIZCaXdfDILBCs5dAE7YnQBugDlhoiHhoiGiYqKhouOjIaNkI6Ij4qQipGGkoaThpSSlYaWhpeKmIaZhpqGm4aci52QnoqfhuIC4XTpAt90AIp0LHSoAIsAdHQEQwRABEIERQRDBEkERgRBBEcESQRIBEQERgRJAJ5udACrA490ALxuAQ10ANFZdHQA13QCFHQA/mJ0AP4BIQD+APwA/AD9APwDhGZ03ASMK23HAP4A/AD8AP0A/CR0dACRYnQA/gCRASEA/gCRAvQA/gCRA4RmdNwEjCttxyR0AP9idAEhAP4A/gD8APwA/QD8AP8A/AD8AP0A/AOEZnTcBIwrbcckdHQAkWJ0ASEA/gCRAP4AkQL0AP4AkQOEZnTcBIwrbcckdAJLAT50AlIBQXQCU8l0dAJfdHQDpgL0A6YDpgOnA6cDpwOnA4RmdNwEjCttxyR0dACRYnQBIQOmAJEDpgCRAvQDpgCRA4RmdNwEjCttxyR0BDh0AJEEOQCRDpU5dSgCADR03gV2CwArdAEFAM5iCnR0AF1iAAYcOgp0dACRCnQAXAEIwWZ0CnRmdHQAkWZ0CnRmdEXgAFF03gp0dEY0tlT2u3SOAQTwscwhjZZKrhYcBSfFp9XNbKiVDOD2b+cpe4/Z17mQnbtzzhaeQtE2GGj0IDNTjRUSyTxxw/RPHW/+vS7d1NfRt9z9QPZg4X7QFfhCnkvgNPIItOsC2eV6hPannZNHlZ9xrwZXIMOlu3jSoQSq78WEjwLjw1ELSlF1aBvfzwk5ZX7AUvQzjPQKbDuQ+sm4wNOp4A6AdVuRS0t1y/DZpg4R6m7FNjM9HgvW7Bi88zaMjOo6lM8wtBBdj8LP4ylv3zCXPhebMKJc066o9sF71oFW/8JXu86HJbwDID5lzw5GWLR/LhT0Qqnp2JQxNZNfcbLIzPy+YypqRm/lBmGmex+82+PisxUumSeJkALIT6rJezxMH+CTJmQtt5uwTVbL3ptmjDUQzlSIvWi8Tl7ng1NpuRn1Ng4n14Qc+3Iil7OwkvNWogLSPkn3pihIFytyIGmMhOe3n1tWsuMy9BdKyqF4Z3v2SgggTL9KVvMXPnCbRe+oOuFFP3HejBG/w9gvmfNYvg6JuWia2lcSSN1uIjBktzoIazOHPJZ7kKHPz8mRWVdW3lA8WGF9dQF6Bm673boov3BUWDU2JNcahR23GtfHKLOz/viZ+rYnZFaIznXO67CYEJ1fXuTRpZhYZkKe54xeoagkNGLs+NTZHE0rX45/XvQ2RGADX6vcAvdxIUBV27wxGm2zjZo4X3ILgAlrOFheuZ6wtsvaIj4yLY7qqawlliaIcrz2G+c3vscAnCkCuMzMmZvMfu9lLwTvfX+3cVSyPdN9ZwgDZhfjRgNJcLiJ67b9xx8JHswprbiE3v9UphotAPIgnXVIN5KmMc0piXhc6cChPnN+MRhG9adtdttQTTwSIpl8I4/j//d3sz1326qTBTpPRM/Hgh3kzqEXs8ZAk4ErQhNO8hzrQ0DLkWMA/N+91tn2MdOJnWC2FCZehkQrwzwbKOjhvZsbM95QoeL9skYyMf4srVPVJSgg7pOLUtr/n9eT99oe9nLtFRpjA9okV2Kj8h9k5HaC0oivRD8VyXkJ81tcd4fHNXPCfloIQasxsuO18/46dR2jgul/UIet2G0kRvnyONMKhHs6J26FEoqSqd+rfYjeEGwHWVDpX1fh1jBBcKGMqRepju9Y00mDVHC+Xdij/j44rKfvfjGinNs1jO/0F3jB83XCDINN/HB84axlP+3E/klktRo+vl3U/aiyMJbIodE1XSsDn6UAzIoMtUObY2+k/4gY/l+AkZJ5Sj2vQrkyLm3FoxjhDX+31UXBFf9XrAH31fFqoBmDEZvhvvpnZ87N+oZEu7U9O/nnk+QWj3x8uyoRbEnf+O5UMr9i0nHP38IF5AvzrBW8YWBUR0mIAzIvndQq9N3v/Jto3aPjPXUPl8ASdPPyAp7jENf8bk7VMM9ol9XGmlBmeDMuGqt+WzuL6CXAxXjIhCPM5vACchgMJ/8XBGLO/D1isVvGhwwHHr1DLaI5mn2Jr/b1pUD90uciDaS8cXNDzCWvNmT/PhQe5e8nTnnnkt8Ds/SIjibcum/fqDhKopxAY8AkSrPn+IGDEKOO+U3XOP6djFs2H5N9+orhOahiQk5KnEUWa+CzkVzhp8bMHRbg81qhjjXuIKbHjSLSIBKWqockGtKinY+z4/RdBUF6pcc3JmnlxVcNgrI4SEzKUZSwcD2QCyxzKve+gAmg6ZuSRkpPFa6mfThu7LJNu3H5K42uCpNvPAsoedolKV/LHe/eJ+BbaG5MG0NaSGVPRUmNFMFFSSpXEcXwbVh7UETOZZtoVNRGOIbbkig3McEtR68cG0RZAoJevWYo7Dg/lZ1CQzblWeUvVHmr8fY4Nqd9JJiH/zEX24mJviH60fAyFr0A3c4bC1j3yZU60VgJxXn8JgJXLUIsiBnmKmMYz+7yBQFBvqb2eYnuW59joZBf56/wXvWIR4R8wTmV80i1mZy+S4+BUES+hzjk0uXpC///z/IlqHZ1monzlXp8aCfhGKMti73FI1KbL1q6IKO4fuBuZ59gagjn5xU79muMpHXg6S+e+gDM/U9BKLHbl9l6o8czQKl4RUkJJiqftQG2i3BMg/TQlUYFkJDYBOOvAugYuzYSDnZbDDd/aSd9x0Oe6F+bJcHfl9+gp6L5/TgA+BdFFovbfCrQ40s5vMPw8866pNX8zyFGeFWdxIpPVp9Rg1UPOVFbFZrvaFq/YAzHQgqMWpahMYfqHpmwXfHL1/kpYmGuHFwT55mQu0dylfNuq2Oq0hTMCPwqfxnuBIPLXfci4Y1ANy+1CUipQxld/izVh16WyG2Q0CQQ9NqtAnx1HCHwDj7sYxOSB0wopZSnOzxQOcExmxrVTF2BkOthVpGfuhaGECfCJpJKpjnihY+xOT2QJxN61+9K6QSqtv2Shr82I3jgJrqBg0wELFZPjvHpvzTtaJnLK6Vb97Yn933koO/saN7fsjwNKzp4l2lJVx2orjCGzC/4ZL4zCver6aQYtC5sdoychuFE6ufOiog+VWi5UDkbmvmtah/3aArEBIi39s5ILUnlFLgilcGuz9CQshEY7fw2ouoILAYPVT/gyAIq3TFAIwVsl+ktkRz/qGfnCDGrm5gsl/l9QdvCWGsjPz3dU7XuqKfdUrr/6XIgjp4rey6AJBmCmUJMjITHVdFb5m1p+dLMCL8t55zD42cmftmLEJC0Da04YiRCVUBLLa8D071/N5UBNBXDh0LFsmhV/5B5ExOB4j3WVG/S3lfK5o+V6ELHvy6RR9n4ac+VsK4VE4yphPvV+kG9FegTBH4ZRXL2HytUHCduJazB/KykjfetYxOXTLws267aGOd+I+JhKP//+VnXmS90OD/jvLcVu0asyqcuYN1mSb6XTlCkqv1vigZPIYwNF/zpWcT1GR/6aEIRjkh0yhg4LXJfaGobYJTY4JI58KiAKgmmgAKWdl5nYCeLqavRJGQNuYuZtZFGx+IkI4w4NS2xwbetNMunOjBu/hmKCI/w7tfiiyUd//4rbTeWt4izBY8YvGIN6vyKYmP/8X8wHKCeN+WRcKM70+tXKNGyevU9H2Dg5BsljnTf8YbsJ1TmMs74Ce2XlHisleguhyeg44rQOHZuw/6HTkhnnurK2d62q6yS7210SsAIaR+jXMQA+svkrLpsUY+F30Uw89uOdGAR6vo4FIME0EfVVeHTu6eKicfhSqOeXJhbftcd08sWEnNUL1C9fnprTgd83IMut8onVUF0hvqzZfHduPjbjwEXIcoYmy+P6tcJZHmeOv6VrvEdkHDJecjHuHeWANe79VG662qTjA/HCvumVv3qL+LrOcpqGps2ZGwQdFJ7PU4iuyRlBrwfO+xnPyr47s2cXVbWzAyznDiBGjCM3ksxjjqM62GE9C8f5U38kB3VjtabKp/nRdvMESPGDG90bWRLAt1Qk5DyLuazRR1YzdC1c+hZXvAWV8xA72S4A8B67vjVhbba3MMop293FeEXpe7zItMWrJG/LOH9ByOXmYnNJfjmfuX9KbrpgLOba4nZ+fl8Gbdv/ihv+6wFGKHCYrVwmhFC0J3V2bn2tIB1wCc1CST3d3X2OyxhguXcs4sm679UngzofuSeBewMFJboIQHbUh/m2JhW2hG9DIvG2t7yZIzKBTz9wBtnNC+2pCRYhSIuQ1j8xsz5VvqnyUIthvuoyyu7fNIrg/KQUVmGQaqkqZk/Vx5b33/gsEs8yX7SC1J+NV4icz6bvIE7C5G6McBaI8rVg56q5QBJWxn/87Q1sPK4+sQa8fLU5gXo4paaq4cOcQ4wR0VBHPGjKh+UlPCbA1nLXyEUX45qZ8J7/Ln4FPJE2TdzD0Z8MLSNQiykMMmSyOCiFfy84Rq60emYB2vD09KjYwsoIpeDcBDTElBbXxND72yhd9pC/1CMid/5HUMvAL27OtcIJDzNKpRPNqPOpyt2aPGz9QWIs9hQ9LiX5s8m9hjTUu/f7MyIatjjd+tSfQ3ufZxPpmJhTaBtZtKLUcfOCUqADuO+QoH8B9v6U+P0HV1GLQmtoNFTb3s74ivZgjES0qfK+8RdGgBbcCMSy8eBvh98+et1KIFqSe1KQPyXULBMTsIYnysIwiZBJYdI20vseV+wuJkcqGemehKjaAb9L57xZm3g2zX0bZ2xk/fU+bCo7TlnbW7JuF1YdURo/2Gw7VclDG1W7LOtas2LX4upifZ/23rzpsnY/ALfRgrcWP5hYmV9VxVOQA1fZvp9F2UNU+7d7xRyVm5wiLp3/0dlV7vdw1PMiZrbDAYzIVqEjRY2YU03sJhPnlwIPcZUG5ltL6S8XCxU1eYS5cjr34veBmXAvy7yN4ZjArIG0dfD/5UpBNlX1ZPoxJOwyqRi3wQWtOzd4oNKh0LkoTm8cwqgIfKhqqGOhwo71I+zXnMemTv2B2AUzABWyFztGgGULjDDzWYwJUVBTjKCn5K2QGMK1CQT7SzziOjo+BhAmqBjzuc3xYym2eedGeOIRJVyTwDw37iCMe4g5Vbnsb5ZBdxOAnMT7HU4DHpxWGuQ7GeiY30Cpbvzss55+5Km1YsbD5ea3NI9QNYIXol5apgSu9dZ8f8xS5dtHpido5BclDuLWY4lhik0tbJa07yJhH0BOyEut/GRbYTS6RfiTYWGMCkNpfSHi7HvdiTglEVHKZXaVhezH4kkXiIvKopYAlPusftpE4a5IZwvw1x/eLvoDIh/zpo9FiQInsTb2SAkKHV42XYBjpJDg4374XiVb3ws4qM0s9eSQ5HzsMU4OZJKuopFjBM+dAZEl8RUMx5uU2N486Kr141tVsGQfGjORYMCJAMsxELeNT4RmWjRcpdTGBwcx6XN9drWqPmJzcrGrH4+DRc7+n1w3kPZwu0BkNr6hQrqgo7JTB9A5kdJ/H7P4cWBMwsmuixAzJB3yrQpnGIq90lxAXLzDCdn1LPibsRt7rHNjgQBklRgPZ8vTbjXdgXrTWQsK5MdrXXQVPp0Rinq3frzZKJ0qD6Qhc40VzAraUXlob1gvkhK3vpmHgI6FRlQZNx6eRqkp0zy4AQlX813fAPtL3jMRaitGFFjo0zmErloC+h+YYdVQ6k4F/epxAoF0BmqEoKNTt6j4vQZNQ2BoqF9Vj53TOIoNmDiu9Xp15RkIgQIGcoLpfoIbenzpGUAtqFJp5W+LLnx38jHeECTJ/navKY1NWfN0sY1T8/pB8kIH3DU3DX+u6W3YwpypBMYOhbSxGjq84RZ84fWJow8pyHqn4S/9J15EcCMsXqrfwyd9mhiu3+rEo9pPpoJkdZqHjra4NvzFwuThNKy6hao/SlLw3ZADUcUp3w3SRVfW2rhl80zOgTYnKE0Hs2qp1J6H3xqPqIkvUDRMFDYyRbsFI3M9MEyovPk8rlw7/0a81cDVLmBsR2ze2pBuKb23fbeZC0uXoIvDppfTwIDxk1Oq2dGesGc+oJXWJLGkOha3CX+DUnzgAp9HGH9RsPZN63Hn4RMA5eSVhPHO+9RcRb/IOgtW31V1Q5IPGtoxPjC+MEJbVlIMYADd9aHYWUIQKopuPOHmoqSkubnAKnzgKHqgIOfW5RdAgotN6BN+O2ZYHkuemLnvQ8U9THVrS1RtLmKbcC7PeeDsYznvqzeg6VCNwmr0Yyx1wnLjyT84BZz3EJyCptD3yeueAyDWIs0L2qs/VQ3HUyqfrja0V1LdDzqAikeWuV4sc7RLIB69jEIBjCkyZedoUHqCrOvShVzyd73OdrJW0hPOuQv2qOoHDc9xVb6Yu6uq3Xqp2ZaH46A7lzevbxQEmfrzvAYSJuZ4WDk1Hz3QX1LVdiUK0EvlAGAYlG3Md30r7dcPN63yqBCIj25prpvZP0nI4+EgWoFG95V596CurXpKRBGRjQlHCvy5Ib/iW8nZJWwrET3mgd6mEhfP4KCuaLjopWs7h+MdXFdIv8dHQJgg1xi1eYqB0uDYjxwVmri0Sv5XKut/onqapC+FQiC2C1lvYJ9MVco6yDYsS3AANUfMtvtbYI2hfwZatiSsnoUeMZd34GVjkMMKA+XnjJpXgRW2SHTZplVowPmJsvXy6w3cfO1AK2dvtZEKTkC/TY9LFiKHCG0DnrMQdGm2lzlBHM9iEYynH2UcVMhUEjsc0oDBTgo2ZSQ1gzkAHeWeBXYFjYLuuf8yzTCy7/RFR81WDjXMbq2BOH5dURnxo6oivmxL3cKzKInlZkD31nvpHB9Kk7GfcfE1t+1V64b9LtgeJGlpRFxQCAqWJ5DoY77ski8gsOEOr2uywZaoO/NGa0X0y1pNQHBi3b2SUGNpcZxDT7rLbBf1FSnQ8guxGW3W+36BW0gBje4DOz6Ba6SVk0xiKgt+q2JOFyr4SYfnu+Ic1QZYIuwHBrgzr6UvOcSCzPTOo7D6IC4ISeS7zkl4h+2VoeHpnG/uWR3+ysNgPcOIXQbv0n4mr3BwQcdKJxgPSeyuP/z1Jjg4e9nUvoXegqQVIE30EHx5GHv+FAVUNTowYDJgyFhf5IvlYmEqRif6+WN1MkEJmDcQITx9FX23a4mxy1AQRsOHO/+eImX9l8EMJI3oPWzVXxSOeHU1dUWYr2uAA7AMb+vAEZSbU3qob9ibCyXeypEMpZ6863o6QPqlqGHZkuWABSTVNd4cOh9hv3qEpSx2Zy/DJMP6cItEmiBJ5PFqQnDEIt3NrA3COlOSgz43D7gpNFNJ5MBh4oFzhDPiglC2ypsNU4ISywY2erkyb1NC3Qh/IfWj0eDgZI4/ln8WPfBsT3meTjq1Uqt1E7Zl/qftqkx6aM9KueMCekSnMrcHj1CqTWWzEzPsZGcDe3Ue4Ws+XFYVxNbOFF8ezkvQGR6ZOtOLU2lQEnMBStx47vE6Pb7AYMBRj2OOfZXfisjJnpTfSNjo6sZ6qSvNxZNmDeS7Gk3yYyCk1HtKN2UnhMIjOXUzAqDv90lx9O/q/AT1ZMnit5XQe9wmQxnE/WSH0CqZ9/2Hy+Sfmpeg8RwsHI5Z8kC8H293m/LHVVM/BA7HaTJYg5Enk7M/xWpq0192ACfBai2LA/qrCjCr6Dh1BIMzMXINBmX96MJ5Hn2nxln/RXPFhwHxUmSV0EV2V0jm86/dxxuYSU1W7sVkEbN9EzkG0QFwPhyHKyb3t+Fj5WoUUTErcazE/N6EW6Lvp0d//SDPj7EV9UdJN+Amnf3Wwk3A0SlJ9Z00yvXZ7n3z70G47Hfsow8Wq1JXcfwnA+Yxa5mFsgV464KKP4T31wqIgzFPd3eCe3j5ory5fBF2hgCFyVFrLzI9eetNXvM7oQqyFgDo4CTp/hDV9NMX9JDHQ/nyHTLvZLNLF6ftn2OxjGm8+PqOwhxnPHWipkE/8wbtyri80Sr7pMNkQGMfo4ZYK9OcCC4ESVFFbLMIvlxSoRqWie0wxqnLfcLSXMSpMMQEJYDVObYsXIQNv4TGNwjq1kvT1UOkicTrG3IaBZ3XdScS3u8sgeZPVpOLkbiF940FjbCeNRINNvDbd01EPBrTCPpm12m43ze1bBB59Ia6Ovhnur/Nvx3IxwSWol+3H2qfCJR8df6aQf4v6WiONxkK+IqT4pKQrZK/LplgDI/PJZbOep8dtbV7oCr6CgfpWa8NczOkPx81iSHbsNhVSJBOtrLIMrL31LK9TqHqAbAHe0RLmmV806kRLDLNEhUEJfm9u0sxpkL93Zgd6rw+tqBfTMi59xqXHLXSHwSbSBl0EK0+loECOPtrl+/nsaFe197di4yUgoe4jKoAJDXc6DGDjrQOoFDWZJ9HXwt8xDrQP+7aRwWKWI1GF8s8O4KzxWBBcwnl3vnl1Oez3oh6Ea1vjR7/z7DDTrFtqU2W/KAEzAuXDNZ7MY73MF216dzdSbWmUp4lcm7keJfWaMHgut9x5C9mj66Z0lJ+yhsjVvyiWrfk1lzPOTdhG15Y7gQlXtacvI7qv/XNSscDwqkgwHT/gUsD5yB7LdRRvJxQGYINn9hTpodKFVSTPrtGvyQw+HlRFXIkodErAGu9Iy1YpfSPc3jkFh5CX3lPxv7aqjE/JAfTIpEjGb/H7MO0e2vsViSW1qa/Lmi4/n4DEI3g7lYrcanspDfEpKkdV1OjSLOy0BCUqVoECaB55vs06rXl4jqmLsPsFM/7vYJ0vrBhDCm/00A/H81l1uekJ/6Lml3Hb9+NKiLqATJmDpyzfYZFHumEjC662L0Bwkxi7E9U4cQA0XMVDuMYAIeLMPgQaMVOd8fmt5SflFIfuBoszeAw7ow5gXPE2Y/yBc/7jExARUf/BxIHQBF5Sn3i61w4z5xJdCyO1F1X3+3ax+JSvMeZ7S6QSKp1Fp/sjYz6Z+VgCZzibGeEoujryfMulH7Rai5kAft9ebcW50DyJr2uo2z97mTWIu45YsSnNSMrrNUuG1XsYBtD9TDYzQffKB87vWbkM4EbPAFgoBV4GQS+vtFDUqOFAoi1nTtmIOvg38N4hT2Sn8r8clmBCXspBlMBYTnrqFJGBT3wZOzAyJDre9dHH7+x7qaaKDOB4UQALD5ecS0DE4obubQEiuJZ0EpBVpLuYcce8Aa4PYd/V4DLDAJBYKQPCWTcrEaZ5HYbJi11Gd6hjGom1ii18VHYnG28NKpkz2UKVPxlhYSp8uZr367iOmoy7zsxehW9wzcy2zG0a80PBMCRQMb32hnaHeOR8fnNDzZhaNYhkOdDsBUZ3loDMa1YP0uS0cjUP3b/6DBlqmZOeNABDsLl5BI5QJups8uxAuWJdkUB/pO6Zax6tsg7fN5mjjDgMGngO+DPcKqiHIDbFIGudxtPTIyDi9SFMKBDcfdGQRv41q1AqmxgkVfJMnP8w/Bc7N9/TR6C7mGObFqFkIEom8sKi2xYqJLTCHK7cxzaZvqODo22c3wisBCP4HeAgcRbNPAsBkNRhSmD48dHupdBRw4mIvtS5oeF6zeT1KMCyhMnmhpkFAGWnGscoNkwvQ8ZM5lE/vgTHFYL99OuNxdFBxTEDd5v2qLR8y9WkXsWgG6kZNndFG+pO/UAkOCipqIhL3hq7cRSdrCq7YhUsTocEcnaFa6nVkhnSeRYUA1YO0z5itF9Sly3VlxYDw239TJJH6f3EUfYO5lb7bcFcz8Bp7Oo8QmnsUHOz/fagVUBtKEw1iT88j+aKkv8cscKNkMxjYr8344D1kFoZ7/td1W6LCNYN594301tUGRmFjAzeRg5vyoM1F6+bJZ/Q54jN/k8SFd3DxPTYaAUsivsBfgTn7Mx8H2SpPt4GOdYRnEJOH6jHM2p6SgB0gzIRq6fHxGMmSmqaPCmlfwxiuloaVIitLGN8wie2CDWhkzLoCJcODh7KIOAqbHEvXdUxaS4TTTs07Clzj/6GmVs9kiZDerMxEnhUB6QQPlcfqkG9882RqHoLiHGBoHfQuXIsAG8GTAtao2KVwRnvvam8jo1e312GQAKWEa4sUVEAMG4G6ckcONDwRcg1e2D3+ohXgY4UAWF8wHKQMrSnzCgfFpsxh+aHXMGtPQroQasRY4U6UdG0rz1Vjbka0MekOGRZQEvqQFlxseFor8zWFgHek3v29+WqN6gaK5gZOTOMZzpQIC1201LkMCXild3vWXSc5UX9xcFYfbRPzGFa1FDcPfPB/jUEq/FeGt419CI3YmBlVoHsa4KdcwQP5ZSwHHhFJ7/Ph/Rap/4vmG91eDwPP0lDfCDRCLszTqfzM71xpmiKi2HwS4WlqvGNwtvwF5Dqpn6KTq8ax00UMPkxDcZrEEEsIvHiUXXEphdb4GB4FymlPwBz4Gperqq5pW7TQ6/yNRhW8VT5NhuP0udlxo4gILq5ZxAZk8ZGh3g4CqxJlPKY7AQxupfUcVpWT5VItp1+30UqoyP4wWsRo3olRRgkWZZ2ZN6VC3OZFeXB8NbnUrSdikNptD1QiGuKkr8EmSR/AK9Rw+FF3s5uwuPbvHGiPeFOViltMK7AUaOsq9+x9cndk3iJEE5LKZRlWJbKOZweROzmPNVPkjE3K/TyA57Rs68TkZ3MR8akKpm7cFjnjPd/DdkWjgYoKHSr5Wu5ssoBYU4acRs5g2DHxUmdq8VXOXRbunD8QN0LhgkssgahcdoYsNvuXGUK/KXD/7oFb+VGdhqIn02veuM5bLudJOc2Ky0GMaG4W/xWBxIJcL7yliJOXOpx0AkBqUgzlDczmLT4iILXDxxtRR1oZa2JWFgiAb43obrJnG/TZC2KSK2wqOzRZTXavZZFMb1f3bXvVaNaK828w9TO610gk8JNf3gMfETzXXsbcvRGCG9JWQZ6+cDPqc4466Yo2RcKH+PILeKOqtnlbInR3MmBeGG3FH10yzkybuqEC2HSQwpA0An7d9+73BkDUTm30bZmoP/RGbgFN+GrCOfADgqr0WbI1a1okpFms8iHYw9hm0zUvlEMivBRxModrbJJ+9/p3jUdQQ9BCtQdxnOGrT5dzRUmw0593/mbRSdBg0nRvRZM5/E16m7ZHmDEtWhwvfdZCZ8J8M12W0yRMszXamWfQTwIZ4ayYktrnscQuWr8idp3PjT2eF/jmtdhIfcpMnb+IfZY2FebW6UY/AK3jP4u3Tu4zE4qlnQgLFbM19EBIsNf7KhjdbqQ/D6yiDb+NlEi2SKD+ivXVUK8ib0oBo366gXkR8ZxGjpJIDcEgZPa9TcYe0TIbiPl/rPUQDu3XBJ9X/GNq3FAUsKsll57DzaGMrjcT+gctp+9MLYXCq+sqP81eVQ0r9lt+gcQfZbACRbEjvlMskztZG8gbC8Qn9tt26Q7y7nDrbZq/LEz7kR6Jc6pg3N9rVX8Y5MJrGlML9p9lU4jbTkKqCveeZUJjHB03m2KRKR2TytoFkTXOLg7keU1s1lrPMQJpoOKLuAAC+y1HlJucU6ysB5hsXhvSPPLq5J7JtnqHKZ4vYjC4Vy8153QY+6780xDuGARsGbOs1WqzH0QS765rnSKEbbKlkO8oI/VDwUd0is13tKpqILu1mDJFNy/iJAWcvDgjxvusIT+PGz3ST/J9r9Mtfd0jpaGeiLYIqXc7DiHSS8TcjFVksi66PEkxW1z6ujbLLUGNNYnzOWpH8BZGK4bCK7iR+MbIv8ncDAz1u4StN3vTTzewr9IQjk9wxFxn+6N1ddKs0vffJiS08N3a4G1SVrlZ97Q/M+8G9fe5AP6d9/Qq4WRnORVhofPIKEdCr3llspUfE0oKIIYoByBRPh+bX1HLS3JWGJRhIvE1aW4NTd8ePi4Z+kXb+Z8snYfSNcqijhAgVsx4RCM54cXUiYkjeBmmC4ajOHrChoELscJJC7+9jjMjw5BagZKlgRMiSNYz7h7vvZIoQqbtQmspc0cUk1G/73iXtSpROl5wtLgQi0mW2Ex8i3WULhcggx6E1LMVHUsdc9GHI1PH3U2Ko0PyGdn9KdVOLm7FPBui0i9a0HpA60MsewVE4z8CAt5d401Gv6zXlIT5Ybit1VIA0FCs7wtvYreru1fUyW3oLAZ/+aTnZrOcYRNVA8spoRtlRoWflsRClFcgzkqiHOrf0/SVw+EpVaFlJ0g4Kxq1MMOmiQdpMNpte8lMMQqm6cIFXlnGbfJllysKDi+0JJMotkqgIxOSQgU9dn/lWkeVf8nUm3iwX2Nl3WDw9i6AUK3vBAbZZrcJpDQ/N64AVwjT07Jef30GSSmtNu2WlW7YoyW2FlWfZFQUwk867EdLYKk9VG6JgEnBiBxkY7LMo4YLQJJlAo9l/oTvJkSARDF/XtyAzM8O2t3eT/iXa6wDN3WewNmQHdPfsxChU/KtLG2Mn8i4ZqKdSlIaBZadxJmRzVS/o4yA65RTSViq60oa395Lqw0pzY4SipwE0SXXsKV+GZraGSkr/RW08wPRvqvSUkYBMA9lPx4m24az+IHmCbXA+0faxTRE9wuGeO06DIXa6QlKJ3puIyiuAVfPr736vzo2pBirS+Vxel3TMm3JKhz9o2ZoRvaFVpIkykb0Hcm4oHFBMcNSNj7/4GJt43ogonY2Vg4nsDQIWxAcorpXACzgBqQPjYsE/VUpXpwNManEru4NwMCFPkXvMoqvoeLN3qyu/N1eWEHttMD65v19l/0kH2mR35iv/FI+yjoHJ9gPMz67af3Mq/BoWXqu3rphiWMXVkmnPSEkpGpUI2h1MThideGFEOK6YZHPwYzMBvpNC7+ZHxPb7epfefGyIB4JzO9DTNEYnDLVVHdQyvOEVefrk6Uv5kTQYVYWWdqrdcIl7yljwwIWdfQ/y+2QB3eR/qxYObuYyB4gTbo2in4PzarU1sO9nETkmj9/AoxDA+JM3GMqQtJR4jtduHtnoCLxd1gQUscHRB/MoRYIEsP2pDZ9KvHgtlk1iTbWWbHhohwFEYX7y51fUV2nuUmnoUcqnWIQAAgl9LTVX+Bc0QGNEhChxHR4YjfE51PUdGfsSFE6ck7BL3/hTf9jLq4G1IafINxOLKeAtO7quulYvH5YOBc+zX7CrMgWnW47/jfRsWnJjYYoE7xMfWV2HN2iyIqLI';
  8412. const FENCED = new Map([[8217,"apostrophe"],[8260,"fraction slash"],[12539,"middle dot"]]);
  8413. const NSM_MAX = 4;
  8414. function decode_arithmetic(bytes) {
  8415. let pos = 0;
  8416. function u16() { return (bytes[pos++] << 8) | bytes[pos++]; }
  8417. // decode the frequency table
  8418. let symbol_count = u16();
  8419. let total = 1;
  8420. let acc = [0, 1]; // first symbol has frequency 1
  8421. for (let i = 1; i < symbol_count; i++) {
  8422. acc.push(total += u16());
  8423. }
  8424. // skip the sized-payload that the last 3 symbols index into
  8425. let skip = u16();
  8426. let pos_payload = pos;
  8427. pos += skip;
  8428. let read_width = 0;
  8429. let read_buffer = 0;
  8430. function read_bit() {
  8431. if (read_width == 0) {
  8432. // this will read beyond end of buffer
  8433. // but (undefined|0) => zero pad
  8434. read_buffer = (read_buffer << 8) | bytes[pos++];
  8435. read_width = 8;
  8436. }
  8437. return (read_buffer >> --read_width) & 1;
  8438. }
  8439. const N = 31;
  8440. const FULL = 2**N;
  8441. const HALF = FULL >>> 1;
  8442. const QRTR = HALF >> 1;
  8443. const MASK = FULL - 1;
  8444. // fill register
  8445. let register = 0;
  8446. for (let i = 0; i < N; i++) register = (register << 1) | read_bit();
  8447. let symbols = [];
  8448. let low = 0;
  8449. let range = FULL; // treat like a float
  8450. while (true) {
  8451. let value = Math.floor((((register - low + 1) * total) - 1) / range);
  8452. let start = 0;
  8453. let end = symbol_count;
  8454. while (end - start > 1) { // binary search
  8455. let mid = (start + end) >>> 1;
  8456. if (value < acc[mid]) {
  8457. end = mid;
  8458. } else {
  8459. start = mid;
  8460. }
  8461. }
  8462. if (start == 0) break; // first symbol is end mark
  8463. symbols.push(start);
  8464. let a = low + Math.floor(range * acc[start] / total);
  8465. let b = low + Math.floor(range * acc[start+1] / total) - 1;
  8466. while (((a ^ b) & HALF) == 0) {
  8467. register = (register << 1) & MASK | read_bit();
  8468. a = (a << 1) & MASK;
  8469. b = (b << 1) & MASK | 1;
  8470. }
  8471. while (a & ~b & QRTR) {
  8472. register = (register & HALF) | ((register << 1) & (MASK >>> 1)) | read_bit();
  8473. a = (a << 1) ^ HALF;
  8474. b = ((b ^ HALF) << 1) | HALF | 1;
  8475. }
  8476. low = a;
  8477. range = 1 + b - a;
  8478. }
  8479. let offset = symbol_count - 4;
  8480. return symbols.map(x => { // index into payload
  8481. switch (x - offset) {
  8482. case 3: return offset + 0x10100 + ((bytes[pos_payload++] << 16) | (bytes[pos_payload++] << 8) | bytes[pos_payload++]);
  8483. case 2: return offset + 0x100 + ((bytes[pos_payload++] << 8) | bytes[pos_payload++]);
  8484. case 1: return offset + bytes[pos_payload++];
  8485. default: return x - 1;
  8486. }
  8487. });
  8488. }
  8489. // returns an iterator which returns the next symbol
  8490. function read_payload(v) {
  8491. let pos = 0;
  8492. return () => v[pos++];
  8493. }
  8494. function read_compressed_payload(s) {
  8495. return read_payload(decode_arithmetic(unsafe_atob(s)));
  8496. }
  8497. // unsafe in the sense:
  8498. // expected well-formed Base64 w/o padding
  8499. // 20220922: added for https://github.com/adraffy/ens-normalize.js/issues/4
  8500. function unsafe_atob(s) {
  8501. let lookup = [];
  8502. [...'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'].forEach((c, i) => lookup[c.charCodeAt(0)] = i);
  8503. let n = s.length;
  8504. let ret = new Uint8Array((6 * n) >> 3);
  8505. for (let i = 0, pos = 0, width = 0, carry = 0; i < n; i++) {
  8506. carry = (carry << 6) | lookup[s.charCodeAt(i)];
  8507. width += 6;
  8508. if (width >= 8) {
  8509. ret[pos++] = (carry >> (width -= 8));
  8510. }
  8511. }
  8512. return ret;
  8513. }
  8514. // eg. [0,1,2,3...] => [0,-1,1,-2,...]
  8515. function signed(i) {
  8516. return (i & 1) ? (~i >> 1) : (i >> 1);
  8517. }
  8518. function read_deltas(n, next) {
  8519. let v = Array(n);
  8520. for (let i = 0, x = 0; i < n; i++) v[i] = x += signed(next());
  8521. return v;
  8522. }
  8523. // [123][5] => [0 3] [1 1] [0 0]
  8524. function read_sorted(next, prev = 0) {
  8525. let ret = [];
  8526. while (true) {
  8527. let x = next();
  8528. let n = next();
  8529. if (!n) break;
  8530. prev += x;
  8531. for (let i = 0; i < n; i++) {
  8532. ret.push(prev + i);
  8533. }
  8534. prev += n + 1;
  8535. }
  8536. return ret;
  8537. }
  8538. function read_sorted_arrays(next) {
  8539. return read_array_while(() => {
  8540. let v = read_sorted(next);
  8541. if (v.length) return v;
  8542. });
  8543. }
  8544. // returns map of x => ys
  8545. function read_mapped(next) {
  8546. let ret = [];
  8547. while (true) {
  8548. let w = next();
  8549. if (w == 0) break;
  8550. ret.push(read_linear_table(w, next));
  8551. }
  8552. while (true) {
  8553. let w = next() - 1;
  8554. if (w < 0) break;
  8555. ret.push(read_replacement_table(w, next));
  8556. }
  8557. return ret.flat();
  8558. }
  8559. // read until next is falsy
  8560. // return array of read values
  8561. function read_array_while(next) {
  8562. let v = [];
  8563. while (true) {
  8564. let x = next(v.length);
  8565. if (!x) break;
  8566. v.push(x);
  8567. }
  8568. return v;
  8569. }
  8570. // read w columns of length n
  8571. // return as n rows of length w
  8572. function read_transposed(n, w, next) {
  8573. let m = Array(n).fill().map(() => []);
  8574. for (let i = 0; i < w; i++) {
  8575. read_deltas(n, next).forEach((x, j) => m[j].push(x));
  8576. }
  8577. return m;
  8578. }
  8579. // returns [[x, ys], [x+dx, ys+dy], [x+2*dx, ys+2*dy], ...]
  8580. // where dx/dy = steps, n = run size, w = length of y
  8581. function read_linear_table(w, next) {
  8582. let dx = 1 + next();
  8583. let dy = next();
  8584. let vN = read_array_while(next);
  8585. let m = read_transposed(vN.length, 1+w, next);
  8586. return m.flatMap((v, i) => {
  8587. let [x, ...ys] = v;
  8588. return Array(vN[i]).fill().map((_, j) => {
  8589. let j_dy = j * dy;
  8590. return [x + j * dx, ys.map(y => y + j_dy)];
  8591. });
  8592. });
  8593. }
  8594. // return [[x, ys...], ...]
  8595. // where w = length of y
  8596. function read_replacement_table(w, next) {
  8597. let n = 1 + next();
  8598. let m = read_transposed(n, 1+w, next);
  8599. return m.map(v => [v[0], v.slice(1)]);
  8600. }
  8601. function read_trie(next) {
  8602. let ret = [];
  8603. let sorted = read_sorted(next);
  8604. expand(decode([]), []);
  8605. return ret; // not sorted
  8606. function decode(Q) { // characters that lead into this node
  8607. let S = next(); // state: valid, save, check
  8608. let B = read_array_while(() => { // buckets leading to new nodes
  8609. let cps = read_sorted(next).map(i => sorted[i]);
  8610. if (cps.length) return decode(cps);
  8611. });
  8612. return {S, B, Q};
  8613. }
  8614. function expand({S, B}, cps, saved) {
  8615. if (S & 4 && saved === cps[cps.length-1]) return;
  8616. if (S & 2) saved = cps[cps.length-1];
  8617. if (S & 1) ret.push(cps);
  8618. for (let br of B) {
  8619. for (let cp of br.Q) {
  8620. expand(br, [...cps, cp], saved);
  8621. }
  8622. }
  8623. }
  8624. }
  8625. function hex_cp(cp) {
  8626. return cp.toString(16).toUpperCase().padStart(2, '0');
  8627. }
  8628. function quote_cp(cp) {
  8629. return `{${hex_cp(cp)}}`; // raffy convention: like "\u{X}" w/o the "\u"
  8630. }
  8631. /*
  8632. export function explode_cp(s) {
  8633. return [...s].map(c => c.codePointAt(0));
  8634. }
  8635. */
  8636. function explode_cp(s) { // this is about 2x faster
  8637. let cps = [];
  8638. for (let pos = 0, len = s.length; pos < len; ) {
  8639. let cp = s.codePointAt(pos);
  8640. pos += cp < 0x10000 ? 1 : 2;
  8641. cps.push(cp);
  8642. }
  8643. return cps;
  8644. }
  8645. function str_from_cps(cps) {
  8646. const chunk = 4096;
  8647. let len = cps.length;
  8648. if (len < chunk) return String.fromCodePoint(...cps);
  8649. let buf = [];
  8650. for (let i = 0; i < len; ) {
  8651. buf.push(String.fromCodePoint(...cps.slice(i, i += chunk)));
  8652. }
  8653. return buf.join('');
  8654. }
  8655. function compare_arrays(a, b) {
  8656. let n = a.length;
  8657. let c = n - b.length;
  8658. for (let i = 0; c == 0 && i < n; i++) c = a[i] - b[i];
  8659. return c;
  8660. }
  8661. // created 2023-09-25T01:01:55.148Z
  8662. // compressed base64-encoded blob for include-nf data
  8663. // source: https://github.com/adraffy/ens-normalize.js/blob/main/src/make.js
  8664. // see: https://github.com/adraffy/ens-normalize.js#security
  8665. // SHA-256: a974b6f8541fc29d919bc85118af0a44015851fab5343f8679cb31be2bdb209e
  8666. var COMPRESSED = 'AEUDTAHBCFQATQDRADAAcgAgADQAFAAsABQAHwAOACQADQARAAoAFwAHABIACAAPAAUACwAFAAwABAAQAAMABwAEAAoABQAIAAIACgABAAQAFAALAAIACwABAAIAAQAHAAMAAwAEAAsADAAMAAwACgANAA0AAwAKAAkABAAdAAYAZwDSAdsDJgC0CkMB8xhZAqfoC190UGcThgBurwf7PT09Pb09AjgJum8OjDllxHYUKXAPxzq6tABAxgK8ysUvWAgMPT09PT09PSs6LT2HcgWXWwFLoSMEEEl5RFVMKvO0XQ8ExDdJMnIgsj26PTQyy8FfEQ8AY8IPAGcEbwRwBHEEcgRzBHQEdQR2BHcEeAR6BHsEfAR+BIAEgfndBQoBYgULAWIFDAFiBNcE2ATZBRAFEQUvBdALFAsVDPcNBw13DYcOMA4xDjMB4BllHI0B2grbAMDpHLkQ7QHVAPRNQQFnGRUEg0yEB2uaJF8AJpIBpob5AERSMAKNoAXqaQLUBMCzEiACnwRZEkkVsS7tANAsBG0RuAQLEPABv9HICTUBXigPZwRBApMDOwAamhtaABqEAY8KvKx3LQ4ArAB8UhwEBAVSagD8AEFZADkBIadVj2UMUgx5Il4ANQC9AxIB1BlbEPMAs30CGxlXAhwZKQIECBc6EbsCoxngzv7UzRQA8M0BawL6ZwkN7wABAD33OQRcsgLJCjMCjqUChtw/km+NAsXPAoP2BT84PwURAK0RAvptb6cApQS/OMMey5HJS84UdxpxTPkCogVFITaTOwERAK5pAvkNBOVyA7q3BKlOJSALAgUIBRcEdASpBXqzABXFSWZOawLCOqw//AolCZdvv3dSBkEQGyelEPcMMwG1ATsN7UvYBPEGOwTJH30ZGQ/NlZwIpS3dDO0m4y6hgFoj9SqDBe1L9DzdC01RaA9ZC2UJ4zpjgU4DIQENIosK3Q05CG0Q8wrJaw3lEUUHOQPVSZoApQcBCxEdNRW1JhBirAsJOXcG+xr2C48mrxMpevwF0xohBk0BKRr/AM8u54WwWjFcHE9fBgMLJSPHFKhQIA0lQLd4SBobBxUlqQKRQ3BKh1E2HpMh9jw9DWYuE1F8B/U8BRlPC4E8nkarRQ4R0j6NPUgiSUwsBDV/LC8niwnPD4UMuXxyAVkJIQmxDHETMREXN8UIOQcZLZckJxUIIUaVYJoE958D8xPRAwsFPwlBBxMDtRwtEy4VKQUNgSTXAvM21S6zAo9WgAEXBcsPJR/fEFBH4A7pCJsCZQODJesALRUhABcimwhDYwBfj9hTBS7LCMdqbCN0A2cU52ERcweRDlcHpxwzFb8c4XDIXguGCCijrwlbAXUJmQFfBOMICTVbjKAgQWdTi1gYmyBhQT9d/AIxDGUVn0S9h3gCiw9rEhsBNQFzBzkNAQJ3Ee0RaxCVCOuGBDW1M/g6JQRPIYMgEQonA09szgsnJvkM+GkBoxJiAww0PXfuZ6tgtiQX/QcZMsVBYCHxC5JPzQycGsEYQlQuGeQHvwPzGvMn6kFXBf8DowMTOk0z7gS9C2kIiwk/AEkOoxcH1xhqCnGM0AExiwG3mQNXkYMCb48GNwcLAGcLhwV55QAdAqcIowAFAM8DVwA5Aq0HnQAZAIVBAT0DJy8BIeUCjwOTCDHLAZUvAfMpBBvDDBUA9zduSgLDsQKAamaiBd1YAo4CSTUBTSUEBU5HUQOvceEA2wBLBhPfRwEVq0rLGuNDAd9vKwDHAPsABTUHBUEBzQHzbQC3AV8LMQmis7UBTekpAIMAFWsB1wKJAN0ANQB/8QFTAE0FWfkF0wJPSQERMRgrV2EBuwMfATMBDQB5BsuNpckHHwRtB9MCEBsV4QLvLge1AQMi3xPNQsUCvd5VoWACZIECYkJbTa9bNyACofcCaJgCZgkCn4Q4GwsCZjsCZiYEbgR/A38TA36SOQY5dxc5gjojIwJsHQIyNjgKAm3HAm2u74ozZ0UrAWcA3gDhAEoFB5gMjQD+C8IADbUCdy8CdqI/AnlLQwJ4uh1c20WuRtcCfD8CesgCfQkCfPAFWQUgSABIfWMkAoFtAoAAAoAFAn+uSVhKWxUXSswC0QEC0MxLJwOITwOH5kTFkTIC8qFdAwMDrkvOTC0lA89NTE2vAos/AorYwRsHHUNnBbcCjjcCjlxAl4ECjtkCjlx4UbRTNQpS1FSFApP7ApMMAOkAHFUeVa9V0AYsGymVhjLheGZFOzkCl58C77JYIagAWSUClo8ClnycAKlZrFoJgU0AOwKWtQKWTlxEXNECmcsCmWRcyl0HGQKcmznCOp0CnBYCn5sCnriKAB0PMSoPAp3xAp6SALU9YTRh7wKe0wKgbgGpAp6fHwKeTqVjyGQnJSsCJ68CJn4CoPsCoEwCot0CocQCpi8Cpc4Cp/8AfQKn8mh8aLEAA0lqHGrRAqzjAqyuAq1nAq0CAlcdAlXcArHh1wMfTmyXArK9DQKy6Bds4G1jbUhfAyXNArZcOz9ukAMpRQK4XgK5RxUCuSp3cDZw4QK9GQK72nCWAzIRAr6IcgIDM3ECvhpzInNPAsPLAsMEc4J0SzVFdOADPKcDPJoDPb8CxXwCxkcCxhCJAshpUQLIRALJTwLJLgJknQLd0nh5YXiueSVL0AMYo2cCAmH0GfOVJHsLXpJeuxECz2sCz2wvS1PS8xOfAMatAs9zASnqA04SfksFAtwnAtuKAtJPA1JcA1NfAQEDVYyAiT8AyxbtYEWCHILTgs6DjQLaxwLZ3oQQhEmnPAOGpQAvA2QOhnFZ+QBVAt9lAt64c3cC4i/tFAHzMCcB9JsB8tKHAuvzAulweQLq+QLq5AD5RwG5Au6JAuuclqqXAwLuPwOF4Jh5cOBxoQLzAwBpA44WmZMC9xMDkW4DkocC95gC+dkC+GaaHJqruzebHgOdgwL++gEbADmfHJ+zAwWNA6ZqA6bZANHFAwZqoYiiBQkDDEkCwAA/AwDhQRdTARHzA2sHl2cFAJMtK7evvdsBiZkUfxEEOQH7KQUhDp0JnwCS/SlXxQL3AZ0AtwW5AG8LbUEuFCaNLgFDAYD8AbUmAHUDDgRtACwCFgyhAAAKAj0CagPdA34EkQEgRQUhfAoABQBEABMANhICdwEABdUDa+8KxQIA9wqfJ7+xt+UBkSFBQgHpFH8RNMCJAAQAGwBaAkUChIsABjpTOpSNbQC4Oo860ACNOME63AClAOgAywE6gTo7Ofw5+Tt2iTpbO56JOm85GAFWATMBbAUvNV01njWtNWY1dTW2NcU1gjWRNdI14TWeNa017jX9NbI1wTYCNhE1xjXVNhY2JzXeNe02LjY9Ni41LSE2OjY9Njw2yTcIBJA8VzY4Nt03IDcPNsogN4k3MAoEsDxnNiQ3GTdsOo03IULUQwdC4EMLHA8PCZsobShRVQYA6X8A6bABFCnXAukBowC9BbcAbwNzBL8MDAMMAQgDAAkKCwsLCQoGBAVVBI/DvwDz9b29kaUCb0QtsRTNLt4eGBcSHAMZFhYZEhYEARAEBUEcQRxBHEEcQRxBHEEaQRxBHEFCSTxBPElISUhBNkM2QTYbNklISVmBVIgBFLWZAu0BhQCjBcEAbykBvwGJAaQcEZ0ePCklMAAhMvAIMAL54gC7Bm8EescjzQMpARQpKgDUABavAj626xQAJP0A3etzuf4NNRA7efy2Z9NQrCnC0OSyANz5BBIbJ5IFDR6miIavYS6tprjjmuKebxm5C74Q225X1pkaYYPb6f1DK4k3xMEBb9S2WMjEibTNWhsRJIA+vwNVEiXTE5iXs/wezV66oFLfp9NZGYW+Gk19J2+bCT6Ye2w6LDYdgzKMUabk595eLBCXANz9HUpWbATq9vqXVx9XDg+Pc9Xp4+bsS005SVM/BJBM4687WUuf+Uj9dEi8aDNaPxtpbDxcG1THTImUMZq4UCaaNYpsVqraNyKLJXDYsFZ/5jl7bLRtO88t7P3xZaAxhb5OdPMXqsSkp1WCieG8jXm1U99+blvLlXzPCS+M93VnJCiK+09LfaSaBAVBomyDgJua8dfUzR7ga34IvR2Nvj+A9heJ6lsl1KG4NkI1032Cnff1m1wof2B9oHJK4bi6JkEdSqeNeiuo6QoZZincoc73/TH9SXF8sCE7XyuYyW8WSgbGFCjPV0ihLKhdPs08Tx82fYAkLLc4I2wdl4apY7GU5lHRFzRWJep7Ww3wbeA3qmd59/86P4xuNaqDpygXt6M85glSBHOCGgJDnt+pN9bK7HApMguX6+06RZNjzVmcZJ+wcUrJ9//bpRNxNuKpNl9uFds+S9tdx7LaM5ZkIrPj6nIU9mnbFtVbs9s/uLgl8MVczAwet+iOEzzBlYW7RCMgE6gyNLeq6+1tIx4dpgZnd0DksJS5f+JNDpwwcPNXaaVspq1fbQajOrJgK0ofKtJ1Ne90L6VO4MOl5S886p7u6xo7OLjG8TGL+HU1JXGJgppg4nNbNJ5nlzSpuPYy21JUEcUA94PoFiZfjZue+QnyQ80ekOuZVkxx4g+cvhJfHgNl4hy1/a6+RKcKlar/J29y//EztlbVPHVUeQ1zX86eQVAjR/M3dA9w4W8LfaXp4EgM85wOWasli837PzVMOnsLzR+k3o75/lRPAJSE1xAKQzEi5v10ke+VBvRt1cwQRMd+U5mLCTGVd6XiZtgBG5cDi0w22GKcVNvHiu5LQbZEDVtz0onn7k5+heuKXVsZtSzilkLRAUmjMXEMB3J9YC50XBxPiz53SC+EhnPl9WsKCv92SM/OFFIMJZYfl0WW8tIO3UxYcwdMAj7FSmgrsZ2aAZO03BOhP1bNNZItyXYQFTpC3SG1VuPDqH9GkiCDmE+JwxyIVSO5siDErAOpEXFgjy6PQtOVDj+s6e1r8heWVvmZnTciuf4EiNZzCAd7SOMhXERIOlsHIMG399i9aLTy3m2hRLZjJVDNLS53iGIK11dPqQt0zBDyg6qc7YqkDm2M5Ve6dCWCaCbTXX2rToaIgz6+zh4lYUi/+6nqcFMAkQJKHYLK0wYk5N9szV6xihDbDDFr45lN1K4aCXBq/FitPSud9gLt5ZVn+ZqGX7cwm2z5EGMgfFpIFyhGGuDPmso6TItTMwny+7uPnLCf4W6goFQFV0oQSsc9VfMmVLcLr6ZetDZbaSFTLqnSO/bIPjA3/zAUoqgGFAEQS4IhuMzEp2I3jJzbzkk/IEmyax+rhZTwd6f+CGtwPixu8IvzACquPWPREu9ZvGkUzpRwvRRuaNN6cr0W1wWits9ICdYJ7ltbgMiSL3sTPeufgNcVqMVWFkCPDH4jG2jA0XcVgQj62Cb29v9f/z/+2KbYvIv/zzjpQAPkliaVDzNrW57TZ/ZOyZD0nlfMmAIBIAGAI0D3k/mdN4xr9v85ZbZbbqfH2jGd5hUqNZWwl5SPfoGmfElmazUIeNL1j/mkF7VNAzTq4jNt8JoQ11NQOcmhprXoxSxfRGJ9LDEOAQ+dmxAQH90iti9e2u/MoeuaGcDTHoC+xsmEeWmxEKefQuIzHbpw5Tc5cEocboAD09oipWQhtTO1wivf/O+DRe2rpl/E9wlrzBorjJsOeG1B/XPW4EaJEFdNlECEZga5ZoGRHXgYouGRuVkm8tDESiEyFNo+3s5M5puSdTyUL2llnINVHEt91XUNW4ewdMgJ4boJfEyt/iY5WXqbA+A2Fkt5Z0lutiWhe9nZIyIUjyXDC3UsaG1t+eNx6z4W/OYoTB7A6x+dNSTOi9AInctbESqm5gvOLww7OWXPrmHwVZasrl4eD113pm+JtT7JVOvnCXqdzzdTRHgJ0PiGTFYW5Gvt9R9LD6Lzfs0v/TZZHSmyVNq7viIHE6DBK7Qp07Iz55EM8SYtQvZf/obBniTWi5C2/ovHfw4VndkE5XYdjOhCMRjDeOEfXeN/CwfGduiUIfsoFeUxXeQXba7c7972XNv8w+dTjjUM0QeNAReW+J014dKAD/McQYXT7c0GQPIkn3Ll6R7gGjuiQoZD0TEeEqQpKoZ15g/0OPQI17QiSv9AUROa/V/TQN3dvLArec3RrsYlvBm1b8LWzltdugsC50lNKYLEp2a+ZZYqPejULRlOJh5zj/LVMyTDvwKhMxxwuDkxJ1QpoNI0OTWLom4Z71SNzI9TV1iXJrIu9Wcnd+MCaAw8o1jSXd94YU/1gnkrC9BUEOtQvEIQ7g0i6h+KL2JKk8Ydl7HruvgWMSAmNe+LshGhV4qnWHhO9/RIPQzY1tHRj2VqOyNsDpK0cww+56AdDC4gsWwY0XxoucIWIqs/GcwnWqlaT0KPr8mbK5U94/301i1WLt4YINTVvCFBrFZbIbY8eycOdeJ2teD5IfPLCRg7jjcFTwlMFNl9zdh/o3E/hHPwj7BWg0MU09pPrBLbrCgm54A6H+I6v27+jL5gkjWg/iYdks9jbfVP5y/n0dlgWEMlKasl7JvFZd56LfybW1eeaVO0gxTfXZwD8G4SI116yx7UKVRgui6Ya1YpixqXeNLc8IxtAwCU5IhwQgn+NqHnRaDv61CxKhOq4pOX7M6pkA+Pmpd4j1vn6ACUALoLLc4vpXci8VidLxzm7qFBe7s+quuJs6ETYmnpgS3LwSZxPIltgBDXz8M1k/W2ySNv2f9/NPhxLGK2D21dkHeSGmenRT3Yqcdl0m/h3OYr8V+lXNYGf8aCCpd4bWjE4QIPj7vUKN4Nrfs7ML6Y2OyS830JCnofg/k7lpFpt4SqZc5HGg1HCOrHvOdC8bP6FGDbE/VV0mX4IakzbdS/op+Kt3G24/8QbBV7y86sGSQ/vZzU8FXs7u6jIvwchsEP2BpIhW3G8uWNwa3HmjfH/ZjhhCWvluAcF+nMf14ClKg5hGgtPLJ98ueNAkc5Hs2WZlk2QHvfreCK1CCGO6nMZVSb99VM/ajr8WHTte9JSmkXq/i/U943HEbdzW6Re/S88dKgg8pGOLlAeNiqrcLkUR3/aClFpMXcOUP3rmETcWSfMXZE3TUOi8i+fqRnTYLflVx/Vb/6GJ7eIRZUA6k3RYR3iFSK9c4iDdNwJuZL2FKz/IK5VimcNWEqdXjSoxSgmF0UPlDoUlNrPcM7ftmA8Y9gKiqKEHuWN+AZRIwtVSxye2Kf8rM3lhJ5XcBXU9n4v0Oy1RU2M+4qM8AQPVwse8ErNSob5oFPWxuqZnVzo1qB/IBxkM3EVUKFUUlO3e51259GgNcJbCmlvrdjtoTW7rChm1wyCKzpCTwozUUEOIcWLneRLgMXh+SjGSFkAllzbGS5HK7LlfCMRNRDSvbQPjcXaenNYxCvu2Qyznz6StuxVj66SgI0T8B6/sfHAJYZaZ78thjOSIFumNWLQbeZixDCCC+v0YBtkxiBB3jefHqZ/dFHU+crbj6OvS1x/JDD7vlm7zOVPwpUC01nhxZuY/63E7g';
  8667. // https://unicode.org/reports/tr15/
  8668. // for reference implementation
  8669. // see: /derive/nf.js
  8670. // algorithmic hangul
  8671. // https://www.unicode.org/versions/Unicode15.0.0/ch03.pdf (page 144)
  8672. const S0 = 0xAC00;
  8673. const L0 = 0x1100;
  8674. const V0 = 0x1161;
  8675. const T0 = 0x11A7;
  8676. const L_COUNT = 19;
  8677. const V_COUNT = 21;
  8678. const T_COUNT = 28;
  8679. const N_COUNT = V_COUNT * T_COUNT;
  8680. const S_COUNT = L_COUNT * N_COUNT;
  8681. const S1 = S0 + S_COUNT;
  8682. const L1 = L0 + L_COUNT;
  8683. const V1 = V0 + V_COUNT;
  8684. const T1$1 = T0 + T_COUNT;
  8685. function unpack_cc(packed) {
  8686. return (packed >> 24) & 0xFF;
  8687. }
  8688. function unpack_cp(packed) {
  8689. return packed & 0xFFFFFF;
  8690. }
  8691. let SHIFTED_RANK, EXCLUSIONS, DECOMP, RECOMP;
  8692. function init$1() {
  8693. //console.time('nf');
  8694. let r = read_compressed_payload(COMPRESSED);
  8695. SHIFTED_RANK = new Map(read_sorted_arrays(r).flatMap((v, i) => v.map(x => [x, (i+1) << 24]))); // pre-shifted
  8696. EXCLUSIONS = new Set(read_sorted(r));
  8697. DECOMP = new Map();
  8698. RECOMP = new Map();
  8699. for (let [cp, cps] of read_mapped(r)) {
  8700. if (!EXCLUSIONS.has(cp) && cps.length == 2) {
  8701. let [a, b] = cps;
  8702. let bucket = RECOMP.get(a);
  8703. if (!bucket) {
  8704. bucket = new Map();
  8705. RECOMP.set(a, bucket);
  8706. }
  8707. bucket.set(b, cp);
  8708. }
  8709. DECOMP.set(cp, cps.reverse()); // stored reversed
  8710. }
  8711. //console.timeEnd('nf');
  8712. // 20230905: 11ms
  8713. }
  8714. function is_hangul(cp) {
  8715. return cp >= S0 && cp < S1;
  8716. }
  8717. function compose_pair(a, b) {
  8718. if (a >= L0 && a < L1 && b >= V0 && b < V1) {
  8719. return S0 + (a - L0) * N_COUNT + (b - V0) * T_COUNT;
  8720. } else if (is_hangul(a) && b > T0 && b < T1$1 && (a - S0) % T_COUNT == 0) {
  8721. return a + (b - T0);
  8722. } else {
  8723. let recomp = RECOMP.get(a);
  8724. if (recomp) {
  8725. recomp = recomp.get(b);
  8726. if (recomp) {
  8727. return recomp;
  8728. }
  8729. }
  8730. return -1;
  8731. }
  8732. }
  8733. function decomposed(cps) {
  8734. if (!SHIFTED_RANK) init$1();
  8735. let ret = [];
  8736. let buf = [];
  8737. let check_order = false;
  8738. function add(cp) {
  8739. let cc = SHIFTED_RANK.get(cp);
  8740. if (cc) {
  8741. check_order = true;
  8742. cp |= cc;
  8743. }
  8744. ret.push(cp);
  8745. }
  8746. for (let cp of cps) {
  8747. while (true) {
  8748. if (cp < 0x80) {
  8749. ret.push(cp);
  8750. } else if (is_hangul(cp)) {
  8751. let s_index = cp - S0;
  8752. let l_index = s_index / N_COUNT | 0;
  8753. let v_index = (s_index % N_COUNT) / T_COUNT | 0;
  8754. let t_index = s_index % T_COUNT;
  8755. add(L0 + l_index);
  8756. add(V0 + v_index);
  8757. if (t_index > 0) add(T0 + t_index);
  8758. } else {
  8759. let mapped = DECOMP.get(cp);
  8760. if (mapped) {
  8761. buf.push(...mapped);
  8762. } else {
  8763. add(cp);
  8764. }
  8765. }
  8766. if (!buf.length) break;
  8767. cp = buf.pop();
  8768. }
  8769. }
  8770. if (check_order && ret.length > 1) {
  8771. let prev_cc = unpack_cc(ret[0]);
  8772. for (let i = 1; i < ret.length; i++) {
  8773. let cc = unpack_cc(ret[i]);
  8774. if (cc == 0 || prev_cc <= cc) {
  8775. prev_cc = cc;
  8776. continue;
  8777. }
  8778. let j = i-1;
  8779. while (true) {
  8780. let tmp = ret[j+1];
  8781. ret[j+1] = ret[j];
  8782. ret[j] = tmp;
  8783. if (!j) break;
  8784. prev_cc = unpack_cc(ret[--j]);
  8785. if (prev_cc <= cc) break;
  8786. }
  8787. prev_cc = unpack_cc(ret[i]);
  8788. }
  8789. }
  8790. return ret;
  8791. }
  8792. function composed_from_decomposed(v) {
  8793. let ret = [];
  8794. let stack = [];
  8795. let prev_cp = -1;
  8796. let prev_cc = 0;
  8797. for (let packed of v) {
  8798. let cc = unpack_cc(packed);
  8799. let cp = unpack_cp(packed);
  8800. if (prev_cp == -1) {
  8801. if (cc == 0) {
  8802. prev_cp = cp;
  8803. } else {
  8804. ret.push(cp);
  8805. }
  8806. } else if (prev_cc > 0 && prev_cc >= cc) {
  8807. if (cc == 0) {
  8808. ret.push(prev_cp, ...stack);
  8809. stack.length = 0;
  8810. prev_cp = cp;
  8811. } else {
  8812. stack.push(cp);
  8813. }
  8814. prev_cc = cc;
  8815. } else {
  8816. let composed = compose_pair(prev_cp, cp);
  8817. if (composed >= 0) {
  8818. prev_cp = composed;
  8819. } else if (prev_cc == 0 && cc == 0) {
  8820. ret.push(prev_cp);
  8821. prev_cp = cp;
  8822. } else {
  8823. stack.push(cp);
  8824. prev_cc = cc;
  8825. }
  8826. }
  8827. }
  8828. if (prev_cp >= 0) {
  8829. ret.push(prev_cp, ...stack);
  8830. }
  8831. return ret;
  8832. }
  8833. // note: cps can be iterable
  8834. function nfd(cps) {
  8835. return decomposed(cps).map(unpack_cp);
  8836. }
  8837. function nfc(cps) {
  8838. return composed_from_decomposed(decomposed(cps));
  8839. }
  8840. const HYPHEN = 0x2D;
  8841. const STOP_CH = '.';
  8842. const FE0F = 0xFE0F;
  8843. const UNIQUE_PH = 1;
  8844. // 20230913: replace [...v] with Array_from(v) to avoid large spreads
  8845. const Array_from = x => Array.from(x); // Array.from.bind(Array);
  8846. function group_has_cp(g, cp) {
  8847. // 20230913: keep primary and secondary distinct instead of creating valid union
  8848. return g.P.has(cp) || g.Q.has(cp);
  8849. }
  8850. class Emoji extends Array {
  8851. get is_emoji() { return true; } // free tagging system
  8852. }
  8853. let MAPPED, IGNORED, CM, NSM, ESCAPE, GROUPS, WHOLE_VALID, WHOLE_MAP, VALID, EMOJI_LIST, EMOJI_ROOT;
  8854. function init() {
  8855. if (MAPPED) return;
  8856. let r = read_compressed_payload(COMPRESSED$1);
  8857. const read_sorted_array = () => read_sorted(r);
  8858. const read_sorted_set = () => new Set(read_sorted_array());
  8859. const set_add_many = (set, v) => v.forEach(x => set.add(x));
  8860. MAPPED = new Map(read_mapped(r));
  8861. IGNORED = read_sorted_set(); // ignored characters are not valid, so just read raw codepoints
  8862. /*
  8863. // direct include from payload is smaller than the decompression code
  8864. const FENCED = new Map(read_array_while(() => {
  8865. let cp = r();
  8866. if (cp) return [cp, read_str(r())];
  8867. }));
  8868. */
  8869. // 20230217: we still need all CM for proper error formatting
  8870. // but norm only needs NSM subset that are potentially-valid
  8871. CM = read_sorted_array();
  8872. NSM = new Set(read_sorted_array().map(i => CM[i]));
  8873. CM = new Set(CM);
  8874. ESCAPE = read_sorted_set(); // characters that should not be printed
  8875. read_sorted_set(); // only needed to illustrate ens_tokenize() transformations
  8876. let chunks = read_sorted_arrays(r);
  8877. let unrestricted = r();
  8878. //const read_chunked = () => new Set(read_sorted_array().flatMap(i => chunks[i]).concat(read_sorted_array()));
  8879. const read_chunked = () => {
  8880. // 20230921: build set in parts, 2x faster
  8881. let set = new Set();
  8882. read_sorted_array().forEach(i => set_add_many(set, chunks[i]));
  8883. set_add_many(set, read_sorted_array());
  8884. return set;
  8885. };
  8886. GROUPS = read_array_while(i => {
  8887. // minifier property mangling seems unsafe
  8888. // so these are manually renamed to single chars
  8889. let N = read_array_while(r).map(x => x+0x60);
  8890. if (N.length) {
  8891. let R = i >= unrestricted; // unrestricted then restricted
  8892. N[0] -= 32; // capitalize
  8893. N = str_from_cps(N);
  8894. if (R) N=`Restricted[${N}]`;
  8895. let P = read_chunked(); // primary
  8896. let Q = read_chunked(); // secondary
  8897. let M = !r(); // not-whitelisted, check for NSM
  8898. // *** this code currently isn't needed ***
  8899. /*
  8900. let V = [...P, ...Q].sort((a, b) => a-b); // derive: sorted valid
  8901. let M = r()-1; // number of combining mark
  8902. if (M < 0) { // whitelisted
  8903. M = new Map(read_array_while(() => {
  8904. let i = r();
  8905. if (i) return [V[i-1], read_array_while(() => {
  8906. let v = read_array_while(r);
  8907. if (v.length) return v.map(x => x-1);
  8908. })];
  8909. }));
  8910. }*/
  8911. return {N, P, Q, M, R};
  8912. }
  8913. });
  8914. // decode compressed wholes
  8915. WHOLE_VALID = read_sorted_set();
  8916. WHOLE_MAP = new Map();
  8917. let wholes = read_sorted_array().concat(Array_from(WHOLE_VALID)).sort((a, b) => a-b); // must be sorted
  8918. wholes.forEach((cp, i) => {
  8919. let d = r();
  8920. let w = wholes[i] = d ? wholes[i-d] : {V: [], M: new Map()};
  8921. w.V.push(cp); // add to member set
  8922. if (!WHOLE_VALID.has(cp)) {
  8923. WHOLE_MAP.set(cp, w); // register with whole map
  8924. }
  8925. });
  8926. // compute confusable-extent complements
  8927. // usage: WHOLE_MAP.get(cp).M.get(cp) = complement set
  8928. for (let {V, M} of new Set(WHOLE_MAP.values())) {
  8929. // connect all groups that have each whole character
  8930. let recs = [];
  8931. for (let cp of V) {
  8932. let gs = GROUPS.filter(g => group_has_cp(g, cp));
  8933. let rec = recs.find(({G}) => gs.some(g => G.has(g)));
  8934. if (!rec) {
  8935. rec = {G: new Set(), V: []};
  8936. recs.push(rec);
  8937. }
  8938. rec.V.push(cp);
  8939. set_add_many(rec.G, gs);
  8940. }
  8941. // per character cache groups which are not a member of the extent
  8942. let union = recs.flatMap(x => Array_from(x.G)); // all of the groups used by this whole
  8943. for (let {G, V} of recs) {
  8944. let complement = new Set(union.filter(g => !G.has(g))); // groups not covered by the extent
  8945. for (let cp of V) {
  8946. M.set(cp, complement); // this is the same reference
  8947. }
  8948. }
  8949. }
  8950. // compute valid set
  8951. // 20230924: VALID was union but can be re-used
  8952. VALID = new Set(); // exists in 1+ groups
  8953. let multi = new Set(); // exists in 2+ groups
  8954. const add_to_union = cp => VALID.has(cp) ? multi.add(cp) : VALID.add(cp);
  8955. for (let g of GROUPS) {
  8956. for (let cp of g.P) add_to_union(cp);
  8957. for (let cp of g.Q) add_to_union(cp);
  8958. }
  8959. // dual purpose WHOLE_MAP: return placeholder if unique non-confusable
  8960. for (let cp of VALID) {
  8961. if (!WHOLE_MAP.has(cp) && !multi.has(cp)) {
  8962. WHOLE_MAP.set(cp, UNIQUE_PH);
  8963. }
  8964. }
  8965. // add all decomposed parts
  8966. // see derive: "Valid is Closed (via Brute-force)"
  8967. set_add_many(VALID, nfd(VALID));
  8968. // decode emoji
  8969. // 20230719: emoji are now fully-expanded to avoid quirk logic
  8970. EMOJI_LIST = read_trie(r).map(v => Emoji.from(v)).sort(compare_arrays);
  8971. EMOJI_ROOT = new Map(); // this has approx 7K nodes (2+ per emoji)
  8972. for (let cps of EMOJI_LIST) {
  8973. // 20230719: change to *slightly* stricter algorithm which disallows
  8974. // insertion of misplaced FE0F in emoji sequences (matching ENSIP-15)
  8975. // example: beautified [A B] (eg. flag emoji)
  8976. // before: allow: [A FE0F B], error: [A FE0F FE0F B]
  8977. // after: error: both
  8978. // note: this code now matches ENSNormalize.{cs,java} logic
  8979. let prev = [EMOJI_ROOT];
  8980. for (let cp of cps) {
  8981. let next = prev.map(node => {
  8982. let child = node.get(cp);
  8983. if (!child) {
  8984. // should this be object?
  8985. // (most have 1-2 items, few have many)
  8986. // 20230719: no, v8 default map is 4?
  8987. child = new Map();
  8988. node.set(cp, child);
  8989. }
  8990. return child;
  8991. });
  8992. if (cp === FE0F) {
  8993. prev.push(...next); // less than 20 elements
  8994. } else {
  8995. prev = next;
  8996. }
  8997. }
  8998. for (let x of prev) {
  8999. x.V = cps;
  9000. }
  9001. }
  9002. }
  9003. // if escaped: {HEX}
  9004. // else: "x" {HEX}
  9005. function quoted_cp(cp) {
  9006. return (should_escape(cp) ? '' : `${bidi_qq(safe_str_from_cps([cp]))} `) + quote_cp(cp);
  9007. }
  9008. // 20230211: some messages can be mixed-directional and result in spillover
  9009. // use 200E after a quoted string to force the remainder of a string from
  9010. // acquring the direction of the quote
  9011. // https://www.w3.org/International/questions/qa-bidi-unicode-controls#exceptions
  9012. function bidi_qq(s) {
  9013. return `"${s}"\u200E`; // strong LTR
  9014. }
  9015. function check_label_extension(cps) {
  9016. if (cps.length >= 4 && cps[2] == HYPHEN && cps[3] == HYPHEN) {
  9017. throw new Error(`invalid label extension: "${str_from_cps(cps.slice(0, 4))}"`); // this can only be ascii so cant be bidi
  9018. }
  9019. }
  9020. function check_leading_underscore(cps) {
  9021. const UNDERSCORE = 0x5F;
  9022. for (let i = cps.lastIndexOf(UNDERSCORE); i > 0; ) {
  9023. if (cps[--i] !== UNDERSCORE) {
  9024. throw new Error('underscore allowed only at start');
  9025. }
  9026. }
  9027. }
  9028. // check that a fenced cp is not leading, trailing, or touching another fenced cp
  9029. function check_fenced(cps) {
  9030. let cp = cps[0];
  9031. let prev = FENCED.get(cp);
  9032. if (prev) throw error_placement(`leading ${prev}`);
  9033. let n = cps.length;
  9034. let last = -1; // prevents trailing from throwing
  9035. for (let i = 1; i < n; i++) {
  9036. cp = cps[i];
  9037. let match = FENCED.get(cp);
  9038. if (match) {
  9039. // since cps[0] isn't fenced, cps[1] cannot throw
  9040. if (last == i) throw error_placement(`${prev} + ${match}`);
  9041. last = i + 1;
  9042. prev = match;
  9043. }
  9044. }
  9045. if (last == n) throw error_placement(`trailing ${prev}`);
  9046. }
  9047. // create a safe to print string
  9048. // invisibles are escaped
  9049. // leading cm uses placeholder
  9050. // if cps exceed max, middle truncate with ellipsis
  9051. // quoter(cp) => string, eg. 3000 => "{3000}"
  9052. // note: in html, you'd call this function then replace [<>&] with entities
  9053. function safe_str_from_cps(cps, max = Infinity, quoter = quote_cp) {
  9054. //if (Number.isInteger(cps)) cps = [cps];
  9055. //if (!Array.isArray(cps)) throw new TypeError(`expected codepoints`);
  9056. let buf = [];
  9057. if (is_combining_mark(cps[0])) buf.push('◌');
  9058. if (cps.length > max) {
  9059. max >>= 1;
  9060. cps = [...cps.slice(0, max), 0x2026, ...cps.slice(-max)];
  9061. }
  9062. let prev = 0;
  9063. let n = cps.length;
  9064. for (let i = 0; i < n; i++) {
  9065. let cp = cps[i];
  9066. if (should_escape(cp)) {
  9067. buf.push(str_from_cps(cps.slice(prev, i)));
  9068. buf.push(quoter(cp));
  9069. prev = i + 1;
  9070. }
  9071. }
  9072. buf.push(str_from_cps(cps.slice(prev, n)));
  9073. return buf.join('');
  9074. }
  9075. // note: set(s) cannot be exposed because they can be modified
  9076. // note: Object.freeze() doesn't work
  9077. function is_combining_mark(cp) {
  9078. init();
  9079. return CM.has(cp);
  9080. }
  9081. function should_escape(cp) {
  9082. init();
  9083. return ESCAPE.has(cp);
  9084. }
  9085. function ens_normalize(name) {
  9086. return flatten(split(name, nfc, filter_fe0f));
  9087. }
  9088. function split(name, nf, ef) {
  9089. if (!name) return []; // 20230719: empty name allowance
  9090. init();
  9091. let offset = 0;
  9092. // https://unicode.org/reports/tr46/#Validity_Criteria
  9093. // 4.) "The label must not contain a U+002E ( . ) FULL STOP."
  9094. return name.split(STOP_CH).map(label => {
  9095. let input = explode_cp(label);
  9096. let info = {
  9097. input,
  9098. offset, // codepoint, not substring!
  9099. };
  9100. offset += input.length + 1; // + stop
  9101. try {
  9102. // 1.) "The label must be in Unicode Normalization Form NFC"
  9103. let tokens = info.tokens = tokens_from_str(input, nf, ef);
  9104. let token_count = tokens.length;
  9105. let type;
  9106. if (!token_count) { // the label was effectively empty (could of had ignored characters)
  9107. //norm = [];
  9108. //type = 'None'; // use this instead of next match, "ASCII"
  9109. // 20230120: change to strict
  9110. // https://discuss.ens.domains/t/ens-name-normalization-2nd/14564/59
  9111. throw new Error(`empty label`);
  9112. }
  9113. let norm = info.output = tokens.flat();
  9114. check_leading_underscore(norm);
  9115. let emoji = info.emoji = token_count > 1 || tokens[0].is_emoji; // same as: tokens.some(x => x.is_emoji);
  9116. if (!emoji && norm.every(cp => cp < 0x80)) { // special case for ascii
  9117. // 20230123: matches matches WHATWG, see note 3.3
  9118. check_label_extension(norm); // only needed for ascii
  9119. // cant have fenced
  9120. // cant have cm
  9121. // cant have wholes
  9122. // see derive: "Fastpath ASCII"
  9123. type = 'ASCII';
  9124. } else {
  9125. let chars = tokens.flatMap(x => x.is_emoji ? [] : x); // all of the nfc tokens concat together
  9126. if (!chars.length) { // theres no text, just emoji
  9127. type = 'Emoji';
  9128. } else {
  9129. // 5.) "The label must not begin with a combining mark, that is: General_Category=Mark."
  9130. if (CM.has(norm[0])) throw error_placement('leading combining mark');
  9131. for (let i = 1; i < token_count; i++) { // we've already checked the first token
  9132. let cps = tokens[i];
  9133. if (!cps.is_emoji && CM.has(cps[0])) { // every text token has emoji neighbors, eg. EtEEEtEt...
  9134. // bidi_qq() not needed since emoji is LTR and cps is a CM
  9135. throw error_placement(`emoji + combining mark: "${str_from_cps(tokens[i-1])} + ${safe_str_from_cps([cps[0]])}"`);
  9136. }
  9137. }
  9138. check_fenced(norm);
  9139. let unique = Array_from(new Set(chars));
  9140. let [g] = determine_group(unique); // take the first match
  9141. // see derive: "Matching Groups have Same CM Style"
  9142. // alternative: could form a hybrid type: Latin/Japanese/...
  9143. check_group(g, chars); // need text in order
  9144. check_whole(g, unique); // only need unique text (order would be required for multiple-char confusables)
  9145. type = g.N;
  9146. // 20230121: consider exposing restricted flag
  9147. // it's simpler to just check for 'Restricted'
  9148. // or even better: type.endsWith(']')
  9149. //if (g.R) info.restricted = true;
  9150. }
  9151. }
  9152. info.type = type;
  9153. } catch (err) {
  9154. info.error = err; // use full error object
  9155. }
  9156. return info;
  9157. });
  9158. }
  9159. function check_whole(group, unique) {
  9160. let maker;
  9161. let shared = [];
  9162. for (let cp of unique) {
  9163. let whole = WHOLE_MAP.get(cp);
  9164. if (whole === UNIQUE_PH) return; // unique, non-confusable
  9165. if (whole) {
  9166. let set = whole.M.get(cp); // groups which have a character that look-like this character
  9167. maker = maker ? maker.filter(g => set.has(g)) : Array_from(set);
  9168. if (!maker.length) return; // confusable intersection is empty
  9169. } else {
  9170. shared.push(cp);
  9171. }
  9172. }
  9173. if (maker) {
  9174. // we have 1+ confusable
  9175. // check if any of the remaining groups
  9176. // contain the shared characters too
  9177. for (let g of maker) {
  9178. if (shared.every(cp => group_has_cp(g, cp))) {
  9179. throw new Error(`whole-script confusable: ${group.N}/${g.N}`);
  9180. }
  9181. }
  9182. }
  9183. }
  9184. // assumption: unique.size > 0
  9185. // returns list of matching groups
  9186. function determine_group(unique) {
  9187. let groups = GROUPS;
  9188. for (let cp of unique) {
  9189. // note: we need to dodge CM that are whitelisted
  9190. // but that code isn't currently necessary
  9191. let gs = groups.filter(g => group_has_cp(g, cp));
  9192. if (!gs.length) {
  9193. if (!GROUPS.some(g => group_has_cp(g, cp))) {
  9194. // the character was composed of valid parts
  9195. // but it's NFC form is invalid
  9196. // 20230716: change to more exact statement, see: ENSNormalize.{cs,java}
  9197. // note: this doesn't have to be a composition
  9198. // 20230720: change to full check
  9199. throw error_disallowed(cp); // this should be rare
  9200. } else {
  9201. // there is no group that contains all these characters
  9202. // throw using the highest priority group that matched
  9203. // https://www.unicode.org/reports/tr39/#mixed_script_confusables
  9204. throw error_group_member(groups[0], cp);
  9205. }
  9206. }
  9207. groups = gs;
  9208. if (gs.length == 1) break; // there is only one group left
  9209. }
  9210. // there are at least 1 group(s) with all of these characters
  9211. return groups;
  9212. }
  9213. // throw on first error
  9214. function flatten(split) {
  9215. return split.map(({input, error, output}) => {
  9216. if (error) {
  9217. // don't print label again if just a single label
  9218. let msg = error.message;
  9219. // bidi_qq() only necessary if msg is digits
  9220. throw new Error(split.length == 1 ? msg : `Invalid label ${bidi_qq(safe_str_from_cps(input, 63))}: ${msg}`);
  9221. }
  9222. return str_from_cps(output);
  9223. }).join(STOP_CH);
  9224. }
  9225. function error_disallowed(cp) {
  9226. // TODO: add cp to error?
  9227. return new Error(`disallowed character: ${quoted_cp(cp)}`);
  9228. }
  9229. function error_group_member(g, cp) {
  9230. let quoted = quoted_cp(cp);
  9231. let gg = GROUPS.find(g => g.P.has(cp)); // only check primary
  9232. if (gg) {
  9233. quoted = `${gg.N} ${quoted}`;
  9234. }
  9235. return new Error(`illegal mixture: ${g.N} + ${quoted}`);
  9236. }
  9237. function error_placement(where) {
  9238. return new Error(`illegal placement: ${where}`);
  9239. }
  9240. // assumption: cps.length > 0
  9241. // assumption: cps[0] isn't a CM
  9242. // assumption: the previous character isn't an emoji
  9243. function check_group(g, cps) {
  9244. for (let cp of cps) {
  9245. if (!group_has_cp(g, cp)) {
  9246. // for whitelisted scripts, this will throw illegal mixture on invalid cm, eg. "e{300}{300}"
  9247. // at the moment, it's unnecessary to introduce an extra error type
  9248. // until there exists a whitelisted multi-character
  9249. // eg. if (M < 0 && is_combining_mark(cp)) { ... }
  9250. // there are 3 cases:
  9251. // 1. illegal cm for wrong group => mixture error
  9252. // 2. illegal cm for same group => cm error
  9253. // requires set of whitelist cm per group:
  9254. // eg. new Set([...g.P, ...g.Q].flatMap(nfc).filter(cp => CM.has(cp)))
  9255. // 3. wrong group => mixture error
  9256. throw error_group_member(g, cp);
  9257. }
  9258. }
  9259. //if (M >= 0) { // we have a known fixed cm count
  9260. if (g.M) { // we need to check for NSM
  9261. let decomposed = nfd(cps);
  9262. for (let i = 1, e = decomposed.length; i < e; i++) { // see: assumption
  9263. // 20230210: bugfix: using cps instead of decomposed h/t Carbon225
  9264. /*
  9265. if (CM.has(decomposed[i])) {
  9266. let j = i + 1;
  9267. while (j < e && CM.has(decomposed[j])) j++;
  9268. if (j - i > M) {
  9269. throw new Error(`too many combining marks: ${g.N} ${bidi_qq(str_from_cps(decomposed.slice(i-1, j)))} (${j-i}/${M})`);
  9270. }
  9271. i = j;
  9272. }
  9273. */
  9274. // 20230217: switch to NSM counting
  9275. // https://www.unicode.org/reports/tr39/#Optional_Detection
  9276. if (NSM.has(decomposed[i])) {
  9277. let j = i + 1;
  9278. for (let cp; j < e && NSM.has(cp = decomposed[j]); j++) {
  9279. // a. Forbid sequences of the same nonspacing mark.
  9280. for (let k = i; k < j; k++) { // O(n^2) but n < 100
  9281. if (decomposed[k] == cp) {
  9282. throw new Error(`duplicate non-spacing marks: ${quoted_cp(cp)}`);
  9283. }
  9284. }
  9285. }
  9286. // parse to end so we have full nsm count
  9287. // b. Forbid sequences of more than 4 nonspacing marks (gc=Mn or gc=Me).
  9288. if (j - i > NSM_MAX) {
  9289. // note: this slice starts with a base char or spacing-mark cm
  9290. throw new Error(`excessive non-spacing marks: ${bidi_qq(safe_str_from_cps(decomposed.slice(i-1, j)))} (${j-i}/${NSM_MAX})`);
  9291. }
  9292. i = j;
  9293. }
  9294. }
  9295. }
  9296. // *** this code currently isn't needed ***
  9297. /*
  9298. let cm_whitelist = M instanceof Map;
  9299. for (let i = 0, e = cps.length; i < e; ) {
  9300. let cp = cps[i++];
  9301. let seqs = cm_whitelist && M.get(cp);
  9302. if (seqs) {
  9303. // list of codepoints that can follow
  9304. // if this exists, this will always be 1+
  9305. let j = i;
  9306. while (j < e && CM.has(cps[j])) j++;
  9307. let cms = cps.slice(i, j);
  9308. let match = seqs.find(seq => !compare_arrays(seq, cms));
  9309. if (!match) throw new Error(`disallowed combining mark sequence: "${safe_str_from_cps([cp, ...cms])}"`);
  9310. i = j;
  9311. } else if (!V.has(cp)) {
  9312. // https://www.unicode.org/reports/tr39/#mixed_script_confusables
  9313. let quoted = quoted_cp(cp);
  9314. for (let cp of cps) {
  9315. let u = UNIQUE.get(cp);
  9316. if (u && u !== g) {
  9317. // if both scripts are restricted this error is confusing
  9318. // because we don't differentiate RestrictedA from RestrictedB
  9319. if (!u.R) quoted = `${quoted} is ${u.N}`;
  9320. break;
  9321. }
  9322. }
  9323. throw new Error(`disallowed ${g.N} character: ${quoted}`);
  9324. //throw new Error(`disallowed character: ${quoted} (expected ${g.N})`);
  9325. //throw new Error(`${g.N} does not allow: ${quoted}`);
  9326. }
  9327. }
  9328. if (!cm_whitelist) {
  9329. let decomposed = nfd(cps);
  9330. for (let i = 1, e = decomposed.length; i < e; i++) { // we know it can't be cm leading
  9331. if (CM.has(decomposed[i])) {
  9332. let j = i + 1;
  9333. while (j < e && CM.has(decomposed[j])) j++;
  9334. if (j - i > M) {
  9335. throw new Error(`too many combining marks: "${str_from_cps(decomposed.slice(i-1, j))}" (${j-i}/${M})`);
  9336. }
  9337. i = j;
  9338. }
  9339. }
  9340. }
  9341. */
  9342. }
  9343. // given a list of codepoints
  9344. // returns a list of lists, where emoji are a fully-qualified (as Array subclass)
  9345. // eg. explode_cp("abc💩d") => [[61, 62, 63], Emoji[1F4A9, FE0F], [64]]
  9346. // 20230818: rename for 'process' name collision h/t Javarome
  9347. // https://github.com/adraffy/ens-normalize.js/issues/23
  9348. function tokens_from_str(input, nf, ef) {
  9349. let ret = [];
  9350. let chars = [];
  9351. input = input.slice().reverse(); // flip so we can pop
  9352. while (input.length) {
  9353. let emoji = consume_emoji_reversed(input);
  9354. if (emoji) {
  9355. if (chars.length) {
  9356. ret.push(nf(chars));
  9357. chars = [];
  9358. }
  9359. ret.push(ef(emoji));
  9360. } else {
  9361. let cp = input.pop();
  9362. if (VALID.has(cp)) {
  9363. chars.push(cp);
  9364. } else {
  9365. let cps = MAPPED.get(cp);
  9366. if (cps) {
  9367. chars.push(...cps); // less than 10 elements
  9368. } else if (!IGNORED.has(cp)) {
  9369. // 20230912: unicode 15.1 changed the order of processing such that
  9370. // disallowed parts are only rejected after NFC
  9371. // https://unicode.org/reports/tr46/#Validity_Criteria
  9372. // this doesn't impact normalization as of today
  9373. // technically, this error can be removed as the group logic will apply similar logic
  9374. // however the error type might be less clear
  9375. throw error_disallowed(cp);
  9376. }
  9377. }
  9378. }
  9379. }
  9380. if (chars.length) {
  9381. ret.push(nf(chars));
  9382. }
  9383. return ret;
  9384. }
  9385. function filter_fe0f(cps) {
  9386. return cps.filter(cp => cp != FE0F);
  9387. }
  9388. // given array of codepoints
  9389. // returns the longest valid emoji sequence (or undefined if no match)
  9390. // *MUTATES* the supplied array
  9391. // disallows interleaved ignored characters
  9392. // fills (optional) eaten array with matched codepoints
  9393. function consume_emoji_reversed(cps, eaten) {
  9394. let node = EMOJI_ROOT;
  9395. let emoji;
  9396. let pos = cps.length;
  9397. while (pos) {
  9398. node = node.get(cps[--pos]);
  9399. if (!node) break;
  9400. let {V} = node;
  9401. if (V) { // this is a valid emoji (so far)
  9402. emoji = V;
  9403. cps.length = pos; // truncate
  9404. }
  9405. }
  9406. return emoji;
  9407. }
  9408. const Zeros = new Uint8Array(32);
  9409. Zeros.fill(0);
  9410. function checkComponent(comp) {
  9411. assertArgument(comp.length !== 0, "invalid ENS name; empty component", "comp", comp);
  9412. return comp;
  9413. }
  9414. function ensNameSplit(name) {
  9415. const bytes = toUtf8Bytes(ensNormalize(name));
  9416. const comps = [];
  9417. if (name.length === 0) {
  9418. return comps;
  9419. }
  9420. let last = 0;
  9421. for (let i = 0; i < bytes.length; i++) {
  9422. const d = bytes[i];
  9423. // A separator (i.e. "."); copy this component
  9424. if (d === 0x2e) {
  9425. comps.push(checkComponent(bytes.slice(last, i)));
  9426. last = i + 1;
  9427. }
  9428. }
  9429. // There was a stray separator at the end of the name
  9430. assertArgument(last < bytes.length, "invalid ENS name; empty component", "name", name);
  9431. comps.push(checkComponent(bytes.slice(last)));
  9432. return comps;
  9433. }
  9434. /**
  9435. * Returns the ENS %%name%% normalized.
  9436. */
  9437. function ensNormalize(name) {
  9438. try {
  9439. if (name.length === 0) {
  9440. throw new Error("empty label");
  9441. }
  9442. return ens_normalize(name);
  9443. }
  9444. catch (error) {
  9445. assertArgument(false, `invalid ENS name (${error.message})`, "name", name);
  9446. }
  9447. }
  9448. /**
  9449. * Returns ``true`` if %%name%% is a valid ENS name.
  9450. */
  9451. function isValidName(name) {
  9452. try {
  9453. return (ensNameSplit(name).length !== 0);
  9454. }
  9455. catch (error) { }
  9456. return false;
  9457. }
  9458. /**
  9459. * Returns the [[link-namehash]] for %%name%%.
  9460. */
  9461. function namehash(name) {
  9462. assertArgument(typeof (name) === "string", "invalid ENS name; not a string", "name", name);
  9463. assertArgument(name.length, `invalid ENS name (empty label)`, "name", name);
  9464. let result = Zeros;
  9465. const comps = ensNameSplit(name);
  9466. while (comps.length) {
  9467. result = keccak256(concat([result, keccak256((comps.pop()))]));
  9468. }
  9469. return hexlify(result);
  9470. }
  9471. /**
  9472. * Returns the DNS encoded %%name%%.
  9473. *
  9474. * This is used for various parts of ENS name resolution, such
  9475. * as the wildcard resolution.
  9476. */
  9477. function dnsEncode(name, _maxLength) {
  9478. const length = (_maxLength != null) ? _maxLength : 63;
  9479. assertArgument(length <= 255, "DNS encoded label cannot exceed 255", "length", length);
  9480. return hexlify(concat(ensNameSplit(name).map((comp) => {
  9481. assertArgument(comp.length <= length, `label ${JSON.stringify(name)} exceeds ${length} bytes`, "name", name);
  9482. const bytes = new Uint8Array(comp.length + 1);
  9483. bytes.set(comp, 1);
  9484. bytes[0] = bytes.length - 1;
  9485. return bytes;
  9486. }))) + "00";
  9487. }
  9488. function accessSetify(addr, storageKeys) {
  9489. return {
  9490. address: getAddress(addr),
  9491. storageKeys: storageKeys.map((storageKey, index) => {
  9492. assertArgument(isHexString(storageKey, 32), "invalid slot", `storageKeys[${index}]`, storageKey);
  9493. return storageKey.toLowerCase();
  9494. })
  9495. };
  9496. }
  9497. /**
  9498. * Returns a [[AccessList]] from any ethers-supported access-list structure.
  9499. */
  9500. function accessListify(value) {
  9501. if (Array.isArray(value)) {
  9502. return value.map((set, index) => {
  9503. if (Array.isArray(set)) {
  9504. assertArgument(set.length === 2, "invalid slot set", `value[${index}]`, set);
  9505. return accessSetify(set[0], set[1]);
  9506. }
  9507. assertArgument(set != null && typeof (set) === "object", "invalid address-slot set", "value", value);
  9508. return accessSetify(set.address, set.storageKeys);
  9509. });
  9510. }
  9511. assertArgument(value != null && typeof (value) === "object", "invalid access list", "value", value);
  9512. const result = Object.keys(value).map((addr) => {
  9513. const storageKeys = value[addr].reduce((accum, storageKey) => {
  9514. accum[storageKey] = true;
  9515. return accum;
  9516. }, {});
  9517. return accessSetify(addr, Object.keys(storageKeys).sort());
  9518. });
  9519. result.sort((a, b) => (a.address.localeCompare(b.address)));
  9520. return result;
  9521. }
  9522. /**
  9523. * Returns the address for the %%key%%.
  9524. *
  9525. * The key may be any standard form of public key or a private key.
  9526. */
  9527. function computeAddress(key) {
  9528. let pubkey;
  9529. if (typeof (key) === "string") {
  9530. pubkey = SigningKey.computePublicKey(key, false);
  9531. }
  9532. else {
  9533. pubkey = key.publicKey;
  9534. }
  9535. return getAddress(keccak256("0x" + pubkey.substring(4)).substring(26));
  9536. }
  9537. /**
  9538. * Returns the recovered address for the private key that was
  9539. * used to sign %%digest%% that resulted in %%signature%%.
  9540. */
  9541. function recoverAddress(digest, signature) {
  9542. return computeAddress(SigningKey.recoverPublicKey(digest, signature));
  9543. }
  9544. const BN_0$4 = BigInt(0);
  9545. const BN_2$2 = BigInt(2);
  9546. const BN_27 = BigInt(27);
  9547. const BN_28 = BigInt(28);
  9548. const BN_35 = BigInt(35);
  9549. const BN_MAX_UINT = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
  9550. const BLOB_SIZE = 4096 * 32;
  9551. function getVersionedHash(version, hash) {
  9552. let versioned = version.toString(16);
  9553. while (versioned.length < 2) {
  9554. versioned = "0" + versioned;
  9555. }
  9556. versioned += sha256(hash).substring(4);
  9557. return "0x" + versioned;
  9558. }
  9559. function handleAddress(value) {
  9560. if (value === "0x") {
  9561. return null;
  9562. }
  9563. return getAddress(value);
  9564. }
  9565. function handleAccessList(value, param) {
  9566. try {
  9567. return accessListify(value);
  9568. }
  9569. catch (error) {
  9570. assertArgument(false, error.message, param, value);
  9571. }
  9572. }
  9573. function handleNumber(_value, param) {
  9574. if (_value === "0x") {
  9575. return 0;
  9576. }
  9577. return getNumber(_value, param);
  9578. }
  9579. function handleUint(_value, param) {
  9580. if (_value === "0x") {
  9581. return BN_0$4;
  9582. }
  9583. const value = getBigInt(_value, param);
  9584. assertArgument(value <= BN_MAX_UINT, "value exceeds uint size", param, value);
  9585. return value;
  9586. }
  9587. function formatNumber(_value, name) {
  9588. const value = getBigInt(_value, "value");
  9589. const result = toBeArray(value);
  9590. assertArgument(result.length <= 32, `value too large`, `tx.${name}`, value);
  9591. return result;
  9592. }
  9593. function formatAccessList(value) {
  9594. return accessListify(value).map((set) => [set.address, set.storageKeys]);
  9595. }
  9596. function formatHashes(value, param) {
  9597. assertArgument(Array.isArray(value), `invalid ${param}`, "value", value);
  9598. for (let i = 0; i < value.length; i++) {
  9599. assertArgument(isHexString(value[i], 32), "invalid ${ param } hash", `value[${i}]`, value[i]);
  9600. }
  9601. return value;
  9602. }
  9603. function _parseLegacy(data) {
  9604. const fields = decodeRlp(data);
  9605. assertArgument(Array.isArray(fields) && (fields.length === 9 || fields.length === 6), "invalid field count for legacy transaction", "data", data);
  9606. const tx = {
  9607. type: 0,
  9608. nonce: handleNumber(fields[0], "nonce"),
  9609. gasPrice: handleUint(fields[1], "gasPrice"),
  9610. gasLimit: handleUint(fields[2], "gasLimit"),
  9611. to: handleAddress(fields[3]),
  9612. value: handleUint(fields[4], "value"),
  9613. data: hexlify(fields[5]),
  9614. chainId: BN_0$4
  9615. };
  9616. // Legacy unsigned transaction
  9617. if (fields.length === 6) {
  9618. return tx;
  9619. }
  9620. const v = handleUint(fields[6], "v");
  9621. const r = handleUint(fields[7], "r");
  9622. const s = handleUint(fields[8], "s");
  9623. if (r === BN_0$4 && s === BN_0$4) {
  9624. // EIP-155 unsigned transaction
  9625. tx.chainId = v;
  9626. }
  9627. else {
  9628. // Compute the EIP-155 chain ID (or 0 for legacy)
  9629. let chainId = (v - BN_35) / BN_2$2;
  9630. if (chainId < BN_0$4) {
  9631. chainId = BN_0$4;
  9632. }
  9633. tx.chainId = chainId;
  9634. // Signed Legacy Transaction
  9635. assertArgument(chainId !== BN_0$4 || (v === BN_27 || v === BN_28), "non-canonical legacy v", "v", fields[6]);
  9636. tx.signature = Signature.from({
  9637. r: zeroPadValue(fields[7], 32),
  9638. s: zeroPadValue(fields[8], 32),
  9639. v
  9640. });
  9641. //tx.hash = keccak256(data);
  9642. }
  9643. return tx;
  9644. }
  9645. function _serializeLegacy(tx, sig) {
  9646. const fields = [
  9647. formatNumber(tx.nonce, "nonce"),
  9648. formatNumber(tx.gasPrice || 0, "gasPrice"),
  9649. formatNumber(tx.gasLimit, "gasLimit"),
  9650. (tx.to || "0x"),
  9651. formatNumber(tx.value, "value"),
  9652. tx.data,
  9653. ];
  9654. let chainId = BN_0$4;
  9655. if (tx.chainId != BN_0$4) {
  9656. // A chainId was provided; if non-zero we'll use EIP-155
  9657. chainId = getBigInt(tx.chainId, "tx.chainId");
  9658. // We have a chainId in the tx and an EIP-155 v in the signature,
  9659. // make sure they agree with each other
  9660. assertArgument(!sig || sig.networkV == null || sig.legacyChainId === chainId, "tx.chainId/sig.v mismatch", "sig", sig);
  9661. }
  9662. else if (tx.signature) {
  9663. // No explicit chainId, but EIP-155 have a derived implicit chainId
  9664. const legacy = tx.signature.legacyChainId;
  9665. if (legacy != null) {
  9666. chainId = legacy;
  9667. }
  9668. }
  9669. // Requesting an unsigned transaction
  9670. if (!sig) {
  9671. // We have an EIP-155 transaction (chainId was specified and non-zero)
  9672. if (chainId !== BN_0$4) {
  9673. fields.push(toBeArray(chainId));
  9674. fields.push("0x");
  9675. fields.push("0x");
  9676. }
  9677. return encodeRlp(fields);
  9678. }
  9679. // @TODO: We should probably check that tx.signature, chainId, and sig
  9680. // match but that logic could break existing code, so schedule
  9681. // this for the next major bump.
  9682. // Compute the EIP-155 v
  9683. let v = BigInt(27 + sig.yParity);
  9684. if (chainId !== BN_0$4) {
  9685. v = Signature.getChainIdV(chainId, sig.v);
  9686. }
  9687. else if (BigInt(sig.v) !== v) {
  9688. assertArgument(false, "tx.chainId/sig.v mismatch", "sig", sig);
  9689. }
  9690. // Add the signature
  9691. fields.push(toBeArray(v));
  9692. fields.push(toBeArray(sig.r));
  9693. fields.push(toBeArray(sig.s));
  9694. return encodeRlp(fields);
  9695. }
  9696. function _parseEipSignature(tx, fields) {
  9697. let yParity;
  9698. try {
  9699. yParity = handleNumber(fields[0], "yParity");
  9700. if (yParity !== 0 && yParity !== 1) {
  9701. throw new Error("bad yParity");
  9702. }
  9703. }
  9704. catch (error) {
  9705. assertArgument(false, "invalid yParity", "yParity", fields[0]);
  9706. }
  9707. const r = zeroPadValue(fields[1], 32);
  9708. const s = zeroPadValue(fields[2], 32);
  9709. const signature = Signature.from({ r, s, yParity });
  9710. tx.signature = signature;
  9711. }
  9712. function _parseEip1559(data) {
  9713. const fields = decodeRlp(getBytes(data).slice(1));
  9714. assertArgument(Array.isArray(fields) && (fields.length === 9 || fields.length === 12), "invalid field count for transaction type: 2", "data", hexlify(data));
  9715. const tx = {
  9716. type: 2,
  9717. chainId: handleUint(fields[0], "chainId"),
  9718. nonce: handleNumber(fields[1], "nonce"),
  9719. maxPriorityFeePerGas: handleUint(fields[2], "maxPriorityFeePerGas"),
  9720. maxFeePerGas: handleUint(fields[3], "maxFeePerGas"),
  9721. gasPrice: null,
  9722. gasLimit: handleUint(fields[4], "gasLimit"),
  9723. to: handleAddress(fields[5]),
  9724. value: handleUint(fields[6], "value"),
  9725. data: hexlify(fields[7]),
  9726. accessList: handleAccessList(fields[8], "accessList"),
  9727. };
  9728. // Unsigned EIP-1559 Transaction
  9729. if (fields.length === 9) {
  9730. return tx;
  9731. }
  9732. //tx.hash = keccak256(data);
  9733. _parseEipSignature(tx, fields.slice(9));
  9734. return tx;
  9735. }
  9736. function _serializeEip1559(tx, sig) {
  9737. const fields = [
  9738. formatNumber(tx.chainId, "chainId"),
  9739. formatNumber(tx.nonce, "nonce"),
  9740. formatNumber(tx.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"),
  9741. formatNumber(tx.maxFeePerGas || 0, "maxFeePerGas"),
  9742. formatNumber(tx.gasLimit, "gasLimit"),
  9743. (tx.to || "0x"),
  9744. formatNumber(tx.value, "value"),
  9745. tx.data,
  9746. formatAccessList(tx.accessList || [])
  9747. ];
  9748. if (sig) {
  9749. fields.push(formatNumber(sig.yParity, "yParity"));
  9750. fields.push(toBeArray(sig.r));
  9751. fields.push(toBeArray(sig.s));
  9752. }
  9753. return concat(["0x02", encodeRlp(fields)]);
  9754. }
  9755. function _parseEip2930(data) {
  9756. const fields = decodeRlp(getBytes(data).slice(1));
  9757. assertArgument(Array.isArray(fields) && (fields.length === 8 || fields.length === 11), "invalid field count for transaction type: 1", "data", hexlify(data));
  9758. const tx = {
  9759. type: 1,
  9760. chainId: handleUint(fields[0], "chainId"),
  9761. nonce: handleNumber(fields[1], "nonce"),
  9762. gasPrice: handleUint(fields[2], "gasPrice"),
  9763. gasLimit: handleUint(fields[3], "gasLimit"),
  9764. to: handleAddress(fields[4]),
  9765. value: handleUint(fields[5], "value"),
  9766. data: hexlify(fields[6]),
  9767. accessList: handleAccessList(fields[7], "accessList")
  9768. };
  9769. // Unsigned EIP-2930 Transaction
  9770. if (fields.length === 8) {
  9771. return tx;
  9772. }
  9773. //tx.hash = keccak256(data);
  9774. _parseEipSignature(tx, fields.slice(8));
  9775. return tx;
  9776. }
  9777. function _serializeEip2930(tx, sig) {
  9778. const fields = [
  9779. formatNumber(tx.chainId, "chainId"),
  9780. formatNumber(tx.nonce, "nonce"),
  9781. formatNumber(tx.gasPrice || 0, "gasPrice"),
  9782. formatNumber(tx.gasLimit, "gasLimit"),
  9783. (tx.to || "0x"),
  9784. formatNumber(tx.value, "value"),
  9785. tx.data,
  9786. formatAccessList(tx.accessList || [])
  9787. ];
  9788. if (sig) {
  9789. fields.push(formatNumber(sig.yParity, "recoveryParam"));
  9790. fields.push(toBeArray(sig.r));
  9791. fields.push(toBeArray(sig.s));
  9792. }
  9793. return concat(["0x01", encodeRlp(fields)]);
  9794. }
  9795. function _parseEip4844(data) {
  9796. let fields = decodeRlp(getBytes(data).slice(1));
  9797. let typeName = "3";
  9798. let blobs = null;
  9799. // Parse the network format
  9800. if (fields.length === 4 && Array.isArray(fields[0])) {
  9801. typeName = "3 (network format)";
  9802. const fBlobs = fields[1], fCommits = fields[2], fProofs = fields[3];
  9803. assertArgument(Array.isArray(fBlobs), "invalid network format: blobs not an array", "fields[1]", fBlobs);
  9804. assertArgument(Array.isArray(fCommits), "invalid network format: commitments not an array", "fields[2]", fCommits);
  9805. assertArgument(Array.isArray(fProofs), "invalid network format: proofs not an array", "fields[3]", fProofs);
  9806. assertArgument(fBlobs.length === fCommits.length, "invalid network format: blobs/commitments length mismatch", "fields", fields);
  9807. assertArgument(fBlobs.length === fProofs.length, "invalid network format: blobs/proofs length mismatch", "fields", fields);
  9808. blobs = [];
  9809. for (let i = 0; i < fields[1].length; i++) {
  9810. blobs.push({
  9811. data: fBlobs[i],
  9812. commitment: fCommits[i],
  9813. proof: fProofs[i],
  9814. });
  9815. }
  9816. fields = fields[0];
  9817. }
  9818. assertArgument(Array.isArray(fields) && (fields.length === 11 || fields.length === 14), `invalid field count for transaction type: ${typeName}`, "data", hexlify(data));
  9819. const tx = {
  9820. type: 3,
  9821. chainId: handleUint(fields[0], "chainId"),
  9822. nonce: handleNumber(fields[1], "nonce"),
  9823. maxPriorityFeePerGas: handleUint(fields[2], "maxPriorityFeePerGas"),
  9824. maxFeePerGas: handleUint(fields[3], "maxFeePerGas"),
  9825. gasPrice: null,
  9826. gasLimit: handleUint(fields[4], "gasLimit"),
  9827. to: handleAddress(fields[5]),
  9828. value: handleUint(fields[6], "value"),
  9829. data: hexlify(fields[7]),
  9830. accessList: handleAccessList(fields[8], "accessList"),
  9831. maxFeePerBlobGas: handleUint(fields[9], "maxFeePerBlobGas"),
  9832. blobVersionedHashes: fields[10]
  9833. };
  9834. if (blobs) {
  9835. tx.blobs = blobs;
  9836. }
  9837. assertArgument(tx.to != null, `invalid address for transaction type: ${typeName}`, "data", data);
  9838. assertArgument(Array.isArray(tx.blobVersionedHashes), "invalid blobVersionedHashes: must be an array", "data", data);
  9839. for (let i = 0; i < tx.blobVersionedHashes.length; i++) {
  9840. assertArgument(isHexString(tx.blobVersionedHashes[i], 32), `invalid blobVersionedHash at index ${i}: must be length 32`, "data", data);
  9841. }
  9842. // Unsigned EIP-4844 Transaction
  9843. if (fields.length === 11) {
  9844. return tx;
  9845. }
  9846. // @TODO: Do we need to do this? This is only called internally
  9847. // and used to verify hashes; it might save time to not do this
  9848. //tx.hash = keccak256(concat([ "0x03", encodeRlp(fields) ]));
  9849. _parseEipSignature(tx, fields.slice(11));
  9850. return tx;
  9851. }
  9852. function _serializeEip4844(tx, sig, blobs) {
  9853. const fields = [
  9854. formatNumber(tx.chainId, "chainId"),
  9855. formatNumber(tx.nonce, "nonce"),
  9856. formatNumber(tx.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"),
  9857. formatNumber(tx.maxFeePerGas || 0, "maxFeePerGas"),
  9858. formatNumber(tx.gasLimit, "gasLimit"),
  9859. (tx.to || ZeroAddress),
  9860. formatNumber(tx.value, "value"),
  9861. tx.data,
  9862. formatAccessList(tx.accessList || []),
  9863. formatNumber(tx.maxFeePerBlobGas || 0, "maxFeePerBlobGas"),
  9864. formatHashes(tx.blobVersionedHashes || [], "blobVersionedHashes")
  9865. ];
  9866. if (sig) {
  9867. fields.push(formatNumber(sig.yParity, "yParity"));
  9868. fields.push(toBeArray(sig.r));
  9869. fields.push(toBeArray(sig.s));
  9870. // We have blobs; return the network wrapped format
  9871. if (blobs) {
  9872. return concat([
  9873. "0x03",
  9874. encodeRlp([
  9875. fields,
  9876. blobs.map((b) => b.data),
  9877. blobs.map((b) => b.commitment),
  9878. blobs.map((b) => b.proof),
  9879. ])
  9880. ]);
  9881. }
  9882. }
  9883. return concat(["0x03", encodeRlp(fields)]);
  9884. }
  9885. /**
  9886. * A **Transaction** describes an operation to be executed on
  9887. * Ethereum by an Externally Owned Account (EOA). It includes
  9888. * who (the [[to]] address), what (the [[data]]) and how much (the
  9889. * [[value]] in ether) the operation should entail.
  9890. *
  9891. * @example:
  9892. * tx = new Transaction()
  9893. * //_result:
  9894. *
  9895. * tx.data = "0x1234";
  9896. * //_result:
  9897. */
  9898. class Transaction {
  9899. #type;
  9900. #to;
  9901. #data;
  9902. #nonce;
  9903. #gasLimit;
  9904. #gasPrice;
  9905. #maxPriorityFeePerGas;
  9906. #maxFeePerGas;
  9907. #value;
  9908. #chainId;
  9909. #sig;
  9910. #accessList;
  9911. #maxFeePerBlobGas;
  9912. #blobVersionedHashes;
  9913. #kzg;
  9914. #blobs;
  9915. /**
  9916. * The transaction type.
  9917. *
  9918. * If null, the type will be automatically inferred based on
  9919. * explicit properties.
  9920. */
  9921. get type() { return this.#type; }
  9922. set type(value) {
  9923. switch (value) {
  9924. case null:
  9925. this.#type = null;
  9926. break;
  9927. case 0:
  9928. case "legacy":
  9929. this.#type = 0;
  9930. break;
  9931. case 1:
  9932. case "berlin":
  9933. case "eip-2930":
  9934. this.#type = 1;
  9935. break;
  9936. case 2:
  9937. case "london":
  9938. case "eip-1559":
  9939. this.#type = 2;
  9940. break;
  9941. case 3:
  9942. case "cancun":
  9943. case "eip-4844":
  9944. this.#type = 3;
  9945. break;
  9946. default:
  9947. assertArgument(false, "unsupported transaction type", "type", value);
  9948. }
  9949. }
  9950. /**
  9951. * The name of the transaction type.
  9952. */
  9953. get typeName() {
  9954. switch (this.type) {
  9955. case 0: return "legacy";
  9956. case 1: return "eip-2930";
  9957. case 2: return "eip-1559";
  9958. case 3: return "eip-4844";
  9959. }
  9960. return null;
  9961. }
  9962. /**
  9963. * The ``to`` address for the transaction or ``null`` if the
  9964. * transaction is an ``init`` transaction.
  9965. */
  9966. get to() {
  9967. const value = this.#to;
  9968. if (value == null && this.type === 3) {
  9969. return ZeroAddress;
  9970. }
  9971. return value;
  9972. }
  9973. set to(value) {
  9974. this.#to = (value == null) ? null : getAddress(value);
  9975. }
  9976. /**
  9977. * The transaction nonce.
  9978. */
  9979. get nonce() { return this.#nonce; }
  9980. set nonce(value) { this.#nonce = getNumber(value, "value"); }
  9981. /**
  9982. * The gas limit.
  9983. */
  9984. get gasLimit() { return this.#gasLimit; }
  9985. set gasLimit(value) { this.#gasLimit = getBigInt(value); }
  9986. /**
  9987. * The gas price.
  9988. *
  9989. * On legacy networks this defines the fee that will be paid. On
  9990. * EIP-1559 networks, this should be ``null``.
  9991. */
  9992. get gasPrice() {
  9993. const value = this.#gasPrice;
  9994. if (value == null && (this.type === 0 || this.type === 1)) {
  9995. return BN_0$4;
  9996. }
  9997. return value;
  9998. }
  9999. set gasPrice(value) {
  10000. this.#gasPrice = (value == null) ? null : getBigInt(value, "gasPrice");
  10001. }
  10002. /**
  10003. * The maximum priority fee per unit of gas to pay. On legacy
  10004. * networks this should be ``null``.
  10005. */
  10006. get maxPriorityFeePerGas() {
  10007. const value = this.#maxPriorityFeePerGas;
  10008. if (value == null) {
  10009. if (this.type === 2 || this.type === 3) {
  10010. return BN_0$4;
  10011. }
  10012. return null;
  10013. }
  10014. return value;
  10015. }
  10016. set maxPriorityFeePerGas(value) {
  10017. this.#maxPriorityFeePerGas = (value == null) ? null : getBigInt(value, "maxPriorityFeePerGas");
  10018. }
  10019. /**
  10020. * The maximum total fee per unit of gas to pay. On legacy
  10021. * networks this should be ``null``.
  10022. */
  10023. get maxFeePerGas() {
  10024. const value = this.#maxFeePerGas;
  10025. if (value == null) {
  10026. if (this.type === 2 || this.type === 3) {
  10027. return BN_0$4;
  10028. }
  10029. return null;
  10030. }
  10031. return value;
  10032. }
  10033. set maxFeePerGas(value) {
  10034. this.#maxFeePerGas = (value == null) ? null : getBigInt(value, "maxFeePerGas");
  10035. }
  10036. /**
  10037. * The transaction data. For ``init`` transactions this is the
  10038. * deployment code.
  10039. */
  10040. get data() { return this.#data; }
  10041. set data(value) { this.#data = hexlify(value); }
  10042. /**
  10043. * The amount of ether (in wei) to send in this transactions.
  10044. */
  10045. get value() { return this.#value; }
  10046. set value(value) {
  10047. this.#value = getBigInt(value, "value");
  10048. }
  10049. /**
  10050. * The chain ID this transaction is valid on.
  10051. */
  10052. get chainId() { return this.#chainId; }
  10053. set chainId(value) { this.#chainId = getBigInt(value); }
  10054. /**
  10055. * If signed, the signature for this transaction.
  10056. */
  10057. get signature() { return this.#sig || null; }
  10058. set signature(value) {
  10059. this.#sig = (value == null) ? null : Signature.from(value);
  10060. }
  10061. /**
  10062. * The access list.
  10063. *
  10064. * An access list permits discounted (but pre-paid) access to
  10065. * bytecode and state variable access within contract execution.
  10066. */
  10067. get accessList() {
  10068. const value = this.#accessList || null;
  10069. if (value == null) {
  10070. if (this.type === 1 || this.type === 2 || this.type === 3) {
  10071. // @TODO: in v7, this should assign the value or become
  10072. // a live object itself, otherwise mutation is inconsistent
  10073. return [];
  10074. }
  10075. return null;
  10076. }
  10077. return value;
  10078. }
  10079. set accessList(value) {
  10080. this.#accessList = (value == null) ? null : accessListify(value);
  10081. }
  10082. /**
  10083. * The max fee per blob gas for Cancun transactions.
  10084. */
  10085. get maxFeePerBlobGas() {
  10086. const value = this.#maxFeePerBlobGas;
  10087. if (value == null && this.type === 3) {
  10088. return BN_0$4;
  10089. }
  10090. return value;
  10091. }
  10092. set maxFeePerBlobGas(value) {
  10093. this.#maxFeePerBlobGas = (value == null) ? null : getBigInt(value, "maxFeePerBlobGas");
  10094. }
  10095. /**
  10096. * The BLOb versioned hashes for Cancun transactions.
  10097. */
  10098. get blobVersionedHashes() {
  10099. // @TODO: Mutation is inconsistent; if unset, the returned value
  10100. // cannot mutate the object, if set it can
  10101. let value = this.#blobVersionedHashes;
  10102. if (value == null && this.type === 3) {
  10103. return [];
  10104. }
  10105. return value;
  10106. }
  10107. set blobVersionedHashes(value) {
  10108. if (value != null) {
  10109. assertArgument(Array.isArray(value), "blobVersionedHashes must be an Array", "value", value);
  10110. value = value.slice();
  10111. for (let i = 0; i < value.length; i++) {
  10112. assertArgument(isHexString(value[i], 32), "invalid blobVersionedHash", `value[${i}]`, value[i]);
  10113. }
  10114. }
  10115. this.#blobVersionedHashes = value;
  10116. }
  10117. /**
  10118. * The BLObs for the Transaction, if any.
  10119. *
  10120. * If ``blobs`` is non-``null``, then the [[seriailized]]
  10121. * will return the network formatted sidecar, otherwise it
  10122. * will return the standard [[link-eip-2718]] payload. The
  10123. * [[unsignedSerialized]] is unaffected regardless.
  10124. *
  10125. * When setting ``blobs``, either fully valid [[Blob]] objects
  10126. * may be specified (i.e. correctly padded, with correct
  10127. * committments and proofs) or a raw [[BytesLike]] may
  10128. * be provided.
  10129. *
  10130. * If raw [[BytesLike]] are provided, the [[kzg]] property **must**
  10131. * be already set. The blob will be correctly padded and the
  10132. * [[KzgLibrary]] will be used to compute the committment and
  10133. * proof for the blob.
  10134. *
  10135. * A BLOb is a sequence of field elements, each of which must
  10136. * be within the BLS field modulo, so some additional processing
  10137. * may be required to encode arbitrary data to ensure each 32 byte
  10138. * field is within the valid range.
  10139. *
  10140. * Setting this automatically populates [[blobVersionedHashes]],
  10141. * overwriting any existing values. Setting this to ``null``
  10142. * does **not** remove the [[blobVersionedHashes]], leaving them
  10143. * present.
  10144. */
  10145. get blobs() {
  10146. if (this.#blobs == null) {
  10147. return null;
  10148. }
  10149. return this.#blobs.map((b) => Object.assign({}, b));
  10150. }
  10151. set blobs(_blobs) {
  10152. if (_blobs == null) {
  10153. this.#blobs = null;
  10154. return;
  10155. }
  10156. const blobs = [];
  10157. const versionedHashes = [];
  10158. for (let i = 0; i < _blobs.length; i++) {
  10159. const blob = _blobs[i];
  10160. if (isBytesLike(blob)) {
  10161. assert(this.#kzg, "adding a raw blob requires a KZG library", "UNSUPPORTED_OPERATION", {
  10162. operation: "set blobs()"
  10163. });
  10164. let data = getBytes(blob);
  10165. assertArgument(data.length <= BLOB_SIZE, "blob is too large", `blobs[${i}]`, blob);
  10166. // Pad blob if necessary
  10167. if (data.length !== BLOB_SIZE) {
  10168. const padded = new Uint8Array(BLOB_SIZE);
  10169. padded.set(data);
  10170. data = padded;
  10171. }
  10172. const commit = this.#kzg.blobToKzgCommitment(data);
  10173. const proof = hexlify(this.#kzg.computeBlobKzgProof(data, commit));
  10174. blobs.push({
  10175. data: hexlify(data),
  10176. commitment: hexlify(commit),
  10177. proof
  10178. });
  10179. versionedHashes.push(getVersionedHash(1, commit));
  10180. }
  10181. else {
  10182. const commit = hexlify(blob.commitment);
  10183. blobs.push({
  10184. data: hexlify(blob.data),
  10185. commitment: commit,
  10186. proof: hexlify(blob.proof)
  10187. });
  10188. versionedHashes.push(getVersionedHash(1, commit));
  10189. }
  10190. }
  10191. this.#blobs = blobs;
  10192. this.#blobVersionedHashes = versionedHashes;
  10193. }
  10194. get kzg() { return this.#kzg; }
  10195. set kzg(kzg) {
  10196. this.#kzg = kzg;
  10197. }
  10198. /**
  10199. * Creates a new Transaction with default values.
  10200. */
  10201. constructor() {
  10202. this.#type = null;
  10203. this.#to = null;
  10204. this.#nonce = 0;
  10205. this.#gasLimit = BN_0$4;
  10206. this.#gasPrice = null;
  10207. this.#maxPriorityFeePerGas = null;
  10208. this.#maxFeePerGas = null;
  10209. this.#data = "0x";
  10210. this.#value = BN_0$4;
  10211. this.#chainId = BN_0$4;
  10212. this.#sig = null;
  10213. this.#accessList = null;
  10214. this.#maxFeePerBlobGas = null;
  10215. this.#blobVersionedHashes = null;
  10216. this.#blobs = null;
  10217. this.#kzg = null;
  10218. }
  10219. /**
  10220. * The transaction hash, if signed. Otherwise, ``null``.
  10221. */
  10222. get hash() {
  10223. if (this.signature == null) {
  10224. return null;
  10225. }
  10226. return keccak256(this.#getSerialized(true, false));
  10227. }
  10228. /**
  10229. * The pre-image hash of this transaction.
  10230. *
  10231. * This is the digest that a [[Signer]] must sign to authorize
  10232. * this transaction.
  10233. */
  10234. get unsignedHash() {
  10235. return keccak256(this.unsignedSerialized);
  10236. }
  10237. /**
  10238. * The sending address, if signed. Otherwise, ``null``.
  10239. */
  10240. get from() {
  10241. if (this.signature == null) {
  10242. return null;
  10243. }
  10244. return recoverAddress(this.unsignedHash, this.signature);
  10245. }
  10246. /**
  10247. * The public key of the sender, if signed. Otherwise, ``null``.
  10248. */
  10249. get fromPublicKey() {
  10250. if (this.signature == null) {
  10251. return null;
  10252. }
  10253. return SigningKey.recoverPublicKey(this.unsignedHash, this.signature);
  10254. }
  10255. /**
  10256. * Returns true if signed.
  10257. *
  10258. * This provides a Type Guard that properties requiring a signed
  10259. * transaction are non-null.
  10260. */
  10261. isSigned() {
  10262. return this.signature != null;
  10263. }
  10264. #getSerialized(signed, sidecar) {
  10265. assert(!signed || this.signature != null, "cannot serialize unsigned transaction; maybe you meant .unsignedSerialized", "UNSUPPORTED_OPERATION", { operation: ".serialized" });
  10266. const sig = signed ? this.signature : null;
  10267. switch (this.inferType()) {
  10268. case 0:
  10269. return _serializeLegacy(this, sig);
  10270. case 1:
  10271. return _serializeEip2930(this, sig);
  10272. case 2:
  10273. return _serializeEip1559(this, sig);
  10274. case 3:
  10275. return _serializeEip4844(this, sig, sidecar ? this.blobs : null);
  10276. }
  10277. assert(false, "unsupported transaction type", "UNSUPPORTED_OPERATION", { operation: ".serialized" });
  10278. }
  10279. /**
  10280. * The serialized transaction.
  10281. *
  10282. * This throws if the transaction is unsigned. For the pre-image,
  10283. * use [[unsignedSerialized]].
  10284. */
  10285. get serialized() {
  10286. return this.#getSerialized(true, true);
  10287. }
  10288. /**
  10289. * The transaction pre-image.
  10290. *
  10291. * The hash of this is the digest which needs to be signed to
  10292. * authorize this transaction.
  10293. */
  10294. get unsignedSerialized() {
  10295. return this.#getSerialized(false, false);
  10296. }
  10297. /**
  10298. * Return the most "likely" type; currently the highest
  10299. * supported transaction type.
  10300. */
  10301. inferType() {
  10302. const types = this.inferTypes();
  10303. // Prefer London (EIP-1559) over Cancun (BLOb)
  10304. if (types.indexOf(2) >= 0) {
  10305. return 2;
  10306. }
  10307. // Return the highest inferred type
  10308. return (types.pop());
  10309. }
  10310. /**
  10311. * Validates the explicit properties and returns a list of compatible
  10312. * transaction types.
  10313. */
  10314. inferTypes() {
  10315. // Checks that there are no conflicting properties set
  10316. const hasGasPrice = this.gasPrice != null;
  10317. const hasFee = (this.maxFeePerGas != null || this.maxPriorityFeePerGas != null);
  10318. const hasAccessList = (this.accessList != null);
  10319. const hasBlob = (this.#maxFeePerBlobGas != null || this.#blobVersionedHashes);
  10320. //if (hasGasPrice && hasFee) {
  10321. // throw new Error("transaction cannot have gasPrice and maxFeePerGas");
  10322. //}
  10323. if (this.maxFeePerGas != null && this.maxPriorityFeePerGas != null) {
  10324. assert(this.maxFeePerGas >= this.maxPriorityFeePerGas, "priorityFee cannot be more than maxFee", "BAD_DATA", { value: this });
  10325. }
  10326. //if (this.type === 2 && hasGasPrice) {
  10327. // throw new Error("eip-1559 transaction cannot have gasPrice");
  10328. //}
  10329. assert(!hasFee || (this.type !== 0 && this.type !== 1), "transaction type cannot have maxFeePerGas or maxPriorityFeePerGas", "BAD_DATA", { value: this });
  10330. assert(this.type !== 0 || !hasAccessList, "legacy transaction cannot have accessList", "BAD_DATA", { value: this });
  10331. const types = [];
  10332. // Explicit type
  10333. if (this.type != null) {
  10334. types.push(this.type);
  10335. }
  10336. else {
  10337. if (hasFee) {
  10338. types.push(2);
  10339. }
  10340. else if (hasGasPrice) {
  10341. types.push(1);
  10342. if (!hasAccessList) {
  10343. types.push(0);
  10344. }
  10345. }
  10346. else if (hasAccessList) {
  10347. types.push(1);
  10348. types.push(2);
  10349. }
  10350. else if (hasBlob && this.to) {
  10351. types.push(3);
  10352. }
  10353. else {
  10354. types.push(0);
  10355. types.push(1);
  10356. types.push(2);
  10357. types.push(3);
  10358. }
  10359. }
  10360. types.sort();
  10361. return types;
  10362. }
  10363. /**
  10364. * Returns true if this transaction is a legacy transaction (i.e.
  10365. * ``type === 0``).
  10366. *
  10367. * This provides a Type Guard that the related properties are
  10368. * non-null.
  10369. */
  10370. isLegacy() {
  10371. return (this.type === 0);
  10372. }
  10373. /**
  10374. * Returns true if this transaction is berlin hardform transaction (i.e.
  10375. * ``type === 1``).
  10376. *
  10377. * This provides a Type Guard that the related properties are
  10378. * non-null.
  10379. */
  10380. isBerlin() {
  10381. return (this.type === 1);
  10382. }
  10383. /**
  10384. * Returns true if this transaction is london hardform transaction (i.e.
  10385. * ``type === 2``).
  10386. *
  10387. * This provides a Type Guard that the related properties are
  10388. * non-null.
  10389. */
  10390. isLondon() {
  10391. return (this.type === 2);
  10392. }
  10393. /**
  10394. * Returns true if this transaction is an [[link-eip-4844]] BLOB
  10395. * transaction.
  10396. *
  10397. * This provides a Type Guard that the related properties are
  10398. * non-null.
  10399. */
  10400. isCancun() {
  10401. return (this.type === 3);
  10402. }
  10403. /**
  10404. * Create a copy of this transaciton.
  10405. */
  10406. clone() {
  10407. return Transaction.from(this);
  10408. }
  10409. /**
  10410. * Return a JSON-friendly object.
  10411. */
  10412. toJSON() {
  10413. const s = (v) => {
  10414. if (v == null) {
  10415. return null;
  10416. }
  10417. return v.toString();
  10418. };
  10419. return {
  10420. type: this.type,
  10421. to: this.to,
  10422. // from: this.from,
  10423. data: this.data,
  10424. nonce: this.nonce,
  10425. gasLimit: s(this.gasLimit),
  10426. gasPrice: s(this.gasPrice),
  10427. maxPriorityFeePerGas: s(this.maxPriorityFeePerGas),
  10428. maxFeePerGas: s(this.maxFeePerGas),
  10429. value: s(this.value),
  10430. chainId: s(this.chainId),
  10431. sig: this.signature ? this.signature.toJSON() : null,
  10432. accessList: this.accessList
  10433. };
  10434. }
  10435. /**
  10436. * Create a **Transaction** from a serialized transaction or a
  10437. * Transaction-like object.
  10438. */
  10439. static from(tx) {
  10440. if (tx == null) {
  10441. return new Transaction();
  10442. }
  10443. if (typeof (tx) === "string") {
  10444. const payload = getBytes(tx);
  10445. if (payload[0] >= 0x7f) { // @TODO: > vs >= ??
  10446. return Transaction.from(_parseLegacy(payload));
  10447. }
  10448. switch (payload[0]) {
  10449. case 1: return Transaction.from(_parseEip2930(payload));
  10450. case 2: return Transaction.from(_parseEip1559(payload));
  10451. case 3: return Transaction.from(_parseEip4844(payload));
  10452. }
  10453. assert(false, "unsupported transaction type", "UNSUPPORTED_OPERATION", { operation: "from" });
  10454. }
  10455. const result = new Transaction();
  10456. if (tx.type != null) {
  10457. result.type = tx.type;
  10458. }
  10459. if (tx.to != null) {
  10460. result.to = tx.to;
  10461. }
  10462. if (tx.nonce != null) {
  10463. result.nonce = tx.nonce;
  10464. }
  10465. if (tx.gasLimit != null) {
  10466. result.gasLimit = tx.gasLimit;
  10467. }
  10468. if (tx.gasPrice != null) {
  10469. result.gasPrice = tx.gasPrice;
  10470. }
  10471. if (tx.maxPriorityFeePerGas != null) {
  10472. result.maxPriorityFeePerGas = tx.maxPriorityFeePerGas;
  10473. }
  10474. if (tx.maxFeePerGas != null) {
  10475. result.maxFeePerGas = tx.maxFeePerGas;
  10476. }
  10477. if (tx.maxFeePerBlobGas != null) {
  10478. result.maxFeePerBlobGas = tx.maxFeePerBlobGas;
  10479. }
  10480. if (tx.data != null) {
  10481. result.data = tx.data;
  10482. }
  10483. if (tx.value != null) {
  10484. result.value = tx.value;
  10485. }
  10486. if (tx.chainId != null) {
  10487. result.chainId = tx.chainId;
  10488. }
  10489. if (tx.signature != null) {
  10490. result.signature = Signature.from(tx.signature);
  10491. }
  10492. if (tx.accessList != null) {
  10493. result.accessList = tx.accessList;
  10494. }
  10495. // This will get overwritten by blobs, if present
  10496. if (tx.blobVersionedHashes != null) {
  10497. result.blobVersionedHashes = tx.blobVersionedHashes;
  10498. }
  10499. // Make sure we assign the kzg before assigning blobs, which
  10500. // require the library in the event raw blob data is provided.
  10501. if (tx.kzg != null) {
  10502. result.kzg = tx.kzg;
  10503. }
  10504. if (tx.blobs != null) {
  10505. result.blobs = tx.blobs;
  10506. }
  10507. if (tx.hash != null) {
  10508. assertArgument(result.isSigned(), "unsigned transaction cannot define '.hash'", "tx", tx);
  10509. assertArgument(result.hash === tx.hash, "hash mismatch", "tx", tx);
  10510. }
  10511. if (tx.from != null) {
  10512. assertArgument(result.isSigned(), "unsigned transaction cannot define '.from'", "tx", tx);
  10513. assertArgument(result.from.toLowerCase() === (tx.from || "").toLowerCase(), "from mismatch", "tx", tx);
  10514. }
  10515. return result;
  10516. }
  10517. }
  10518. /**
  10519. * Computes the [[link-eip-191]] personal-sign message digest to sign.
  10520. *
  10521. * This prefixes the message with [[MessagePrefix]] and the decimal length
  10522. * of %%message%% and computes the [[keccak256]] digest.
  10523. *
  10524. * If %%message%% is a string, it is converted to its UTF-8 bytes
  10525. * first. To compute the digest of a [[DataHexString]], it must be converted
  10526. * to [bytes](getBytes).
  10527. *
  10528. * @example:
  10529. * hashMessage("Hello World")
  10530. * //_result:
  10531. *
  10532. * // Hashes the SIX (6) string characters, i.e.
  10533. * // [ "0", "x", "4", "2", "4", "3" ]
  10534. * hashMessage("0x4243")
  10535. * //_result:
  10536. *
  10537. * // Hashes the TWO (2) bytes [ 0x42, 0x43 ]...
  10538. * hashMessage(getBytes("0x4243"))
  10539. * //_result:
  10540. *
  10541. * // ...which is equal to using data
  10542. * hashMessage(new Uint8Array([ 0x42, 0x43 ]))
  10543. * //_result:
  10544. *
  10545. */
  10546. function hashMessage(message) {
  10547. if (typeof (message) === "string") {
  10548. message = toUtf8Bytes(message);
  10549. }
  10550. return keccak256(concat([
  10551. toUtf8Bytes(MessagePrefix),
  10552. toUtf8Bytes(String(message.length)),
  10553. message
  10554. ]));
  10555. }
  10556. /**
  10557. * Return the address of the private key that produced
  10558. * the signature %%sig%% during signing for %%message%%.
  10559. */
  10560. function verifyMessage(message, sig) {
  10561. const digest = hashMessage(message);
  10562. return recoverAddress(digest, sig);
  10563. }
  10564. const regexBytes = new RegExp("^bytes([0-9]+)$");
  10565. const regexNumber = new RegExp("^(u?int)([0-9]*)$");
  10566. const regexArray = new RegExp("^(.*)\\[([0-9]*)\\]$");
  10567. function _pack(type, value, isArray) {
  10568. switch (type) {
  10569. case "address":
  10570. if (isArray) {
  10571. return getBytes(zeroPadValue(value, 32));
  10572. }
  10573. return getBytes(getAddress(value));
  10574. case "string":
  10575. return toUtf8Bytes(value);
  10576. case "bytes":
  10577. return getBytes(value);
  10578. case "bool":
  10579. value = (!!value ? "0x01" : "0x00");
  10580. if (isArray) {
  10581. return getBytes(zeroPadValue(value, 32));
  10582. }
  10583. return getBytes(value);
  10584. }
  10585. let match = type.match(regexNumber);
  10586. if (match) {
  10587. let signed = (match[1] === "int");
  10588. let size = parseInt(match[2] || "256");
  10589. assertArgument((!match[2] || match[2] === String(size)) && (size % 8 === 0) && size !== 0 && size <= 256, "invalid number type", "type", type);
  10590. if (isArray) {
  10591. size = 256;
  10592. }
  10593. if (signed) {
  10594. value = toTwos(value, size);
  10595. }
  10596. return getBytes(zeroPadValue(toBeArray(value), size / 8));
  10597. }
  10598. match = type.match(regexBytes);
  10599. if (match) {
  10600. const size = parseInt(match[1]);
  10601. assertArgument(String(size) === match[1] && size !== 0 && size <= 32, "invalid bytes type", "type", type);
  10602. assertArgument(dataLength(value) === size, `invalid value for ${type}`, "value", value);
  10603. if (isArray) {
  10604. return getBytes(zeroPadBytes(value, 32));
  10605. }
  10606. return value;
  10607. }
  10608. match = type.match(regexArray);
  10609. if (match && Array.isArray(value)) {
  10610. const baseType = match[1];
  10611. const count = parseInt(match[2] || String(value.length));
  10612. assertArgument(count === value.length, `invalid array length for ${type}`, "value", value);
  10613. const result = [];
  10614. value.forEach(function (value) {
  10615. result.push(_pack(baseType, value, true));
  10616. });
  10617. return getBytes(concat(result));
  10618. }
  10619. assertArgument(false, "invalid type", "type", type);
  10620. }
  10621. // @TODO: Array Enum
  10622. /**
  10623. * Computes the [[link-solc-packed]] representation of %%values%%
  10624. * respectively to their %%types%%.
  10625. *
  10626. * @example:
  10627. * addr = "0x8ba1f109551bd432803012645ac136ddd64dba72"
  10628. * solidityPacked([ "address", "uint" ], [ addr, 45 ]);
  10629. * //_result:
  10630. */
  10631. function solidityPacked(types, values) {
  10632. assertArgument(types.length === values.length, "wrong number of values; expected ${ types.length }", "values", values);
  10633. const tight = [];
  10634. types.forEach(function (type, index) {
  10635. tight.push(_pack(type, values[index]));
  10636. });
  10637. return hexlify(concat(tight));
  10638. }
  10639. /**
  10640. * Computes the [[link-solc-packed]] [[keccak256]] hash of %%values%%
  10641. * respectively to their %%types%%.
  10642. *
  10643. * @example:
  10644. * addr = "0x8ba1f109551bd432803012645ac136ddd64dba72"
  10645. * solidityPackedKeccak256([ "address", "uint" ], [ addr, 45 ]);
  10646. * //_result:
  10647. */
  10648. function solidityPackedKeccak256(types, values) {
  10649. return keccak256(solidityPacked(types, values));
  10650. }
  10651. /**
  10652. * Computes the [[link-solc-packed]] [[sha256]] hash of %%values%%
  10653. * respectively to their %%types%%.
  10654. *
  10655. * @example:
  10656. * addr = "0x8ba1f109551bd432803012645ac136ddd64dba72"
  10657. * solidityPackedSha256([ "address", "uint" ], [ addr, 45 ]);
  10658. * //_result:
  10659. */
  10660. function solidityPackedSha256(types, values) {
  10661. return sha256(solidityPacked(types, values));
  10662. }
  10663. //import { TypedDataDomain, TypedDataField } from "@ethersproject/providerabstract-signer";
  10664. const padding = new Uint8Array(32);
  10665. padding.fill(0);
  10666. const BN__1 = BigInt(-1);
  10667. const BN_0$3 = BigInt(0);
  10668. const BN_1$1 = BigInt(1);
  10669. const BN_MAX_UINT256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
  10670. function hexPadRight(value) {
  10671. const bytes = getBytes(value);
  10672. const padOffset = bytes.length % 32;
  10673. if (padOffset) {
  10674. return concat([bytes, padding.slice(padOffset)]);
  10675. }
  10676. return hexlify(bytes);
  10677. }
  10678. const hexTrue = toBeHex(BN_1$1, 32);
  10679. const hexFalse = toBeHex(BN_0$3, 32);
  10680. const domainFieldTypes = {
  10681. name: "string",
  10682. version: "string",
  10683. chainId: "uint256",
  10684. verifyingContract: "address",
  10685. salt: "bytes32"
  10686. };
  10687. const domainFieldNames = [
  10688. "name", "version", "chainId", "verifyingContract", "salt"
  10689. ];
  10690. function checkString(key) {
  10691. return function (value) {
  10692. assertArgument(typeof (value) === "string", `invalid domain value for ${JSON.stringify(key)}`, `domain.${key}`, value);
  10693. return value;
  10694. };
  10695. }
  10696. const domainChecks = {
  10697. name: checkString("name"),
  10698. version: checkString("version"),
  10699. chainId: function (_value) {
  10700. const value = getBigInt(_value, "domain.chainId");
  10701. assertArgument(value >= 0, "invalid chain ID", "domain.chainId", _value);
  10702. if (Number.isSafeInteger(value)) {
  10703. return Number(value);
  10704. }
  10705. return toQuantity(value);
  10706. },
  10707. verifyingContract: function (value) {
  10708. try {
  10709. return getAddress(value).toLowerCase();
  10710. }
  10711. catch (error) { }
  10712. assertArgument(false, `invalid domain value "verifyingContract"`, "domain.verifyingContract", value);
  10713. },
  10714. salt: function (value) {
  10715. const bytes = getBytes(value, "domain.salt");
  10716. assertArgument(bytes.length === 32, `invalid domain value "salt"`, "domain.salt", value);
  10717. return hexlify(bytes);
  10718. }
  10719. };
  10720. function getBaseEncoder(type) {
  10721. // intXX and uintXX
  10722. {
  10723. const match = type.match(/^(u?)int(\d+)$/);
  10724. if (match) {
  10725. const signed = (match[1] === "");
  10726. const width = parseInt(match[2]);
  10727. assertArgument(width % 8 === 0 && width !== 0 && width <= 256 && match[2] === String(width), "invalid numeric width", "type", type);
  10728. const boundsUpper = mask(BN_MAX_UINT256, signed ? (width - 1) : width);
  10729. const boundsLower = signed ? ((boundsUpper + BN_1$1) * BN__1) : BN_0$3;
  10730. return function (_value) {
  10731. const value = getBigInt(_value, "value");
  10732. assertArgument(value >= boundsLower && value <= boundsUpper, `value out-of-bounds for ${type}`, "value", value);
  10733. return toBeHex(signed ? toTwos(value, 256) : value, 32);
  10734. };
  10735. }
  10736. }
  10737. // bytesXX
  10738. {
  10739. const match = type.match(/^bytes(\d+)$/);
  10740. if (match) {
  10741. const width = parseInt(match[1]);
  10742. assertArgument(width !== 0 && width <= 32 && match[1] === String(width), "invalid bytes width", "type", type);
  10743. return function (value) {
  10744. const bytes = getBytes(value);
  10745. assertArgument(bytes.length === width, `invalid length for ${type}`, "value", value);
  10746. return hexPadRight(value);
  10747. };
  10748. }
  10749. }
  10750. switch (type) {
  10751. case "address": return function (value) {
  10752. return zeroPadValue(getAddress(value), 32);
  10753. };
  10754. case "bool": return function (value) {
  10755. return ((!value) ? hexFalse : hexTrue);
  10756. };
  10757. case "bytes": return function (value) {
  10758. return keccak256(value);
  10759. };
  10760. case "string": return function (value) {
  10761. return id(value);
  10762. };
  10763. }
  10764. return null;
  10765. }
  10766. function encodeType(name, fields) {
  10767. return `${name}(${fields.map(({ name, type }) => (type + " " + name)).join(",")})`;
  10768. }
  10769. // foo[][3] => { base: "foo", index: "[][3]", array: {
  10770. // base: "foo", prefix: "foo[]", count: 3 } }
  10771. function splitArray(type) {
  10772. const match = type.match(/^([^\x5b]*)((\x5b\d*\x5d)*)(\x5b(\d*)\x5d)$/);
  10773. if (match) {
  10774. return {
  10775. base: match[1],
  10776. index: (match[2] + match[4]),
  10777. array: {
  10778. base: match[1],
  10779. prefix: (match[1] + match[2]),
  10780. count: (match[5] ? parseInt(match[5]) : -1),
  10781. }
  10782. };
  10783. }
  10784. return { base: type };
  10785. }
  10786. /**
  10787. * A **TypedDataEncode** prepares and encodes [[link-eip-712]] payloads
  10788. * for signed typed data.
  10789. *
  10790. * This is useful for those that wish to compute various components of a
  10791. * typed data hash, primary types, or sub-components, but generally the
  10792. * higher level [[Signer-signTypedData]] is more useful.
  10793. */
  10794. class TypedDataEncoder {
  10795. /**
  10796. * The primary type for the structured [[types]].
  10797. *
  10798. * This is derived automatically from the [[types]], since no
  10799. * recursion is possible, once the DAG for the types is consturcted
  10800. * internally, the primary type must be the only remaining type with
  10801. * no parent nodes.
  10802. */
  10803. primaryType;
  10804. #types;
  10805. /**
  10806. * The types.
  10807. */
  10808. get types() {
  10809. return JSON.parse(this.#types);
  10810. }
  10811. #fullTypes;
  10812. #encoderCache;
  10813. /**
  10814. * Create a new **TypedDataEncoder** for %%types%%.
  10815. *
  10816. * This performs all necessary checking that types are valid and
  10817. * do not violate the [[link-eip-712]] structural constraints as
  10818. * well as computes the [[primaryType]].
  10819. */
  10820. constructor(_types) {
  10821. this.#fullTypes = new Map();
  10822. this.#encoderCache = new Map();
  10823. // Link struct types to their direct child structs
  10824. const links = new Map();
  10825. // Link structs to structs which contain them as a child
  10826. const parents = new Map();
  10827. // Link all subtypes within a given struct
  10828. const subtypes = new Map();
  10829. const types = {};
  10830. Object.keys(_types).forEach((type) => {
  10831. types[type] = _types[type].map(({ name, type }) => {
  10832. // Normalize the base type (unless name conflict)
  10833. let { base, index } = splitArray(type);
  10834. if (base === "int" && !_types["int"]) {
  10835. base = "int256";
  10836. }
  10837. if (base === "uint" && !_types["uint"]) {
  10838. base = "uint256";
  10839. }
  10840. return { name, type: (base + (index || "")) };
  10841. });
  10842. links.set(type, new Set());
  10843. parents.set(type, []);
  10844. subtypes.set(type, new Set());
  10845. });
  10846. this.#types = JSON.stringify(types);
  10847. for (const name in types) {
  10848. const uniqueNames = new Set();
  10849. for (const field of types[name]) {
  10850. // Check each field has a unique name
  10851. assertArgument(!uniqueNames.has(field.name), `duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name)}`, "types", _types);
  10852. uniqueNames.add(field.name);
  10853. // Get the base type (drop any array specifiers)
  10854. const baseType = splitArray(field.type).base;
  10855. assertArgument(baseType !== name, `circular type reference to ${JSON.stringify(baseType)}`, "types", _types);
  10856. // Is this a base encoding type?
  10857. const encoder = getBaseEncoder(baseType);
  10858. if (encoder) {
  10859. continue;
  10860. }
  10861. assertArgument(parents.has(baseType), `unknown type ${JSON.stringify(baseType)}`, "types", _types);
  10862. // Add linkage
  10863. parents.get(baseType).push(name);
  10864. links.get(name).add(baseType);
  10865. }
  10866. }
  10867. // Deduce the primary type
  10868. const primaryTypes = Array.from(parents.keys()).filter((n) => (parents.get(n).length === 0));
  10869. assertArgument(primaryTypes.length !== 0, "missing primary type", "types", _types);
  10870. assertArgument(primaryTypes.length === 1, `ambiguous primary types or unused types: ${primaryTypes.map((t) => (JSON.stringify(t))).join(", ")}`, "types", _types);
  10871. defineProperties(this, { primaryType: primaryTypes[0] });
  10872. // Check for circular type references
  10873. function checkCircular(type, found) {
  10874. assertArgument(!found.has(type), `circular type reference to ${JSON.stringify(type)}`, "types", _types);
  10875. found.add(type);
  10876. for (const child of links.get(type)) {
  10877. if (!parents.has(child)) {
  10878. continue;
  10879. }
  10880. // Recursively check children
  10881. checkCircular(child, found);
  10882. // Mark all ancestors as having this decendant
  10883. for (const subtype of found) {
  10884. subtypes.get(subtype).add(child);
  10885. }
  10886. }
  10887. found.delete(type);
  10888. }
  10889. checkCircular(this.primaryType, new Set());
  10890. // Compute each fully describe type
  10891. for (const [name, set] of subtypes) {
  10892. const st = Array.from(set);
  10893. st.sort();
  10894. this.#fullTypes.set(name, encodeType(name, types[name]) + st.map((t) => encodeType(t, types[t])).join(""));
  10895. }
  10896. }
  10897. /**
  10898. * Returnthe encoder for the specific %%type%%.
  10899. */
  10900. getEncoder(type) {
  10901. let encoder = this.#encoderCache.get(type);
  10902. if (!encoder) {
  10903. encoder = this.#getEncoder(type);
  10904. this.#encoderCache.set(type, encoder);
  10905. }
  10906. return encoder;
  10907. }
  10908. #getEncoder(type) {
  10909. // Basic encoder type (address, bool, uint256, etc)
  10910. {
  10911. const encoder = getBaseEncoder(type);
  10912. if (encoder) {
  10913. return encoder;
  10914. }
  10915. }
  10916. // Array
  10917. const array = splitArray(type).array;
  10918. if (array) {
  10919. const subtype = array.prefix;
  10920. const subEncoder = this.getEncoder(subtype);
  10921. return (value) => {
  10922. assertArgument(array.count === -1 || array.count === value.length, `array length mismatch; expected length ${array.count}`, "value", value);
  10923. let result = value.map(subEncoder);
  10924. if (this.#fullTypes.has(subtype)) {
  10925. result = result.map(keccak256);
  10926. }
  10927. return keccak256(concat(result));
  10928. };
  10929. }
  10930. // Struct
  10931. const fields = this.types[type];
  10932. if (fields) {
  10933. const encodedType = id(this.#fullTypes.get(type));
  10934. return (value) => {
  10935. const values = fields.map(({ name, type }) => {
  10936. const result = this.getEncoder(type)(value[name]);
  10937. if (this.#fullTypes.has(type)) {
  10938. return keccak256(result);
  10939. }
  10940. return result;
  10941. });
  10942. values.unshift(encodedType);
  10943. return concat(values);
  10944. };
  10945. }
  10946. assertArgument(false, `unknown type: ${type}`, "type", type);
  10947. }
  10948. /**
  10949. * Return the full type for %%name%%.
  10950. */
  10951. encodeType(name) {
  10952. const result = this.#fullTypes.get(name);
  10953. assertArgument(result, `unknown type: ${JSON.stringify(name)}`, "name", name);
  10954. return result;
  10955. }
  10956. /**
  10957. * Return the encoded %%value%% for the %%type%%.
  10958. */
  10959. encodeData(type, value) {
  10960. return this.getEncoder(type)(value);
  10961. }
  10962. /**
  10963. * Returns the hash of %%value%% for the type of %%name%%.
  10964. */
  10965. hashStruct(name, value) {
  10966. return keccak256(this.encodeData(name, value));
  10967. }
  10968. /**
  10969. * Return the fulled encoded %%value%% for the [[types]].
  10970. */
  10971. encode(value) {
  10972. return this.encodeData(this.primaryType, value);
  10973. }
  10974. /**
  10975. * Return the hash of the fully encoded %%value%% for the [[types]].
  10976. */
  10977. hash(value) {
  10978. return this.hashStruct(this.primaryType, value);
  10979. }
  10980. /**
  10981. * @_ignore:
  10982. */
  10983. _visit(type, value, callback) {
  10984. // Basic encoder type (address, bool, uint256, etc)
  10985. {
  10986. const encoder = getBaseEncoder(type);
  10987. if (encoder) {
  10988. return callback(type, value);
  10989. }
  10990. }
  10991. // Array
  10992. const array = splitArray(type).array;
  10993. if (array) {
  10994. assertArgument(array.count === -1 || array.count === value.length, `array length mismatch; expected length ${array.count}`, "value", value);
  10995. return value.map((v) => this._visit(array.prefix, v, callback));
  10996. }
  10997. // Struct
  10998. const fields = this.types[type];
  10999. if (fields) {
  11000. return fields.reduce((accum, { name, type }) => {
  11001. accum[name] = this._visit(type, value[name], callback);
  11002. return accum;
  11003. }, {});
  11004. }
  11005. assertArgument(false, `unknown type: ${type}`, "type", type);
  11006. }
  11007. /**
  11008. * Call %%calback%% for each value in %%value%%, passing the type and
  11009. * component within %%value%%.
  11010. *
  11011. * This is useful for replacing addresses or other transformation that
  11012. * may be desired on each component, based on its type.
  11013. */
  11014. visit(value, callback) {
  11015. return this._visit(this.primaryType, value, callback);
  11016. }
  11017. /**
  11018. * Create a new **TypedDataEncoder** for %%types%%.
  11019. */
  11020. static from(types) {
  11021. return new TypedDataEncoder(types);
  11022. }
  11023. /**
  11024. * Return the primary type for %%types%%.
  11025. */
  11026. static getPrimaryType(types) {
  11027. return TypedDataEncoder.from(types).primaryType;
  11028. }
  11029. /**
  11030. * Return the hashed struct for %%value%% using %%types%% and %%name%%.
  11031. */
  11032. static hashStruct(name, types, value) {
  11033. return TypedDataEncoder.from(types).hashStruct(name, value);
  11034. }
  11035. /**
  11036. * Return the domain hash for %%domain%%.
  11037. */
  11038. static hashDomain(domain) {
  11039. const domainFields = [];
  11040. for (const name in domain) {
  11041. if (domain[name] == null) {
  11042. continue;
  11043. }
  11044. const type = domainFieldTypes[name];
  11045. assertArgument(type, `invalid typed-data domain key: ${JSON.stringify(name)}`, "domain", domain);
  11046. domainFields.push({ name, type });
  11047. }
  11048. domainFields.sort((a, b) => {
  11049. return domainFieldNames.indexOf(a.name) - domainFieldNames.indexOf(b.name);
  11050. });
  11051. return TypedDataEncoder.hashStruct("EIP712Domain", { EIP712Domain: domainFields }, domain);
  11052. }
  11053. /**
  11054. * Return the fully encoded [[link-eip-712]] %%value%% for %%types%% with %%domain%%.
  11055. */
  11056. static encode(domain, types, value) {
  11057. return concat([
  11058. "0x1901",
  11059. TypedDataEncoder.hashDomain(domain),
  11060. TypedDataEncoder.from(types).hash(value)
  11061. ]);
  11062. }
  11063. /**
  11064. * Return the hash of the fully encoded [[link-eip-712]] %%value%% for %%types%% with %%domain%%.
  11065. */
  11066. static hash(domain, types, value) {
  11067. return keccak256(TypedDataEncoder.encode(domain, types, value));
  11068. }
  11069. // Replaces all address types with ENS names with their looked up address
  11070. /**
  11071. * Resolves to the value from resolving all addresses in %%value%% for
  11072. * %%types%% and the %%domain%%.
  11073. */
  11074. static async resolveNames(domain, types, value, resolveName) {
  11075. // Make a copy to isolate it from the object passed in
  11076. domain = Object.assign({}, domain);
  11077. // Allow passing null to ignore value
  11078. for (const key in domain) {
  11079. if (domain[key] == null) {
  11080. delete domain[key];
  11081. }
  11082. }
  11083. // Look up all ENS names
  11084. const ensCache = {};
  11085. // Do we need to look up the domain's verifyingContract?
  11086. if (domain.verifyingContract && !isHexString(domain.verifyingContract, 20)) {
  11087. ensCache[domain.verifyingContract] = "0x";
  11088. }
  11089. // We are going to use the encoder to visit all the base values
  11090. const encoder = TypedDataEncoder.from(types);
  11091. // Get a list of all the addresses
  11092. encoder.visit(value, (type, value) => {
  11093. if (type === "address" && !isHexString(value, 20)) {
  11094. ensCache[value] = "0x";
  11095. }
  11096. return value;
  11097. });
  11098. // Lookup each name
  11099. for (const name in ensCache) {
  11100. ensCache[name] = await resolveName(name);
  11101. }
  11102. // Replace the domain verifyingContract if needed
  11103. if (domain.verifyingContract && ensCache[domain.verifyingContract]) {
  11104. domain.verifyingContract = ensCache[domain.verifyingContract];
  11105. }
  11106. // Replace all ENS names with their address
  11107. value = encoder.visit(value, (type, value) => {
  11108. if (type === "address" && ensCache[value]) {
  11109. return ensCache[value];
  11110. }
  11111. return value;
  11112. });
  11113. return { domain, value };
  11114. }
  11115. /**
  11116. * Returns the JSON-encoded payload expected by nodes which implement
  11117. * the JSON-RPC [[link-eip-712]] method.
  11118. */
  11119. static getPayload(domain, types, value) {
  11120. // Validate the domain fields
  11121. TypedDataEncoder.hashDomain(domain);
  11122. // Derive the EIP712Domain Struct reference type
  11123. const domainValues = {};
  11124. const domainTypes = [];
  11125. domainFieldNames.forEach((name) => {
  11126. const value = domain[name];
  11127. if (value == null) {
  11128. return;
  11129. }
  11130. domainValues[name] = domainChecks[name](value);
  11131. domainTypes.push({ name, type: domainFieldTypes[name] });
  11132. });
  11133. const encoder = TypedDataEncoder.from(types);
  11134. // Get the normalized types
  11135. types = encoder.types;
  11136. const typesWithDomain = Object.assign({}, types);
  11137. assertArgument(typesWithDomain.EIP712Domain == null, "types must not contain EIP712Domain type", "types.EIP712Domain", types);
  11138. typesWithDomain.EIP712Domain = domainTypes;
  11139. // Validate the data structures and types
  11140. encoder.encode(value);
  11141. return {
  11142. types: typesWithDomain,
  11143. domain: domainValues,
  11144. primaryType: encoder.primaryType,
  11145. message: encoder.visit(value, (type, value) => {
  11146. // bytes
  11147. if (type.match(/^bytes(\d*)/)) {
  11148. return hexlify(getBytes(value));
  11149. }
  11150. // uint or int
  11151. if (type.match(/^u?int/)) {
  11152. return getBigInt(value).toString();
  11153. }
  11154. switch (type) {
  11155. case "address":
  11156. return value.toLowerCase();
  11157. case "bool":
  11158. return !!value;
  11159. case "string":
  11160. assertArgument(typeof (value) === "string", "invalid string", "value", value);
  11161. return value;
  11162. }
  11163. assertArgument(false, "unsupported type", "type", type);
  11164. })
  11165. };
  11166. }
  11167. }
  11168. /**
  11169. * Compute the address used to sign the typed data for the %%signature%%.
  11170. */
  11171. function verifyTypedData(domain, types, value, signature) {
  11172. return recoverAddress(TypedDataEncoder.hash(domain, types, value), signature);
  11173. }
  11174. /**
  11175. * A fragment is a single item from an ABI, which may represent any of:
  11176. *
  11177. * - [Functions](FunctionFragment)
  11178. * - [Events](EventFragment)
  11179. * - [Constructors](ConstructorFragment)
  11180. * - Custom [Errors](ErrorFragment)
  11181. * - [Fallback or Receive](FallbackFragment) functions
  11182. *
  11183. * @_subsection api/abi/abi-coder:Fragments [about-fragments]
  11184. */
  11185. // [ "a", "b" ] => { "a": 1, "b": 1 }
  11186. function setify(items) {
  11187. const result = new Set();
  11188. items.forEach((k) => result.add(k));
  11189. return Object.freeze(result);
  11190. }
  11191. const _kwVisibDeploy = "external public payable override";
  11192. const KwVisibDeploy = setify(_kwVisibDeploy.split(" "));
  11193. // Visibility Keywords
  11194. const _kwVisib = "constant external internal payable private public pure view override";
  11195. const KwVisib = setify(_kwVisib.split(" "));
  11196. const _kwTypes = "constructor error event fallback function receive struct";
  11197. const KwTypes = setify(_kwTypes.split(" "));
  11198. const _kwModifiers = "calldata memory storage payable indexed";
  11199. const KwModifiers = setify(_kwModifiers.split(" "));
  11200. const _kwOther = "tuple returns";
  11201. // All Keywords
  11202. const _keywords = [_kwTypes, _kwModifiers, _kwOther, _kwVisib].join(" ");
  11203. const Keywords = setify(_keywords.split(" "));
  11204. // Single character tokens
  11205. const SimpleTokens = {
  11206. "(": "OPEN_PAREN", ")": "CLOSE_PAREN",
  11207. "[": "OPEN_BRACKET", "]": "CLOSE_BRACKET",
  11208. ",": "COMMA", "@": "AT"
  11209. };
  11210. // Parser regexes to consume the next token
  11211. const regexWhitespacePrefix = new RegExp("^(\\s*)");
  11212. const regexNumberPrefix = new RegExp("^([0-9]+)");
  11213. const regexIdPrefix = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)");
  11214. // Parser regexs to check validity
  11215. const regexId = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$");
  11216. const regexType = new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$");
  11217. class TokenString {
  11218. #offset;
  11219. #tokens;
  11220. get offset() { return this.#offset; }
  11221. get length() { return this.#tokens.length - this.#offset; }
  11222. constructor(tokens) {
  11223. this.#offset = 0;
  11224. this.#tokens = tokens.slice();
  11225. }
  11226. clone() { return new TokenString(this.#tokens); }
  11227. reset() { this.#offset = 0; }
  11228. #subTokenString(from = 0, to = 0) {
  11229. return new TokenString(this.#tokens.slice(from, to).map((t) => {
  11230. return Object.freeze(Object.assign({}, t, {
  11231. match: (t.match - from),
  11232. linkBack: (t.linkBack - from),
  11233. linkNext: (t.linkNext - from),
  11234. }));
  11235. }));
  11236. }
  11237. // Pops and returns the value of the next token, if it is a keyword in allowed; throws if out of tokens
  11238. popKeyword(allowed) {
  11239. const top = this.peek();
  11240. if (top.type !== "KEYWORD" || !allowed.has(top.text)) {
  11241. throw new Error(`expected keyword ${top.text}`);
  11242. }
  11243. return this.pop().text;
  11244. }
  11245. // Pops and returns the value of the next token if it is `type`; throws if out of tokens
  11246. popType(type) {
  11247. if (this.peek().type !== type) {
  11248. const top = this.peek();
  11249. throw new Error(`expected ${type}; got ${top.type} ${JSON.stringify(top.text)}`);
  11250. }
  11251. return this.pop().text;
  11252. }
  11253. // Pops and returns a "(" TOKENS ")"
  11254. popParen() {
  11255. const top = this.peek();
  11256. if (top.type !== "OPEN_PAREN") {
  11257. throw new Error("bad start");
  11258. }
  11259. const result = this.#subTokenString(this.#offset + 1, top.match + 1);
  11260. this.#offset = top.match + 1;
  11261. return result;
  11262. }
  11263. // Pops and returns the items within "(" ITEM1 "," ITEM2 "," ... ")"
  11264. popParams() {
  11265. const top = this.peek();
  11266. if (top.type !== "OPEN_PAREN") {
  11267. throw new Error("bad start");
  11268. }
  11269. const result = [];
  11270. while (this.#offset < top.match - 1) {
  11271. const link = this.peek().linkNext;
  11272. result.push(this.#subTokenString(this.#offset + 1, link));
  11273. this.#offset = link;
  11274. }
  11275. this.#offset = top.match + 1;
  11276. return result;
  11277. }
  11278. // Returns the top Token, throwing if out of tokens
  11279. peek() {
  11280. if (this.#offset >= this.#tokens.length) {
  11281. throw new Error("out-of-bounds");
  11282. }
  11283. return this.#tokens[this.#offset];
  11284. }
  11285. // Returns the next value, if it is a keyword in `allowed`
  11286. peekKeyword(allowed) {
  11287. const top = this.peekType("KEYWORD");
  11288. return (top != null && allowed.has(top)) ? top : null;
  11289. }
  11290. // Returns the value of the next token if it is `type`
  11291. peekType(type) {
  11292. if (this.length === 0) {
  11293. return null;
  11294. }
  11295. const top = this.peek();
  11296. return (top.type === type) ? top.text : null;
  11297. }
  11298. // Returns the next token; throws if out of tokens
  11299. pop() {
  11300. const result = this.peek();
  11301. this.#offset++;
  11302. return result;
  11303. }
  11304. toString() {
  11305. const tokens = [];
  11306. for (let i = this.#offset; i < this.#tokens.length; i++) {
  11307. const token = this.#tokens[i];
  11308. tokens.push(`${token.type}:${token.text}`);
  11309. }
  11310. return `<TokenString ${tokens.join(" ")}>`;
  11311. }
  11312. }
  11313. function lex(text) {
  11314. const tokens = [];
  11315. const throwError = (message) => {
  11316. const token = (offset < text.length) ? JSON.stringify(text[offset]) : "$EOI";
  11317. throw new Error(`invalid token ${token} at ${offset}: ${message}`);
  11318. };
  11319. let brackets = [];
  11320. let commas = [];
  11321. let offset = 0;
  11322. while (offset < text.length) {
  11323. // Strip off any leading whitespace
  11324. let cur = text.substring(offset);
  11325. let match = cur.match(regexWhitespacePrefix);
  11326. if (match) {
  11327. offset += match[1].length;
  11328. cur = text.substring(offset);
  11329. }
  11330. const token = { depth: brackets.length, linkBack: -1, linkNext: -1, match: -1, type: "", text: "", offset, value: -1 };
  11331. tokens.push(token);
  11332. let type = (SimpleTokens[cur[0]] || "");
  11333. if (type) {
  11334. token.type = type;
  11335. token.text = cur[0];
  11336. offset++;
  11337. if (type === "OPEN_PAREN") {
  11338. brackets.push(tokens.length - 1);
  11339. commas.push(tokens.length - 1);
  11340. }
  11341. else if (type == "CLOSE_PAREN") {
  11342. if (brackets.length === 0) {
  11343. throwError("no matching open bracket");
  11344. }
  11345. token.match = brackets.pop();
  11346. (tokens[token.match]).match = tokens.length - 1;
  11347. token.depth--;
  11348. token.linkBack = commas.pop();
  11349. (tokens[token.linkBack]).linkNext = tokens.length - 1;
  11350. }
  11351. else if (type === "COMMA") {
  11352. token.linkBack = commas.pop();
  11353. (tokens[token.linkBack]).linkNext = tokens.length - 1;
  11354. commas.push(tokens.length - 1);
  11355. }
  11356. else if (type === "OPEN_BRACKET") {
  11357. token.type = "BRACKET";
  11358. }
  11359. else if (type === "CLOSE_BRACKET") {
  11360. // Remove the CLOSE_BRACKET
  11361. let suffix = tokens.pop().text;
  11362. if (tokens.length > 0 && tokens[tokens.length - 1].type === "NUMBER") {
  11363. const value = tokens.pop().text;
  11364. suffix = value + suffix;
  11365. (tokens[tokens.length - 1]).value = getNumber(value);
  11366. }
  11367. if (tokens.length === 0 || tokens[tokens.length - 1].type !== "BRACKET") {
  11368. throw new Error("missing opening bracket");
  11369. }
  11370. (tokens[tokens.length - 1]).text += suffix;
  11371. }
  11372. continue;
  11373. }
  11374. match = cur.match(regexIdPrefix);
  11375. if (match) {
  11376. token.text = match[1];
  11377. offset += token.text.length;
  11378. if (Keywords.has(token.text)) {
  11379. token.type = "KEYWORD";
  11380. continue;
  11381. }
  11382. if (token.text.match(regexType)) {
  11383. token.type = "TYPE";
  11384. continue;
  11385. }
  11386. token.type = "ID";
  11387. continue;
  11388. }
  11389. match = cur.match(regexNumberPrefix);
  11390. if (match) {
  11391. token.text = match[1];
  11392. token.type = "NUMBER";
  11393. offset += token.text.length;
  11394. continue;
  11395. }
  11396. throw new Error(`unexpected token ${JSON.stringify(cur[0])} at position ${offset}`);
  11397. }
  11398. return new TokenString(tokens.map((t) => Object.freeze(t)));
  11399. }
  11400. // Check only one of `allowed` is in `set`
  11401. function allowSingle(set, allowed) {
  11402. let included = [];
  11403. for (const key in allowed.keys()) {
  11404. if (set.has(key)) {
  11405. included.push(key);
  11406. }
  11407. }
  11408. if (included.length > 1) {
  11409. throw new Error(`conflicting types: ${included.join(", ")}`);
  11410. }
  11411. }
  11412. // Functions to process a Solidity Signature TokenString from left-to-right for...
  11413. // ...the name with an optional type, returning the name
  11414. function consumeName(type, tokens) {
  11415. if (tokens.peekKeyword(KwTypes)) {
  11416. const keyword = tokens.pop().text;
  11417. if (keyword !== type) {
  11418. throw new Error(`expected ${type}, got ${keyword}`);
  11419. }
  11420. }
  11421. return tokens.popType("ID");
  11422. }
  11423. // ...all keywords matching allowed, returning the keywords
  11424. function consumeKeywords(tokens, allowed) {
  11425. const keywords = new Set();
  11426. while (true) {
  11427. const keyword = tokens.peekType("KEYWORD");
  11428. if (keyword == null || (allowed && !allowed.has(keyword))) {
  11429. break;
  11430. }
  11431. tokens.pop();
  11432. if (keywords.has(keyword)) {
  11433. throw new Error(`duplicate keywords: ${JSON.stringify(keyword)}`);
  11434. }
  11435. keywords.add(keyword);
  11436. }
  11437. return Object.freeze(keywords);
  11438. }
  11439. // ...all visibility keywords, returning the coalesced mutability
  11440. function consumeMutability(tokens) {
  11441. let modifiers = consumeKeywords(tokens, KwVisib);
  11442. // Detect conflicting modifiers
  11443. allowSingle(modifiers, setify("constant payable nonpayable".split(" ")));
  11444. allowSingle(modifiers, setify("pure view payable nonpayable".split(" ")));
  11445. // Process mutability states
  11446. if (modifiers.has("view")) {
  11447. return "view";
  11448. }
  11449. if (modifiers.has("pure")) {
  11450. return "pure";
  11451. }
  11452. if (modifiers.has("payable")) {
  11453. return "payable";
  11454. }
  11455. if (modifiers.has("nonpayable")) {
  11456. return "nonpayable";
  11457. }
  11458. // Process legacy `constant` last
  11459. if (modifiers.has("constant")) {
  11460. return "view";
  11461. }
  11462. return "nonpayable";
  11463. }
  11464. // ...a parameter list, returning the ParamType list
  11465. function consumeParams(tokens, allowIndexed) {
  11466. return tokens.popParams().map((t) => ParamType.from(t, allowIndexed));
  11467. }
  11468. // ...a gas limit, returning a BigNumber or null if none
  11469. function consumeGas(tokens) {
  11470. if (tokens.peekType("AT")) {
  11471. tokens.pop();
  11472. if (tokens.peekType("NUMBER")) {
  11473. return getBigInt(tokens.pop().text);
  11474. }
  11475. throw new Error("invalid gas");
  11476. }
  11477. return null;
  11478. }
  11479. function consumeEoi(tokens) {
  11480. if (tokens.length) {
  11481. throw new Error(`unexpected tokens at offset ${tokens.offset}: ${tokens.toString()}`);
  11482. }
  11483. }
  11484. const regexArrayType = new RegExp(/^(.*)\[([0-9]*)\]$/);
  11485. function verifyBasicType(type) {
  11486. const match = type.match(regexType);
  11487. assertArgument(match, "invalid type", "type", type);
  11488. if (type === "uint") {
  11489. return "uint256";
  11490. }
  11491. if (type === "int") {
  11492. return "int256";
  11493. }
  11494. if (match[2]) {
  11495. // bytesXX
  11496. const length = parseInt(match[2]);
  11497. assertArgument(length !== 0 && length <= 32, "invalid bytes length", "type", type);
  11498. }
  11499. else if (match[3]) {
  11500. // intXX or uintXX
  11501. const size = parseInt(match[3]);
  11502. assertArgument(size !== 0 && size <= 256 && (size % 8) === 0, "invalid numeric width", "type", type);
  11503. }
  11504. return type;
  11505. }
  11506. // Make the Fragment constructors effectively private
  11507. const _guard$2 = {};
  11508. const internal$1 = Symbol.for("_ethers_internal");
  11509. const ParamTypeInternal = "_ParamTypeInternal";
  11510. const ErrorFragmentInternal = "_ErrorInternal";
  11511. const EventFragmentInternal = "_EventInternal";
  11512. const ConstructorFragmentInternal = "_ConstructorInternal";
  11513. const FallbackFragmentInternal = "_FallbackInternal";
  11514. const FunctionFragmentInternal = "_FunctionInternal";
  11515. const StructFragmentInternal = "_StructInternal";
  11516. /**
  11517. * Each input and output of a [[Fragment]] is an Array of **ParamType**.
  11518. */
  11519. class ParamType {
  11520. /**
  11521. * The local name of the parameter (or ``""`` if unbound)
  11522. */
  11523. name;
  11524. /**
  11525. * The fully qualified type (e.g. ``"address"``, ``"tuple(address)"``,
  11526. * ``"uint256[3][]"``)
  11527. */
  11528. type;
  11529. /**
  11530. * The base type (e.g. ``"address"``, ``"tuple"``, ``"array"``)
  11531. */
  11532. baseType;
  11533. /**
  11534. * True if the parameters is indexed.
  11535. *
  11536. * For non-indexable types this is ``null``.
  11537. */
  11538. indexed;
  11539. /**
  11540. * The components for the tuple.
  11541. *
  11542. * For non-tuple types this is ``null``.
  11543. */
  11544. components;
  11545. /**
  11546. * The array length, or ``-1`` for dynamic-lengthed arrays.
  11547. *
  11548. * For non-array types this is ``null``.
  11549. */
  11550. arrayLength;
  11551. /**
  11552. * The type of each child in the array.
  11553. *
  11554. * For non-array types this is ``null``.
  11555. */
  11556. arrayChildren;
  11557. /**
  11558. * @private
  11559. */
  11560. constructor(guard, name, type, baseType, indexed, components, arrayLength, arrayChildren) {
  11561. assertPrivate(guard, _guard$2, "ParamType");
  11562. Object.defineProperty(this, internal$1, { value: ParamTypeInternal });
  11563. if (components) {
  11564. components = Object.freeze(components.slice());
  11565. }
  11566. if (baseType === "array") {
  11567. if (arrayLength == null || arrayChildren == null) {
  11568. throw new Error("");
  11569. }
  11570. }
  11571. else if (arrayLength != null || arrayChildren != null) {
  11572. throw new Error("");
  11573. }
  11574. if (baseType === "tuple") {
  11575. if (components == null) {
  11576. throw new Error("");
  11577. }
  11578. }
  11579. else if (components != null) {
  11580. throw new Error("");
  11581. }
  11582. defineProperties(this, {
  11583. name, type, baseType, indexed, components, arrayLength, arrayChildren
  11584. });
  11585. }
  11586. /**
  11587. * Return a string representation of this type.
  11588. *
  11589. * For example,
  11590. *
  11591. * ``sighash" => "(uint256,address)"``
  11592. *
  11593. * ``"minimal" => "tuple(uint256,address) indexed"``
  11594. *
  11595. * ``"full" => "tuple(uint256 foo, address bar) indexed baz"``
  11596. */
  11597. format(format) {
  11598. if (format == null) {
  11599. format = "sighash";
  11600. }
  11601. if (format === "json") {
  11602. const name = this.name || "";
  11603. if (this.isArray()) {
  11604. const result = JSON.parse(this.arrayChildren.format("json"));
  11605. result.name = name;
  11606. result.type += `[${(this.arrayLength < 0 ? "" : String(this.arrayLength))}]`;
  11607. return JSON.stringify(result);
  11608. }
  11609. const result = {
  11610. type: ((this.baseType === "tuple") ? "tuple" : this.type),
  11611. name
  11612. };
  11613. if (typeof (this.indexed) === "boolean") {
  11614. result.indexed = this.indexed;
  11615. }
  11616. if (this.isTuple()) {
  11617. result.components = this.components.map((c) => JSON.parse(c.format(format)));
  11618. }
  11619. return JSON.stringify(result);
  11620. }
  11621. let result = "";
  11622. // Array
  11623. if (this.isArray()) {
  11624. result += this.arrayChildren.format(format);
  11625. result += `[${(this.arrayLength < 0 ? "" : String(this.arrayLength))}]`;
  11626. }
  11627. else {
  11628. if (this.isTuple()) {
  11629. result += "(" + this.components.map((comp) => comp.format(format)).join((format === "full") ? ", " : ",") + ")";
  11630. }
  11631. else {
  11632. result += this.type;
  11633. }
  11634. }
  11635. if (format !== "sighash") {
  11636. if (this.indexed === true) {
  11637. result += " indexed";
  11638. }
  11639. if (format === "full" && this.name) {
  11640. result += " " + this.name;
  11641. }
  11642. }
  11643. return result;
  11644. }
  11645. /**
  11646. * Returns true if %%this%% is an Array type.
  11647. *
  11648. * This provides a type gaurd ensuring that [[arrayChildren]]
  11649. * and [[arrayLength]] are non-null.
  11650. */
  11651. isArray() {
  11652. return (this.baseType === "array");
  11653. }
  11654. /**
  11655. * Returns true if %%this%% is a Tuple type.
  11656. *
  11657. * This provides a type gaurd ensuring that [[components]]
  11658. * is non-null.
  11659. */
  11660. isTuple() {
  11661. return (this.baseType === "tuple");
  11662. }
  11663. /**
  11664. * Returns true if %%this%% is an Indexable type.
  11665. *
  11666. * This provides a type gaurd ensuring that [[indexed]]
  11667. * is non-null.
  11668. */
  11669. isIndexable() {
  11670. return (this.indexed != null);
  11671. }
  11672. /**
  11673. * Walks the **ParamType** with %%value%%, calling %%process%%
  11674. * on each type, destructing the %%value%% recursively.
  11675. */
  11676. walk(value, process) {
  11677. if (this.isArray()) {
  11678. if (!Array.isArray(value)) {
  11679. throw new Error("invalid array value");
  11680. }
  11681. if (this.arrayLength !== -1 && value.length !== this.arrayLength) {
  11682. throw new Error("array is wrong length");
  11683. }
  11684. const _this = this;
  11685. return value.map((v) => (_this.arrayChildren.walk(v, process)));
  11686. }
  11687. if (this.isTuple()) {
  11688. if (!Array.isArray(value)) {
  11689. throw new Error("invalid tuple value");
  11690. }
  11691. if (value.length !== this.components.length) {
  11692. throw new Error("array is wrong length");
  11693. }
  11694. const _this = this;
  11695. return value.map((v, i) => (_this.components[i].walk(v, process)));
  11696. }
  11697. return process(this.type, value);
  11698. }
  11699. #walkAsync(promises, value, process, setValue) {
  11700. if (this.isArray()) {
  11701. if (!Array.isArray(value)) {
  11702. throw new Error("invalid array value");
  11703. }
  11704. if (this.arrayLength !== -1 && value.length !== this.arrayLength) {
  11705. throw new Error("array is wrong length");
  11706. }
  11707. const childType = this.arrayChildren;
  11708. const result = value.slice();
  11709. result.forEach((value, index) => {
  11710. childType.#walkAsync(promises, value, process, (value) => {
  11711. result[index] = value;
  11712. });
  11713. });
  11714. setValue(result);
  11715. return;
  11716. }
  11717. if (this.isTuple()) {
  11718. const components = this.components;
  11719. // Convert the object into an array
  11720. let result;
  11721. if (Array.isArray(value)) {
  11722. result = value.slice();
  11723. }
  11724. else {
  11725. if (value == null || typeof (value) !== "object") {
  11726. throw new Error("invalid tuple value");
  11727. }
  11728. result = components.map((param) => {
  11729. if (!param.name) {
  11730. throw new Error("cannot use object value with unnamed components");
  11731. }
  11732. if (!(param.name in value)) {
  11733. throw new Error(`missing value for component ${param.name}`);
  11734. }
  11735. return value[param.name];
  11736. });
  11737. }
  11738. if (result.length !== this.components.length) {
  11739. throw new Error("array is wrong length");
  11740. }
  11741. result.forEach((value, index) => {
  11742. components[index].#walkAsync(promises, value, process, (value) => {
  11743. result[index] = value;
  11744. });
  11745. });
  11746. setValue(result);
  11747. return;
  11748. }
  11749. const result = process(this.type, value);
  11750. if (result.then) {
  11751. promises.push((async function () { setValue(await result); })());
  11752. }
  11753. else {
  11754. setValue(result);
  11755. }
  11756. }
  11757. /**
  11758. * Walks the **ParamType** with %%value%%, asynchronously calling
  11759. * %%process%% on each type, destructing the %%value%% recursively.
  11760. *
  11761. * This can be used to resolve ENS names by walking and resolving each
  11762. * ``"address"`` type.
  11763. */
  11764. async walkAsync(value, process) {
  11765. const promises = [];
  11766. const result = [value];
  11767. this.#walkAsync(promises, value, process, (value) => {
  11768. result[0] = value;
  11769. });
  11770. if (promises.length) {
  11771. await Promise.all(promises);
  11772. }
  11773. return result[0];
  11774. }
  11775. /**
  11776. * Creates a new **ParamType** for %%obj%%.
  11777. *
  11778. * If %%allowIndexed%% then the ``indexed`` keyword is permitted,
  11779. * otherwise the ``indexed`` keyword will throw an error.
  11780. */
  11781. static from(obj, allowIndexed) {
  11782. if (ParamType.isParamType(obj)) {
  11783. return obj;
  11784. }
  11785. if (typeof (obj) === "string") {
  11786. try {
  11787. return ParamType.from(lex(obj), allowIndexed);
  11788. }
  11789. catch (error) {
  11790. assertArgument(false, "invalid param type", "obj", obj);
  11791. }
  11792. }
  11793. else if (obj instanceof TokenString) {
  11794. let type = "", baseType = "";
  11795. let comps = null;
  11796. if (consumeKeywords(obj, setify(["tuple"])).has("tuple") || obj.peekType("OPEN_PAREN")) {
  11797. // Tuple
  11798. baseType = "tuple";
  11799. comps = obj.popParams().map((t) => ParamType.from(t));
  11800. type = `tuple(${comps.map((c) => c.format()).join(",")})`;
  11801. }
  11802. else {
  11803. // Normal
  11804. type = verifyBasicType(obj.popType("TYPE"));
  11805. baseType = type;
  11806. }
  11807. // Check for Array
  11808. let arrayChildren = null;
  11809. let arrayLength = null;
  11810. while (obj.length && obj.peekType("BRACKET")) {
  11811. const bracket = obj.pop(); //arrays[i];
  11812. arrayChildren = new ParamType(_guard$2, "", type, baseType, null, comps, arrayLength, arrayChildren);
  11813. arrayLength = bracket.value;
  11814. type += bracket.text;
  11815. baseType = "array";
  11816. comps = null;
  11817. }
  11818. let indexed = null;
  11819. const keywords = consumeKeywords(obj, KwModifiers);
  11820. if (keywords.has("indexed")) {
  11821. if (!allowIndexed) {
  11822. throw new Error("");
  11823. }
  11824. indexed = true;
  11825. }
  11826. const name = (obj.peekType("ID") ? obj.pop().text : "");
  11827. if (obj.length) {
  11828. throw new Error("leftover tokens");
  11829. }
  11830. return new ParamType(_guard$2, name, type, baseType, indexed, comps, arrayLength, arrayChildren);
  11831. }
  11832. const name = obj.name;
  11833. assertArgument(!name || (typeof (name) === "string" && name.match(regexId)), "invalid name", "obj.name", name);
  11834. let indexed = obj.indexed;
  11835. if (indexed != null) {
  11836. assertArgument(allowIndexed, "parameter cannot be indexed", "obj.indexed", obj.indexed);
  11837. indexed = !!indexed;
  11838. }
  11839. let type = obj.type;
  11840. let arrayMatch = type.match(regexArrayType);
  11841. if (arrayMatch) {
  11842. const arrayLength = parseInt(arrayMatch[2] || "-1");
  11843. const arrayChildren = ParamType.from({
  11844. type: arrayMatch[1],
  11845. components: obj.components
  11846. });
  11847. return new ParamType(_guard$2, name || "", type, "array", indexed, null, arrayLength, arrayChildren);
  11848. }
  11849. if (type === "tuple" || type.startsWith("tuple(" /* fix: ) */) || type.startsWith("(" /* fix: ) */)) {
  11850. const comps = (obj.components != null) ? obj.components.map((c) => ParamType.from(c)) : null;
  11851. const tuple = new ParamType(_guard$2, name || "", type, "tuple", indexed, comps, null, null);
  11852. // @TODO: use lexer to validate and normalize type
  11853. return tuple;
  11854. }
  11855. type = verifyBasicType(obj.type);
  11856. return new ParamType(_guard$2, name || "", type, type, indexed, null, null, null);
  11857. }
  11858. /**
  11859. * Returns true if %%value%% is a **ParamType**.
  11860. */
  11861. static isParamType(value) {
  11862. return (value && value[internal$1] === ParamTypeInternal);
  11863. }
  11864. }
  11865. /**
  11866. * An abstract class to represent An individual fragment from a parse ABI.
  11867. */
  11868. class Fragment {
  11869. /**
  11870. * The type of the fragment.
  11871. */
  11872. type;
  11873. /**
  11874. * The inputs for the fragment.
  11875. */
  11876. inputs;
  11877. /**
  11878. * @private
  11879. */
  11880. constructor(guard, type, inputs) {
  11881. assertPrivate(guard, _guard$2, "Fragment");
  11882. inputs = Object.freeze(inputs.slice());
  11883. defineProperties(this, { type, inputs });
  11884. }
  11885. /**
  11886. * Creates a new **Fragment** for %%obj%%, wich can be any supported
  11887. * ABI frgament type.
  11888. */
  11889. static from(obj) {
  11890. if (typeof (obj) === "string") {
  11891. // Try parsing JSON...
  11892. try {
  11893. Fragment.from(JSON.parse(obj));
  11894. }
  11895. catch (e) { }
  11896. // ...otherwise, use the human-readable lexer
  11897. return Fragment.from(lex(obj));
  11898. }
  11899. if (obj instanceof TokenString) {
  11900. // Human-readable ABI (already lexed)
  11901. const type = obj.peekKeyword(KwTypes);
  11902. switch (type) {
  11903. case "constructor": return ConstructorFragment.from(obj);
  11904. case "error": return ErrorFragment.from(obj);
  11905. case "event": return EventFragment.from(obj);
  11906. case "fallback":
  11907. case "receive":
  11908. return FallbackFragment.from(obj);
  11909. case "function": return FunctionFragment.from(obj);
  11910. case "struct": return StructFragment.from(obj);
  11911. }
  11912. }
  11913. else if (typeof (obj) === "object") {
  11914. // JSON ABI
  11915. switch (obj.type) {
  11916. case "constructor": return ConstructorFragment.from(obj);
  11917. case "error": return ErrorFragment.from(obj);
  11918. case "event": return EventFragment.from(obj);
  11919. case "fallback":
  11920. case "receive":
  11921. return FallbackFragment.from(obj);
  11922. case "function": return FunctionFragment.from(obj);
  11923. case "struct": return StructFragment.from(obj);
  11924. }
  11925. assert(false, `unsupported type: ${obj.type}`, "UNSUPPORTED_OPERATION", {
  11926. operation: "Fragment.from"
  11927. });
  11928. }
  11929. assertArgument(false, "unsupported frgament object", "obj", obj);
  11930. }
  11931. /**
  11932. * Returns true if %%value%% is a [[ConstructorFragment]].
  11933. */
  11934. static isConstructor(value) {
  11935. return ConstructorFragment.isFragment(value);
  11936. }
  11937. /**
  11938. * Returns true if %%value%% is an [[ErrorFragment]].
  11939. */
  11940. static isError(value) {
  11941. return ErrorFragment.isFragment(value);
  11942. }
  11943. /**
  11944. * Returns true if %%value%% is an [[EventFragment]].
  11945. */
  11946. static isEvent(value) {
  11947. return EventFragment.isFragment(value);
  11948. }
  11949. /**
  11950. * Returns true if %%value%% is a [[FunctionFragment]].
  11951. */
  11952. static isFunction(value) {
  11953. return FunctionFragment.isFragment(value);
  11954. }
  11955. /**
  11956. * Returns true if %%value%% is a [[StructFragment]].
  11957. */
  11958. static isStruct(value) {
  11959. return StructFragment.isFragment(value);
  11960. }
  11961. }
  11962. /**
  11963. * An abstract class to represent An individual fragment
  11964. * which has a name from a parse ABI.
  11965. */
  11966. class NamedFragment extends Fragment {
  11967. /**
  11968. * The name of the fragment.
  11969. */
  11970. name;
  11971. /**
  11972. * @private
  11973. */
  11974. constructor(guard, type, name, inputs) {
  11975. super(guard, type, inputs);
  11976. assertArgument(typeof (name) === "string" && name.match(regexId), "invalid identifier", "name", name);
  11977. inputs = Object.freeze(inputs.slice());
  11978. defineProperties(this, { name });
  11979. }
  11980. }
  11981. function joinParams(format, params) {
  11982. return "(" + params.map((p) => p.format(format)).join((format === "full") ? ", " : ",") + ")";
  11983. }
  11984. /**
  11985. * A Fragment which represents a //Custom Error//.
  11986. */
  11987. class ErrorFragment extends NamedFragment {
  11988. /**
  11989. * @private
  11990. */
  11991. constructor(guard, name, inputs) {
  11992. super(guard, "error", name, inputs);
  11993. Object.defineProperty(this, internal$1, { value: ErrorFragmentInternal });
  11994. }
  11995. /**
  11996. * The Custom Error selector.
  11997. */
  11998. get selector() {
  11999. return id(this.format("sighash")).substring(0, 10);
  12000. }
  12001. /**
  12002. * Returns a string representation of this fragment as %%format%%.
  12003. */
  12004. format(format) {
  12005. if (format == null) {
  12006. format = "sighash";
  12007. }
  12008. if (format === "json") {
  12009. return JSON.stringify({
  12010. type: "error",
  12011. name: this.name,
  12012. inputs: this.inputs.map((input) => JSON.parse(input.format(format))),
  12013. });
  12014. }
  12015. const result = [];
  12016. if (format !== "sighash") {
  12017. result.push("error");
  12018. }
  12019. result.push(this.name + joinParams(format, this.inputs));
  12020. return result.join(" ");
  12021. }
  12022. /**
  12023. * Returns a new **ErrorFragment** for %%obj%%.
  12024. */
  12025. static from(obj) {
  12026. if (ErrorFragment.isFragment(obj)) {
  12027. return obj;
  12028. }
  12029. if (typeof (obj) === "string") {
  12030. return ErrorFragment.from(lex(obj));
  12031. }
  12032. else if (obj instanceof TokenString) {
  12033. const name = consumeName("error", obj);
  12034. const inputs = consumeParams(obj);
  12035. consumeEoi(obj);
  12036. return new ErrorFragment(_guard$2, name, inputs);
  12037. }
  12038. return new ErrorFragment(_guard$2, obj.name, obj.inputs ? obj.inputs.map(ParamType.from) : []);
  12039. }
  12040. /**
  12041. * Returns ``true`` and provides a type guard if %%value%% is an
  12042. * **ErrorFragment**.
  12043. */
  12044. static isFragment(value) {
  12045. return (value && value[internal$1] === ErrorFragmentInternal);
  12046. }
  12047. }
  12048. /**
  12049. * A Fragment which represents an Event.
  12050. */
  12051. class EventFragment extends NamedFragment {
  12052. /**
  12053. * Whether this event is anonymous.
  12054. */
  12055. anonymous;
  12056. /**
  12057. * @private
  12058. */
  12059. constructor(guard, name, inputs, anonymous) {
  12060. super(guard, "event", name, inputs);
  12061. Object.defineProperty(this, internal$1, { value: EventFragmentInternal });
  12062. defineProperties(this, { anonymous });
  12063. }
  12064. /**
  12065. * The Event topic hash.
  12066. */
  12067. get topicHash() {
  12068. return id(this.format("sighash"));
  12069. }
  12070. /**
  12071. * Returns a string representation of this event as %%format%%.
  12072. */
  12073. format(format) {
  12074. if (format == null) {
  12075. format = "sighash";
  12076. }
  12077. if (format === "json") {
  12078. return JSON.stringify({
  12079. type: "event",
  12080. anonymous: this.anonymous,
  12081. name: this.name,
  12082. inputs: this.inputs.map((i) => JSON.parse(i.format(format)))
  12083. });
  12084. }
  12085. const result = [];
  12086. if (format !== "sighash") {
  12087. result.push("event");
  12088. }
  12089. result.push(this.name + joinParams(format, this.inputs));
  12090. if (format !== "sighash" && this.anonymous) {
  12091. result.push("anonymous");
  12092. }
  12093. return result.join(" ");
  12094. }
  12095. /**
  12096. * Return the topic hash for an event with %%name%% and %%params%%.
  12097. */
  12098. static getTopicHash(name, params) {
  12099. params = (params || []).map((p) => ParamType.from(p));
  12100. const fragment = new EventFragment(_guard$2, name, params, false);
  12101. return fragment.topicHash;
  12102. }
  12103. /**
  12104. * Returns a new **EventFragment** for %%obj%%.
  12105. */
  12106. static from(obj) {
  12107. if (EventFragment.isFragment(obj)) {
  12108. return obj;
  12109. }
  12110. if (typeof (obj) === "string") {
  12111. try {
  12112. return EventFragment.from(lex(obj));
  12113. }
  12114. catch (error) {
  12115. assertArgument(false, "invalid event fragment", "obj", obj);
  12116. }
  12117. }
  12118. else if (obj instanceof TokenString) {
  12119. const name = consumeName("event", obj);
  12120. const inputs = consumeParams(obj, true);
  12121. const anonymous = !!consumeKeywords(obj, setify(["anonymous"])).has("anonymous");
  12122. consumeEoi(obj);
  12123. return new EventFragment(_guard$2, name, inputs, anonymous);
  12124. }
  12125. return new EventFragment(_guard$2, obj.name, obj.inputs ? obj.inputs.map((p) => ParamType.from(p, true)) : [], !!obj.anonymous);
  12126. }
  12127. /**
  12128. * Returns ``true`` and provides a type guard if %%value%% is an
  12129. * **EventFragment**.
  12130. */
  12131. static isFragment(value) {
  12132. return (value && value[internal$1] === EventFragmentInternal);
  12133. }
  12134. }
  12135. /**
  12136. * A Fragment which represents a constructor.
  12137. */
  12138. class ConstructorFragment extends Fragment {
  12139. /**
  12140. * Whether the constructor can receive an endowment.
  12141. */
  12142. payable;
  12143. /**
  12144. * The recommended gas limit for deployment or ``null``.
  12145. */
  12146. gas;
  12147. /**
  12148. * @private
  12149. */
  12150. constructor(guard, type, inputs, payable, gas) {
  12151. super(guard, type, inputs);
  12152. Object.defineProperty(this, internal$1, { value: ConstructorFragmentInternal });
  12153. defineProperties(this, { payable, gas });
  12154. }
  12155. /**
  12156. * Returns a string representation of this constructor as %%format%%.
  12157. */
  12158. format(format) {
  12159. assert(format != null && format !== "sighash", "cannot format a constructor for sighash", "UNSUPPORTED_OPERATION", { operation: "format(sighash)" });
  12160. if (format === "json") {
  12161. return JSON.stringify({
  12162. type: "constructor",
  12163. stateMutability: (this.payable ? "payable" : "undefined"),
  12164. payable: this.payable,
  12165. gas: ((this.gas != null) ? this.gas : undefined),
  12166. inputs: this.inputs.map((i) => JSON.parse(i.format(format)))
  12167. });
  12168. }
  12169. const result = [`constructor${joinParams(format, this.inputs)}`];
  12170. if (this.payable) {
  12171. result.push("payable");
  12172. }
  12173. if (this.gas != null) {
  12174. result.push(`@${this.gas.toString()}`);
  12175. }
  12176. return result.join(" ");
  12177. }
  12178. /**
  12179. * Returns a new **ConstructorFragment** for %%obj%%.
  12180. */
  12181. static from(obj) {
  12182. if (ConstructorFragment.isFragment(obj)) {
  12183. return obj;
  12184. }
  12185. if (typeof (obj) === "string") {
  12186. try {
  12187. return ConstructorFragment.from(lex(obj));
  12188. }
  12189. catch (error) {
  12190. assertArgument(false, "invalid constuctor fragment", "obj", obj);
  12191. }
  12192. }
  12193. else if (obj instanceof TokenString) {
  12194. consumeKeywords(obj, setify(["constructor"]));
  12195. const inputs = consumeParams(obj);
  12196. const payable = !!consumeKeywords(obj, KwVisibDeploy).has("payable");
  12197. const gas = consumeGas(obj);
  12198. consumeEoi(obj);
  12199. return new ConstructorFragment(_guard$2, "constructor", inputs, payable, gas);
  12200. }
  12201. return new ConstructorFragment(_guard$2, "constructor", obj.inputs ? obj.inputs.map(ParamType.from) : [], !!obj.payable, (obj.gas != null) ? obj.gas : null);
  12202. }
  12203. /**
  12204. * Returns ``true`` and provides a type guard if %%value%% is a
  12205. * **ConstructorFragment**.
  12206. */
  12207. static isFragment(value) {
  12208. return (value && value[internal$1] === ConstructorFragmentInternal);
  12209. }
  12210. }
  12211. /**
  12212. * A Fragment which represents a method.
  12213. */
  12214. class FallbackFragment extends Fragment {
  12215. /**
  12216. * If the function can be sent value during invocation.
  12217. */
  12218. payable;
  12219. constructor(guard, inputs, payable) {
  12220. super(guard, "fallback", inputs);
  12221. Object.defineProperty(this, internal$1, { value: FallbackFragmentInternal });
  12222. defineProperties(this, { payable });
  12223. }
  12224. /**
  12225. * Returns a string representation of this fallback as %%format%%.
  12226. */
  12227. format(format) {
  12228. const type = ((this.inputs.length === 0) ? "receive" : "fallback");
  12229. if (format === "json") {
  12230. const stateMutability = (this.payable ? "payable" : "nonpayable");
  12231. return JSON.stringify({ type, stateMutability });
  12232. }
  12233. return `${type}()${this.payable ? " payable" : ""}`;
  12234. }
  12235. /**
  12236. * Returns a new **FallbackFragment** for %%obj%%.
  12237. */
  12238. static from(obj) {
  12239. if (FallbackFragment.isFragment(obj)) {
  12240. return obj;
  12241. }
  12242. if (typeof (obj) === "string") {
  12243. try {
  12244. return FallbackFragment.from(lex(obj));
  12245. }
  12246. catch (error) {
  12247. assertArgument(false, "invalid fallback fragment", "obj", obj);
  12248. }
  12249. }
  12250. else if (obj instanceof TokenString) {
  12251. const errorObj = obj.toString();
  12252. const topIsValid = obj.peekKeyword(setify(["fallback", "receive"]));
  12253. assertArgument(topIsValid, "type must be fallback or receive", "obj", errorObj);
  12254. const type = obj.popKeyword(setify(["fallback", "receive"]));
  12255. // receive()
  12256. if (type === "receive") {
  12257. const inputs = consumeParams(obj);
  12258. assertArgument(inputs.length === 0, `receive cannot have arguments`, "obj.inputs", inputs);
  12259. consumeKeywords(obj, setify(["payable"]));
  12260. consumeEoi(obj);
  12261. return new FallbackFragment(_guard$2, [], true);
  12262. }
  12263. // fallback() [payable]
  12264. // fallback(bytes) [payable] returns (bytes)
  12265. let inputs = consumeParams(obj);
  12266. if (inputs.length) {
  12267. assertArgument(inputs.length === 1 && inputs[0].type === "bytes", "invalid fallback inputs", "obj.inputs", inputs.map((i) => i.format("minimal")).join(", "));
  12268. }
  12269. else {
  12270. inputs = [ParamType.from("bytes")];
  12271. }
  12272. const mutability = consumeMutability(obj);
  12273. assertArgument(mutability === "nonpayable" || mutability === "payable", "fallback cannot be constants", "obj.stateMutability", mutability);
  12274. if (consumeKeywords(obj, setify(["returns"])).has("returns")) {
  12275. const outputs = consumeParams(obj);
  12276. assertArgument(outputs.length === 1 && outputs[0].type === "bytes", "invalid fallback outputs", "obj.outputs", outputs.map((i) => i.format("minimal")).join(", "));
  12277. }
  12278. consumeEoi(obj);
  12279. return new FallbackFragment(_guard$2, inputs, mutability === "payable");
  12280. }
  12281. if (obj.type === "receive") {
  12282. return new FallbackFragment(_guard$2, [], true);
  12283. }
  12284. if (obj.type === "fallback") {
  12285. const inputs = [ParamType.from("bytes")];
  12286. const payable = (obj.stateMutability === "payable");
  12287. return new FallbackFragment(_guard$2, inputs, payable);
  12288. }
  12289. assertArgument(false, "invalid fallback description", "obj", obj);
  12290. }
  12291. /**
  12292. * Returns ``true`` and provides a type guard if %%value%% is a
  12293. * **FallbackFragment**.
  12294. */
  12295. static isFragment(value) {
  12296. return (value && value[internal$1] === FallbackFragmentInternal);
  12297. }
  12298. }
  12299. /**
  12300. * A Fragment which represents a method.
  12301. */
  12302. class FunctionFragment extends NamedFragment {
  12303. /**
  12304. * If the function is constant (e.g. ``pure`` or ``view`` functions).
  12305. */
  12306. constant;
  12307. /**
  12308. * The returned types for the result of calling this function.
  12309. */
  12310. outputs;
  12311. /**
  12312. * The state mutability (e.g. ``payable``, ``nonpayable``, ``view``
  12313. * or ``pure``)
  12314. */
  12315. stateMutability;
  12316. /**
  12317. * If the function can be sent value during invocation.
  12318. */
  12319. payable;
  12320. /**
  12321. * The recommended gas limit to send when calling this function.
  12322. */
  12323. gas;
  12324. /**
  12325. * @private
  12326. */
  12327. constructor(guard, name, stateMutability, inputs, outputs, gas) {
  12328. super(guard, "function", name, inputs);
  12329. Object.defineProperty(this, internal$1, { value: FunctionFragmentInternal });
  12330. outputs = Object.freeze(outputs.slice());
  12331. const constant = (stateMutability === "view" || stateMutability === "pure");
  12332. const payable = (stateMutability === "payable");
  12333. defineProperties(this, { constant, gas, outputs, payable, stateMutability });
  12334. }
  12335. /**
  12336. * The Function selector.
  12337. */
  12338. get selector() {
  12339. return id(this.format("sighash")).substring(0, 10);
  12340. }
  12341. /**
  12342. * Returns a string representation of this function as %%format%%.
  12343. */
  12344. format(format) {
  12345. if (format == null) {
  12346. format = "sighash";
  12347. }
  12348. if (format === "json") {
  12349. return JSON.stringify({
  12350. type: "function",
  12351. name: this.name,
  12352. constant: this.constant,
  12353. stateMutability: ((this.stateMutability !== "nonpayable") ? this.stateMutability : undefined),
  12354. payable: this.payable,
  12355. gas: ((this.gas != null) ? this.gas : undefined),
  12356. inputs: this.inputs.map((i) => JSON.parse(i.format(format))),
  12357. outputs: this.outputs.map((o) => JSON.parse(o.format(format))),
  12358. });
  12359. }
  12360. const result = [];
  12361. if (format !== "sighash") {
  12362. result.push("function");
  12363. }
  12364. result.push(this.name + joinParams(format, this.inputs));
  12365. if (format !== "sighash") {
  12366. if (this.stateMutability !== "nonpayable") {
  12367. result.push(this.stateMutability);
  12368. }
  12369. if (this.outputs && this.outputs.length) {
  12370. result.push("returns");
  12371. result.push(joinParams(format, this.outputs));
  12372. }
  12373. if (this.gas != null) {
  12374. result.push(`@${this.gas.toString()}`);
  12375. }
  12376. }
  12377. return result.join(" ");
  12378. }
  12379. /**
  12380. * Return the selector for a function with %%name%% and %%params%%.
  12381. */
  12382. static getSelector(name, params) {
  12383. params = (params || []).map((p) => ParamType.from(p));
  12384. const fragment = new FunctionFragment(_guard$2, name, "view", params, [], null);
  12385. return fragment.selector;
  12386. }
  12387. /**
  12388. * Returns a new **FunctionFragment** for %%obj%%.
  12389. */
  12390. static from(obj) {
  12391. if (FunctionFragment.isFragment(obj)) {
  12392. return obj;
  12393. }
  12394. if (typeof (obj) === "string") {
  12395. try {
  12396. return FunctionFragment.from(lex(obj));
  12397. }
  12398. catch (error) {
  12399. assertArgument(false, "invalid function fragment", "obj", obj);
  12400. }
  12401. }
  12402. else if (obj instanceof TokenString) {
  12403. const name = consumeName("function", obj);
  12404. const inputs = consumeParams(obj);
  12405. const mutability = consumeMutability(obj);
  12406. let outputs = [];
  12407. if (consumeKeywords(obj, setify(["returns"])).has("returns")) {
  12408. outputs = consumeParams(obj);
  12409. }
  12410. const gas = consumeGas(obj);
  12411. consumeEoi(obj);
  12412. return new FunctionFragment(_guard$2, name, mutability, inputs, outputs, gas);
  12413. }
  12414. let stateMutability = obj.stateMutability;
  12415. // Use legacy Solidity ABI logic if stateMutability is missing
  12416. if (stateMutability == null) {
  12417. stateMutability = "payable";
  12418. if (typeof (obj.constant) === "boolean") {
  12419. stateMutability = "view";
  12420. if (!obj.constant) {
  12421. stateMutability = "payable";
  12422. if (typeof (obj.payable) === "boolean" && !obj.payable) {
  12423. stateMutability = "nonpayable";
  12424. }
  12425. }
  12426. }
  12427. else if (typeof (obj.payable) === "boolean" && !obj.payable) {
  12428. stateMutability = "nonpayable";
  12429. }
  12430. }
  12431. // @TODO: verifyState for stateMutability (e.g. throw if
  12432. // payable: false but stateMutability is "nonpayable")
  12433. return new FunctionFragment(_guard$2, obj.name, stateMutability, obj.inputs ? obj.inputs.map(ParamType.from) : [], obj.outputs ? obj.outputs.map(ParamType.from) : [], (obj.gas != null) ? obj.gas : null);
  12434. }
  12435. /**
  12436. * Returns ``true`` and provides a type guard if %%value%% is a
  12437. * **FunctionFragment**.
  12438. */
  12439. static isFragment(value) {
  12440. return (value && value[internal$1] === FunctionFragmentInternal);
  12441. }
  12442. }
  12443. /**
  12444. * A Fragment which represents a structure.
  12445. */
  12446. class StructFragment extends NamedFragment {
  12447. /**
  12448. * @private
  12449. */
  12450. constructor(guard, name, inputs) {
  12451. super(guard, "struct", name, inputs);
  12452. Object.defineProperty(this, internal$1, { value: StructFragmentInternal });
  12453. }
  12454. /**
  12455. * Returns a string representation of this struct as %%format%%.
  12456. */
  12457. format() {
  12458. throw new Error("@TODO");
  12459. }
  12460. /**
  12461. * Returns a new **StructFragment** for %%obj%%.
  12462. */
  12463. static from(obj) {
  12464. if (typeof (obj) === "string") {
  12465. try {
  12466. return StructFragment.from(lex(obj));
  12467. }
  12468. catch (error) {
  12469. assertArgument(false, "invalid struct fragment", "obj", obj);
  12470. }
  12471. }
  12472. else if (obj instanceof TokenString) {
  12473. const name = consumeName("struct", obj);
  12474. const inputs = consumeParams(obj);
  12475. consumeEoi(obj);
  12476. return new StructFragment(_guard$2, name, inputs);
  12477. }
  12478. return new StructFragment(_guard$2, obj.name, obj.inputs ? obj.inputs.map(ParamType.from) : []);
  12479. }
  12480. // @TODO: fix this return type
  12481. /**
  12482. * Returns ``true`` and provides a type guard if %%value%% is a
  12483. * **StructFragment**.
  12484. */
  12485. static isFragment(value) {
  12486. return (value && value[internal$1] === StructFragmentInternal);
  12487. }
  12488. }
  12489. /**
  12490. * When sending values to or receiving values from a [[Contract]], the
  12491. * data is generally encoded using the [ABI standard](link-solc-abi).
  12492. *
  12493. * The AbiCoder provides a utility to encode values to ABI data and
  12494. * decode values from ABI data.
  12495. *
  12496. * Most of the time, developers should favour the [[Contract]] class,
  12497. * which further abstracts a lot of the finer details of ABI data.
  12498. *
  12499. * @_section api/abi/abi-coder:ABI Encoding
  12500. */
  12501. // See: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI
  12502. // https://docs.soliditylang.org/en/v0.8.17/control-structures.html
  12503. const PanicReasons$1 = new Map();
  12504. PanicReasons$1.set(0x00, "GENERIC_PANIC");
  12505. PanicReasons$1.set(0x01, "ASSERT_FALSE");
  12506. PanicReasons$1.set(0x11, "OVERFLOW");
  12507. PanicReasons$1.set(0x12, "DIVIDE_BY_ZERO");
  12508. PanicReasons$1.set(0x21, "ENUM_RANGE_ERROR");
  12509. PanicReasons$1.set(0x22, "BAD_STORAGE_DATA");
  12510. PanicReasons$1.set(0x31, "STACK_UNDERFLOW");
  12511. PanicReasons$1.set(0x32, "ARRAY_RANGE_ERROR");
  12512. PanicReasons$1.set(0x41, "OUT_OF_MEMORY");
  12513. PanicReasons$1.set(0x51, "UNINITIALIZED_FUNCTION_CALL");
  12514. const paramTypeBytes = new RegExp(/^bytes([0-9]*)$/);
  12515. const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/);
  12516. let defaultCoder = null;
  12517. let defaultMaxInflation = 1024;
  12518. function getBuiltinCallException(action, tx, data, abiCoder) {
  12519. let message = "missing revert data";
  12520. let reason = null;
  12521. const invocation = null;
  12522. let revert = null;
  12523. if (data) {
  12524. message = "execution reverted";
  12525. const bytes = getBytes(data);
  12526. data = hexlify(data);
  12527. if (bytes.length === 0) {
  12528. message += " (no data present; likely require(false) occurred";
  12529. reason = "require(false)";
  12530. }
  12531. else if (bytes.length % 32 !== 4) {
  12532. message += " (could not decode reason; invalid data length)";
  12533. }
  12534. else if (hexlify(bytes.slice(0, 4)) === "0x08c379a0") {
  12535. // Error(string)
  12536. try {
  12537. reason = abiCoder.decode(["string"], bytes.slice(4))[0];
  12538. revert = {
  12539. signature: "Error(string)",
  12540. name: "Error",
  12541. args: [reason]
  12542. };
  12543. message += `: ${JSON.stringify(reason)}`;
  12544. }
  12545. catch (error) {
  12546. message += " (could not decode reason; invalid string data)";
  12547. }
  12548. }
  12549. else if (hexlify(bytes.slice(0, 4)) === "0x4e487b71") {
  12550. // Panic(uint256)
  12551. try {
  12552. const code = Number(abiCoder.decode(["uint256"], bytes.slice(4))[0]);
  12553. revert = {
  12554. signature: "Panic(uint256)",
  12555. name: "Panic",
  12556. args: [code]
  12557. };
  12558. reason = `Panic due to ${PanicReasons$1.get(code) || "UNKNOWN"}(${code})`;
  12559. message += `: ${reason}`;
  12560. }
  12561. catch (error) {
  12562. message += " (could not decode panic code)";
  12563. }
  12564. }
  12565. else {
  12566. message += " (unknown custom error)";
  12567. }
  12568. }
  12569. const transaction = {
  12570. to: (tx.to ? getAddress(tx.to) : null),
  12571. data: (tx.data || "0x")
  12572. };
  12573. if (tx.from) {
  12574. transaction.from = getAddress(tx.from);
  12575. }
  12576. return makeError(message, "CALL_EXCEPTION", {
  12577. action, data, reason, transaction, invocation, revert
  12578. });
  12579. }
  12580. /**
  12581. * The **AbiCoder** is a low-level class responsible for encoding JavaScript
  12582. * values into binary data and decoding binary data into JavaScript values.
  12583. */
  12584. class AbiCoder {
  12585. #getCoder(param) {
  12586. if (param.isArray()) {
  12587. return new ArrayCoder(this.#getCoder(param.arrayChildren), param.arrayLength, param.name);
  12588. }
  12589. if (param.isTuple()) {
  12590. return new TupleCoder(param.components.map((c) => this.#getCoder(c)), param.name);
  12591. }
  12592. switch (param.baseType) {
  12593. case "address":
  12594. return new AddressCoder(param.name);
  12595. case "bool":
  12596. return new BooleanCoder(param.name);
  12597. case "string":
  12598. return new StringCoder(param.name);
  12599. case "bytes":
  12600. return new BytesCoder(param.name);
  12601. case "":
  12602. return new NullCoder(param.name);
  12603. }
  12604. // u?int[0-9]*
  12605. let match = param.type.match(paramTypeNumber);
  12606. if (match) {
  12607. let size = parseInt(match[2] || "256");
  12608. assertArgument(size !== 0 && size <= 256 && (size % 8) === 0, "invalid " + match[1] + " bit length", "param", param);
  12609. return new NumberCoder(size / 8, (match[1] === "int"), param.name);
  12610. }
  12611. // bytes[0-9]+
  12612. match = param.type.match(paramTypeBytes);
  12613. if (match) {
  12614. let size = parseInt(match[1]);
  12615. assertArgument(size !== 0 && size <= 32, "invalid bytes length", "param", param);
  12616. return new FixedBytesCoder(size, param.name);
  12617. }
  12618. assertArgument(false, "invalid type", "type", param.type);
  12619. }
  12620. /**
  12621. * Get the default values for the given %%types%%.
  12622. *
  12623. * For example, a ``uint`` is by default ``0`` and ``bool``
  12624. * is by default ``false``.
  12625. */
  12626. getDefaultValue(types) {
  12627. const coders = types.map((type) => this.#getCoder(ParamType.from(type)));
  12628. const coder = new TupleCoder(coders, "_");
  12629. return coder.defaultValue();
  12630. }
  12631. /**
  12632. * Encode the %%values%% as the %%types%% into ABI data.
  12633. *
  12634. * @returns DataHexstring
  12635. */
  12636. encode(types, values) {
  12637. assertArgumentCount(values.length, types.length, "types/values length mismatch");
  12638. const coders = types.map((type) => this.#getCoder(ParamType.from(type)));
  12639. const coder = (new TupleCoder(coders, "_"));
  12640. const writer = new Writer();
  12641. coder.encode(writer, values);
  12642. return writer.data;
  12643. }
  12644. /**
  12645. * Decode the ABI %%data%% as the %%types%% into values.
  12646. *
  12647. * If %%loose%% decoding is enabled, then strict padding is
  12648. * not enforced. Some older versions of Solidity incorrectly
  12649. * padded event data emitted from ``external`` functions.
  12650. */
  12651. decode(types, data, loose) {
  12652. const coders = types.map((type) => this.#getCoder(ParamType.from(type)));
  12653. const coder = new TupleCoder(coders, "_");
  12654. return coder.decode(new Reader(data, loose, defaultMaxInflation));
  12655. }
  12656. static _setDefaultMaxInflation(value) {
  12657. assertArgument(typeof (value) === "number" && Number.isInteger(value), "invalid defaultMaxInflation factor", "value", value);
  12658. defaultMaxInflation = value;
  12659. }
  12660. /**
  12661. * Returns the shared singleton instance of a default [[AbiCoder]].
  12662. *
  12663. * On the first call, the instance is created internally.
  12664. */
  12665. static defaultAbiCoder() {
  12666. if (defaultCoder == null) {
  12667. defaultCoder = new AbiCoder();
  12668. }
  12669. return defaultCoder;
  12670. }
  12671. /**
  12672. * Returns an ethers-compatible [[CallExceptionError]] Error for the given
  12673. * result %%data%% for the [[CallExceptionAction]] %%action%% against
  12674. * the Transaction %%tx%%.
  12675. */
  12676. static getBuiltinCallException(action, tx, data) {
  12677. return getBuiltinCallException(action, tx, data, AbiCoder.defaultAbiCoder());
  12678. }
  12679. }
  12680. /**
  12681. * About bytes32 strings...
  12682. *
  12683. * @_docloc: api/utils:Bytes32 Strings
  12684. */
  12685. /**
  12686. * Encodes %%text%% as a Bytes32 string.
  12687. */
  12688. function encodeBytes32String(text) {
  12689. // Get the bytes
  12690. const bytes = toUtf8Bytes(text);
  12691. // Check we have room for null-termination
  12692. if (bytes.length > 31) {
  12693. throw new Error("bytes32 string must be less than 32 bytes");
  12694. }
  12695. // Zero-pad (implicitly null-terminates)
  12696. return zeroPadBytes(bytes, 32);
  12697. }
  12698. /**
  12699. * Encodes the Bytes32-encoded %%bytes%% into a string.
  12700. */
  12701. function decodeBytes32String(_bytes) {
  12702. const data = getBytes(_bytes, "bytes");
  12703. // Must be 32 bytes with a null-termination
  12704. if (data.length !== 32) {
  12705. throw new Error("invalid bytes32 - not 32 bytes long");
  12706. }
  12707. if (data[31] !== 0) {
  12708. throw new Error("invalid bytes32 string - no null terminator");
  12709. }
  12710. // Find the null termination
  12711. let length = 31;
  12712. while (data[length - 1] === 0) {
  12713. length--;
  12714. }
  12715. // Determine the string value
  12716. return toUtf8String(data.slice(0, length));
  12717. }
  12718. /**
  12719. * The Interface class is a low-level class that accepts an
  12720. * ABI and provides all the necessary functionality to encode
  12721. * and decode paramaters to and results from methods, events
  12722. * and errors.
  12723. *
  12724. * It also provides several convenience methods to automatically
  12725. * search and find matching transactions and events to parse them.
  12726. *
  12727. * @_subsection api/abi:Interfaces [interfaces]
  12728. */
  12729. /**
  12730. * When using the [[Interface-parseLog]] to automatically match a Log to its event
  12731. * for parsing, a **LogDescription** is returned.
  12732. */
  12733. class LogDescription {
  12734. /**
  12735. * The matching fragment for the ``topic0``.
  12736. */
  12737. fragment;
  12738. /**
  12739. * The name of the Event.
  12740. */
  12741. name;
  12742. /**
  12743. * The full Event signature.
  12744. */
  12745. signature;
  12746. /**
  12747. * The topic hash for the Event.
  12748. */
  12749. topic;
  12750. /**
  12751. * The arguments passed into the Event with ``emit``.
  12752. */
  12753. args;
  12754. /**
  12755. * @_ignore:
  12756. */
  12757. constructor(fragment, topic, args) {
  12758. const name = fragment.name, signature = fragment.format();
  12759. defineProperties(this, {
  12760. fragment, name, signature, topic, args
  12761. });
  12762. }
  12763. }
  12764. /**
  12765. * When using the [[Interface-parseTransaction]] to automatically match
  12766. * a transaction data to its function for parsing,
  12767. * a **TransactionDescription** is returned.
  12768. */
  12769. class TransactionDescription {
  12770. /**
  12771. * The matching fragment from the transaction ``data``.
  12772. */
  12773. fragment;
  12774. /**
  12775. * The name of the Function from the transaction ``data``.
  12776. */
  12777. name;
  12778. /**
  12779. * The arguments passed to the Function from the transaction ``data``.
  12780. */
  12781. args;
  12782. /**
  12783. * The full Function signature from the transaction ``data``.
  12784. */
  12785. signature;
  12786. /**
  12787. * The selector for the Function from the transaction ``data``.
  12788. */
  12789. selector;
  12790. /**
  12791. * The ``value`` (in wei) from the transaction.
  12792. */
  12793. value;
  12794. /**
  12795. * @_ignore:
  12796. */
  12797. constructor(fragment, selector, args, value) {
  12798. const name = fragment.name, signature = fragment.format();
  12799. defineProperties(this, {
  12800. fragment, name, args, signature, selector, value
  12801. });
  12802. }
  12803. }
  12804. /**
  12805. * When using the [[Interface-parseError]] to automatically match an
  12806. * error for a call result for parsing, an **ErrorDescription** is returned.
  12807. */
  12808. class ErrorDescription {
  12809. /**
  12810. * The matching fragment.
  12811. */
  12812. fragment;
  12813. /**
  12814. * The name of the Error.
  12815. */
  12816. name;
  12817. /**
  12818. * The arguments passed to the Error with ``revert``.
  12819. */
  12820. args;
  12821. /**
  12822. * The full Error signature.
  12823. */
  12824. signature;
  12825. /**
  12826. * The selector for the Error.
  12827. */
  12828. selector;
  12829. /**
  12830. * @_ignore:
  12831. */
  12832. constructor(fragment, selector, args) {
  12833. const name = fragment.name, signature = fragment.format();
  12834. defineProperties(this, {
  12835. fragment, name, args, signature, selector
  12836. });
  12837. }
  12838. }
  12839. /**
  12840. * An **Indexed** is used as a value when a value that does not
  12841. * fit within a topic (i.e. not a fixed-length, 32-byte type). It
  12842. * is the ``keccak256`` of the value, and used for types such as
  12843. * arrays, tuples, bytes and strings.
  12844. */
  12845. class Indexed {
  12846. /**
  12847. * The ``keccak256`` of the value logged.
  12848. */
  12849. hash;
  12850. /**
  12851. * @_ignore:
  12852. */
  12853. _isIndexed;
  12854. /**
  12855. * Returns ``true`` if %%value%% is an **Indexed**.
  12856. *
  12857. * This provides a Type Guard for property access.
  12858. */
  12859. static isIndexed(value) {
  12860. return !!(value && value._isIndexed);
  12861. }
  12862. /**
  12863. * @_ignore:
  12864. */
  12865. constructor(hash) {
  12866. defineProperties(this, { hash, _isIndexed: true });
  12867. }
  12868. }
  12869. // https://docs.soliditylang.org/en/v0.8.13/control-structures.html?highlight=panic#panic-via-assert-and-error-via-require
  12870. const PanicReasons = {
  12871. "0": "generic panic",
  12872. "1": "assert(false)",
  12873. "17": "arithmetic overflow",
  12874. "18": "division or modulo by zero",
  12875. "33": "enum overflow",
  12876. "34": "invalid encoded storage byte array accessed",
  12877. "49": "out-of-bounds array access; popping on an empty array",
  12878. "50": "out-of-bounds access of an array or bytesN",
  12879. "65": "out of memory",
  12880. "81": "uninitialized function",
  12881. };
  12882. const BuiltinErrors = {
  12883. "0x08c379a0": {
  12884. signature: "Error(string)",
  12885. name: "Error",
  12886. inputs: ["string"],
  12887. reason: (message) => {
  12888. return `reverted with reason string ${JSON.stringify(message)}`;
  12889. }
  12890. },
  12891. "0x4e487b71": {
  12892. signature: "Panic(uint256)",
  12893. name: "Panic",
  12894. inputs: ["uint256"],
  12895. reason: (code) => {
  12896. let reason = "unknown panic code";
  12897. if (code >= 0 && code <= 0xff && PanicReasons[code.toString()]) {
  12898. reason = PanicReasons[code.toString()];
  12899. }
  12900. return `reverted with panic code 0x${code.toString(16)} (${reason})`;
  12901. }
  12902. }
  12903. };
  12904. /**
  12905. * An Interface abstracts many of the low-level details for
  12906. * encoding and decoding the data on the blockchain.
  12907. *
  12908. * An ABI provides information on how to encode data to send to
  12909. * a Contract, how to decode the results and events and how to
  12910. * interpret revert errors.
  12911. *
  12912. * The ABI can be specified by [any supported format](InterfaceAbi).
  12913. */
  12914. class Interface {
  12915. /**
  12916. * All the Contract ABI members (i.e. methods, events, errors, etc).
  12917. */
  12918. fragments;
  12919. /**
  12920. * The Contract constructor.
  12921. */
  12922. deploy;
  12923. /**
  12924. * The Fallback method, if any.
  12925. */
  12926. fallback;
  12927. /**
  12928. * If receiving ether is supported.
  12929. */
  12930. receive;
  12931. #errors;
  12932. #events;
  12933. #functions;
  12934. // #structs: Map<string, StructFragment>;
  12935. #abiCoder;
  12936. /**
  12937. * Create a new Interface for the %%fragments%%.
  12938. */
  12939. constructor(fragments) {
  12940. let abi = [];
  12941. if (typeof (fragments) === "string") {
  12942. abi = JSON.parse(fragments);
  12943. }
  12944. else {
  12945. abi = fragments;
  12946. }
  12947. this.#functions = new Map();
  12948. this.#errors = new Map();
  12949. this.#events = new Map();
  12950. // this.#structs = new Map();
  12951. const frags = [];
  12952. for (const a of abi) {
  12953. try {
  12954. frags.push(Fragment.from(a));
  12955. }
  12956. catch (error) {
  12957. console.log(`[Warning] Invalid Fragment ${JSON.stringify(a)}:`, error.message);
  12958. }
  12959. }
  12960. defineProperties(this, {
  12961. fragments: Object.freeze(frags)
  12962. });
  12963. let fallback = null;
  12964. let receive = false;
  12965. this.#abiCoder = this.getAbiCoder();
  12966. // Add all fragments by their signature
  12967. this.fragments.forEach((fragment, index) => {
  12968. let bucket;
  12969. switch (fragment.type) {
  12970. case "constructor":
  12971. if (this.deploy) {
  12972. console.log("duplicate definition - constructor");
  12973. return;
  12974. }
  12975. //checkNames(fragment, "input", fragment.inputs);
  12976. defineProperties(this, { deploy: fragment });
  12977. return;
  12978. case "fallback":
  12979. if (fragment.inputs.length === 0) {
  12980. receive = true;
  12981. }
  12982. else {
  12983. assertArgument(!fallback || fragment.payable !== fallback.payable, "conflicting fallback fragments", `fragments[${index}]`, fragment);
  12984. fallback = fragment;
  12985. receive = fallback.payable;
  12986. }
  12987. return;
  12988. case "function":
  12989. //checkNames(fragment, "input", fragment.inputs);
  12990. //checkNames(fragment, "output", (<FunctionFragment>fragment).outputs);
  12991. bucket = this.#functions;
  12992. break;
  12993. case "event":
  12994. //checkNames(fragment, "input", fragment.inputs);
  12995. bucket = this.#events;
  12996. break;
  12997. case "error":
  12998. bucket = this.#errors;
  12999. break;
  13000. default:
  13001. return;
  13002. }
  13003. // Two identical entries; ignore it
  13004. const signature = fragment.format();
  13005. if (bucket.has(signature)) {
  13006. return;
  13007. }
  13008. bucket.set(signature, fragment);
  13009. });
  13010. // If we do not have a constructor add a default
  13011. if (!this.deploy) {
  13012. defineProperties(this, {
  13013. deploy: ConstructorFragment.from("constructor()")
  13014. });
  13015. }
  13016. defineProperties(this, { fallback, receive });
  13017. }
  13018. /**
  13019. * Returns the entire Human-Readable ABI, as an array of
  13020. * signatures, optionally as %%minimal%% strings, which
  13021. * removes parameter names and unneceesary spaces.
  13022. */
  13023. format(minimal) {
  13024. const format = (minimal ? "minimal" : "full");
  13025. const abi = this.fragments.map((f) => f.format(format));
  13026. return abi;
  13027. }
  13028. /**
  13029. * Return the JSON-encoded ABI. This is the format Solidiy
  13030. * returns.
  13031. */
  13032. formatJson() {
  13033. const abi = this.fragments.map((f) => f.format("json"));
  13034. // We need to re-bundle the JSON fragments a bit
  13035. return JSON.stringify(abi.map((j) => JSON.parse(j)));
  13036. }
  13037. /**
  13038. * The ABI coder that will be used to encode and decode binary
  13039. * data.
  13040. */
  13041. getAbiCoder() {
  13042. return AbiCoder.defaultAbiCoder();
  13043. }
  13044. // Find a function definition by any means necessary (unless it is ambiguous)
  13045. #getFunction(key, values, forceUnique) {
  13046. // Selector
  13047. if (isHexString(key)) {
  13048. const selector = key.toLowerCase();
  13049. for (const fragment of this.#functions.values()) {
  13050. if (selector === fragment.selector) {
  13051. return fragment;
  13052. }
  13053. }
  13054. return null;
  13055. }
  13056. // It is a bare name, look up the function (will return null if ambiguous)
  13057. if (key.indexOf("(") === -1) {
  13058. const matching = [];
  13059. for (const [name, fragment] of this.#functions) {
  13060. if (name.split("(" /* fix:) */)[0] === key) {
  13061. matching.push(fragment);
  13062. }
  13063. }
  13064. if (values) {
  13065. const lastValue = (values.length > 0) ? values[values.length - 1] : null;
  13066. let valueLength = values.length;
  13067. let allowOptions = true;
  13068. if (Typed.isTyped(lastValue) && lastValue.type === "overrides") {
  13069. allowOptions = false;
  13070. valueLength--;
  13071. }
  13072. // Remove all matches that don't have a compatible length. The args
  13073. // may contain an overrides, so the match may have n or n - 1 parameters
  13074. for (let i = matching.length - 1; i >= 0; i--) {
  13075. const inputs = matching[i].inputs.length;
  13076. if (inputs !== valueLength && (!allowOptions || inputs !== valueLength - 1)) {
  13077. matching.splice(i, 1);
  13078. }
  13079. }
  13080. // Remove all matches that don't match the Typed signature
  13081. for (let i = matching.length - 1; i >= 0; i--) {
  13082. const inputs = matching[i].inputs;
  13083. for (let j = 0; j < values.length; j++) {
  13084. // Not a typed value
  13085. if (!Typed.isTyped(values[j])) {
  13086. continue;
  13087. }
  13088. // We are past the inputs
  13089. if (j >= inputs.length) {
  13090. if (values[j].type === "overrides") {
  13091. continue;
  13092. }
  13093. matching.splice(i, 1);
  13094. break;
  13095. }
  13096. // Make sure the value type matches the input type
  13097. if (values[j].type !== inputs[j].baseType) {
  13098. matching.splice(i, 1);
  13099. break;
  13100. }
  13101. }
  13102. }
  13103. }
  13104. // We found a single matching signature with an overrides, but the
  13105. // last value is something that cannot possibly be an options
  13106. if (matching.length === 1 && values && values.length !== matching[0].inputs.length) {
  13107. const lastArg = values[values.length - 1];
  13108. if (lastArg == null || Array.isArray(lastArg) || typeof (lastArg) !== "object") {
  13109. matching.splice(0, 1);
  13110. }
  13111. }
  13112. if (matching.length === 0) {
  13113. return null;
  13114. }
  13115. if (matching.length > 1 && forceUnique) {
  13116. const matchStr = matching.map((m) => JSON.stringify(m.format())).join(", ");
  13117. assertArgument(false, `ambiguous function description (i.e. matches ${matchStr})`, "key", key);
  13118. }
  13119. return matching[0];
  13120. }
  13121. // Normalize the signature and lookup the function
  13122. const result = this.#functions.get(FunctionFragment.from(key).format());
  13123. if (result) {
  13124. return result;
  13125. }
  13126. return null;
  13127. }
  13128. /**
  13129. * Get the function name for %%key%%, which may be a function selector,
  13130. * function name or function signature that belongs to the ABI.
  13131. */
  13132. getFunctionName(key) {
  13133. const fragment = this.#getFunction(key, null, false);
  13134. assertArgument(fragment, "no matching function", "key", key);
  13135. return fragment.name;
  13136. }
  13137. /**
  13138. * Returns true if %%key%% (a function selector, function name or
  13139. * function signature) is present in the ABI.
  13140. *
  13141. * In the case of a function name, the name may be ambiguous, so
  13142. * accessing the [[FunctionFragment]] may require refinement.
  13143. */
  13144. hasFunction(key) {
  13145. return !!this.#getFunction(key, null, false);
  13146. }
  13147. /**
  13148. * Get the [[FunctionFragment]] for %%key%%, which may be a function
  13149. * selector, function name or function signature that belongs to the ABI.
  13150. *
  13151. * If %%values%% is provided, it will use the Typed API to handle
  13152. * ambiguous cases where multiple functions match by name.
  13153. *
  13154. * If the %%key%% and %%values%% do not refine to a single function in
  13155. * the ABI, this will throw.
  13156. */
  13157. getFunction(key, values) {
  13158. return this.#getFunction(key, values || null, true);
  13159. }
  13160. /**
  13161. * Iterate over all functions, calling %%callback%%, sorted by their name.
  13162. */
  13163. forEachFunction(callback) {
  13164. const names = Array.from(this.#functions.keys());
  13165. names.sort((a, b) => a.localeCompare(b));
  13166. for (let i = 0; i < names.length; i++) {
  13167. const name = names[i];
  13168. callback((this.#functions.get(name)), i);
  13169. }
  13170. }
  13171. // Find an event definition by any means necessary (unless it is ambiguous)
  13172. #getEvent(key, values, forceUnique) {
  13173. // EventTopic
  13174. if (isHexString(key)) {
  13175. const eventTopic = key.toLowerCase();
  13176. for (const fragment of this.#events.values()) {
  13177. if (eventTopic === fragment.topicHash) {
  13178. return fragment;
  13179. }
  13180. }
  13181. return null;
  13182. }
  13183. // It is a bare name, look up the function (will return null if ambiguous)
  13184. if (key.indexOf("(") === -1) {
  13185. const matching = [];
  13186. for (const [name, fragment] of this.#events) {
  13187. if (name.split("(" /* fix:) */)[0] === key) {
  13188. matching.push(fragment);
  13189. }
  13190. }
  13191. if (values) {
  13192. // Remove all matches that don't have a compatible length.
  13193. for (let i = matching.length - 1; i >= 0; i--) {
  13194. if (matching[i].inputs.length < values.length) {
  13195. matching.splice(i, 1);
  13196. }
  13197. }
  13198. // Remove all matches that don't match the Typed signature
  13199. for (let i = matching.length - 1; i >= 0; i--) {
  13200. const inputs = matching[i].inputs;
  13201. for (let j = 0; j < values.length; j++) {
  13202. // Not a typed value
  13203. if (!Typed.isTyped(values[j])) {
  13204. continue;
  13205. }
  13206. // Make sure the value type matches the input type
  13207. if (values[j].type !== inputs[j].baseType) {
  13208. matching.splice(i, 1);
  13209. break;
  13210. }
  13211. }
  13212. }
  13213. }
  13214. if (matching.length === 0) {
  13215. return null;
  13216. }
  13217. if (matching.length > 1 && forceUnique) {
  13218. const matchStr = matching.map((m) => JSON.stringify(m.format())).join(", ");
  13219. assertArgument(false, `ambiguous event description (i.e. matches ${matchStr})`, "key", key);
  13220. }
  13221. return matching[0];
  13222. }
  13223. // Normalize the signature and lookup the function
  13224. const result = this.#events.get(EventFragment.from(key).format());
  13225. if (result) {
  13226. return result;
  13227. }
  13228. return null;
  13229. }
  13230. /**
  13231. * Get the event name for %%key%%, which may be a topic hash,
  13232. * event name or event signature that belongs to the ABI.
  13233. */
  13234. getEventName(key) {
  13235. const fragment = this.#getEvent(key, null, false);
  13236. assertArgument(fragment, "no matching event", "key", key);
  13237. return fragment.name;
  13238. }
  13239. /**
  13240. * Returns true if %%key%% (an event topic hash, event name or
  13241. * event signature) is present in the ABI.
  13242. *
  13243. * In the case of an event name, the name may be ambiguous, so
  13244. * accessing the [[EventFragment]] may require refinement.
  13245. */
  13246. hasEvent(key) {
  13247. return !!this.#getEvent(key, null, false);
  13248. }
  13249. /**
  13250. * Get the [[EventFragment]] for %%key%%, which may be a topic hash,
  13251. * event name or event signature that belongs to the ABI.
  13252. *
  13253. * If %%values%% is provided, it will use the Typed API to handle
  13254. * ambiguous cases where multiple events match by name.
  13255. *
  13256. * If the %%key%% and %%values%% do not refine to a single event in
  13257. * the ABI, this will throw.
  13258. */
  13259. getEvent(key, values) {
  13260. return this.#getEvent(key, values || null, true);
  13261. }
  13262. /**
  13263. * Iterate over all events, calling %%callback%%, sorted by their name.
  13264. */
  13265. forEachEvent(callback) {
  13266. const names = Array.from(this.#events.keys());
  13267. names.sort((a, b) => a.localeCompare(b));
  13268. for (let i = 0; i < names.length; i++) {
  13269. const name = names[i];
  13270. callback((this.#events.get(name)), i);
  13271. }
  13272. }
  13273. /**
  13274. * Get the [[ErrorFragment]] for %%key%%, which may be an error
  13275. * selector, error name or error signature that belongs to the ABI.
  13276. *
  13277. * If %%values%% is provided, it will use the Typed API to handle
  13278. * ambiguous cases where multiple errors match by name.
  13279. *
  13280. * If the %%key%% and %%values%% do not refine to a single error in
  13281. * the ABI, this will throw.
  13282. */
  13283. getError(key, values) {
  13284. if (isHexString(key)) {
  13285. const selector = key.toLowerCase();
  13286. if (BuiltinErrors[selector]) {
  13287. return ErrorFragment.from(BuiltinErrors[selector].signature);
  13288. }
  13289. for (const fragment of this.#errors.values()) {
  13290. if (selector === fragment.selector) {
  13291. return fragment;
  13292. }
  13293. }
  13294. return null;
  13295. }
  13296. // It is a bare name, look up the function (will return null if ambiguous)
  13297. if (key.indexOf("(") === -1) {
  13298. const matching = [];
  13299. for (const [name, fragment] of this.#errors) {
  13300. if (name.split("(" /* fix:) */)[0] === key) {
  13301. matching.push(fragment);
  13302. }
  13303. }
  13304. if (matching.length === 0) {
  13305. if (key === "Error") {
  13306. return ErrorFragment.from("error Error(string)");
  13307. }
  13308. if (key === "Panic") {
  13309. return ErrorFragment.from("error Panic(uint256)");
  13310. }
  13311. return null;
  13312. }
  13313. else if (matching.length > 1) {
  13314. const matchStr = matching.map((m) => JSON.stringify(m.format())).join(", ");
  13315. assertArgument(false, `ambiguous error description (i.e. ${matchStr})`, "name", key);
  13316. }
  13317. return matching[0];
  13318. }
  13319. // Normalize the signature and lookup the function
  13320. key = ErrorFragment.from(key).format();
  13321. if (key === "Error(string)") {
  13322. return ErrorFragment.from("error Error(string)");
  13323. }
  13324. if (key === "Panic(uint256)") {
  13325. return ErrorFragment.from("error Panic(uint256)");
  13326. }
  13327. const result = this.#errors.get(key);
  13328. if (result) {
  13329. return result;
  13330. }
  13331. return null;
  13332. }
  13333. /**
  13334. * Iterate over all errors, calling %%callback%%, sorted by their name.
  13335. */
  13336. forEachError(callback) {
  13337. const names = Array.from(this.#errors.keys());
  13338. names.sort((a, b) => a.localeCompare(b));
  13339. for (let i = 0; i < names.length; i++) {
  13340. const name = names[i];
  13341. callback((this.#errors.get(name)), i);
  13342. }
  13343. }
  13344. // Get the 4-byte selector used by Solidity to identify a function
  13345. /*
  13346. getSelector(fragment: ErrorFragment | FunctionFragment): string {
  13347. if (typeof(fragment) === "string") {
  13348. const matches: Array<Fragment> = [ ];
  13349. try { matches.push(this.getFunction(fragment)); } catch (error) { }
  13350. try { matches.push(this.getError(<string>fragment)); } catch (_) { }
  13351. if (matches.length === 0) {
  13352. logger.throwArgumentError("unknown fragment", "key", fragment);
  13353. } else if (matches.length > 1) {
  13354. logger.throwArgumentError("ambiguous fragment matches function and error", "key", fragment);
  13355. }
  13356. fragment = matches[0];
  13357. }
  13358. return dataSlice(id(fragment.format()), 0, 4);
  13359. }
  13360. */
  13361. // Get the 32-byte topic hash used by Solidity to identify an event
  13362. /*
  13363. getEventTopic(fragment: EventFragment): string {
  13364. //if (typeof(fragment) === "string") { fragment = this.getEvent(eventFragment); }
  13365. return id(fragment.format());
  13366. }
  13367. */
  13368. _decodeParams(params, data) {
  13369. return this.#abiCoder.decode(params, data);
  13370. }
  13371. _encodeParams(params, values) {
  13372. return this.#abiCoder.encode(params, values);
  13373. }
  13374. /**
  13375. * Encodes a ``tx.data`` object for deploying the Contract with
  13376. * the %%values%% as the constructor arguments.
  13377. */
  13378. encodeDeploy(values) {
  13379. return this._encodeParams(this.deploy.inputs, values || []);
  13380. }
  13381. /**
  13382. * Decodes the result %%data%% (e.g. from an ``eth_call``) for the
  13383. * specified error (see [[getError]] for valid values for
  13384. * %%key%%).
  13385. *
  13386. * Most developers should prefer the [[parseCallResult]] method instead,
  13387. * which will automatically detect a ``CALL_EXCEPTION`` and throw the
  13388. * corresponding error.
  13389. */
  13390. decodeErrorResult(fragment, data) {
  13391. if (typeof (fragment) === "string") {
  13392. const f = this.getError(fragment);
  13393. assertArgument(f, "unknown error", "fragment", fragment);
  13394. fragment = f;
  13395. }
  13396. assertArgument(dataSlice(data, 0, 4) === fragment.selector, `data signature does not match error ${fragment.name}.`, "data", data);
  13397. return this._decodeParams(fragment.inputs, dataSlice(data, 4));
  13398. }
  13399. /**
  13400. * Encodes the transaction revert data for a call result that
  13401. * reverted from the the Contract with the sepcified %%error%%
  13402. * (see [[getError]] for valid values for %%fragment%%) with the %%values%%.
  13403. *
  13404. * This is generally not used by most developers, unless trying to mock
  13405. * a result from a Contract.
  13406. */
  13407. encodeErrorResult(fragment, values) {
  13408. if (typeof (fragment) === "string") {
  13409. const f = this.getError(fragment);
  13410. assertArgument(f, "unknown error", "fragment", fragment);
  13411. fragment = f;
  13412. }
  13413. return concat([
  13414. fragment.selector,
  13415. this._encodeParams(fragment.inputs, values || [])
  13416. ]);
  13417. }
  13418. /**
  13419. * Decodes the %%data%% from a transaction ``tx.data`` for
  13420. * the function specified (see [[getFunction]] for valid values
  13421. * for %%fragment%%).
  13422. *
  13423. * Most developers should prefer the [[parseTransaction]] method
  13424. * instead, which will automatically detect the fragment.
  13425. */
  13426. decodeFunctionData(fragment, data) {
  13427. if (typeof (fragment) === "string") {
  13428. const f = this.getFunction(fragment);
  13429. assertArgument(f, "unknown function", "fragment", fragment);
  13430. fragment = f;
  13431. }
  13432. assertArgument(dataSlice(data, 0, 4) === fragment.selector, `data signature does not match function ${fragment.name}.`, "data", data);
  13433. return this._decodeParams(fragment.inputs, dataSlice(data, 4));
  13434. }
  13435. /**
  13436. * Encodes the ``tx.data`` for a transaction that calls the function
  13437. * specified (see [[getFunction]] for valid values for %%fragment%%) with
  13438. * the %%values%%.
  13439. */
  13440. encodeFunctionData(fragment, values) {
  13441. if (typeof (fragment) === "string") {
  13442. const f = this.getFunction(fragment);
  13443. assertArgument(f, "unknown function", "fragment", fragment);
  13444. fragment = f;
  13445. }
  13446. return concat([
  13447. fragment.selector,
  13448. this._encodeParams(fragment.inputs, values || [])
  13449. ]);
  13450. }
  13451. /**
  13452. * Decodes the result %%data%% (e.g. from an ``eth_call``) for the
  13453. * specified function (see [[getFunction]] for valid values for
  13454. * %%key%%).
  13455. *
  13456. * Most developers should prefer the [[parseCallResult]] method instead,
  13457. * which will automatically detect a ``CALL_EXCEPTION`` and throw the
  13458. * corresponding error.
  13459. */
  13460. decodeFunctionResult(fragment, data) {
  13461. if (typeof (fragment) === "string") {
  13462. const f = this.getFunction(fragment);
  13463. assertArgument(f, "unknown function", "fragment", fragment);
  13464. fragment = f;
  13465. }
  13466. let message = "invalid length for result data";
  13467. const bytes = getBytesCopy(data);
  13468. if ((bytes.length % 32) === 0) {
  13469. try {
  13470. return this.#abiCoder.decode(fragment.outputs, bytes);
  13471. }
  13472. catch (error) {
  13473. message = "could not decode result data";
  13474. }
  13475. }
  13476. // Call returned data with no error, but the data is junk
  13477. assert(false, message, "BAD_DATA", {
  13478. value: hexlify(bytes),
  13479. info: { method: fragment.name, signature: fragment.format() }
  13480. });
  13481. }
  13482. makeError(_data, tx) {
  13483. const data = getBytes(_data, "data");
  13484. const error = AbiCoder.getBuiltinCallException("call", tx, data);
  13485. // Not a built-in error; try finding a custom error
  13486. const customPrefix = "execution reverted (unknown custom error)";
  13487. if (error.message.startsWith(customPrefix)) {
  13488. const selector = hexlify(data.slice(0, 4));
  13489. const ef = this.getError(selector);
  13490. if (ef) {
  13491. try {
  13492. const args = this.#abiCoder.decode(ef.inputs, data.slice(4));
  13493. error.revert = {
  13494. name: ef.name, signature: ef.format(), args
  13495. };
  13496. error.reason = error.revert.signature;
  13497. error.message = `execution reverted: ${error.reason}`;
  13498. }
  13499. catch (e) {
  13500. error.message = `execution reverted (coult not decode custom error)`;
  13501. }
  13502. }
  13503. }
  13504. // Add the invocation, if available
  13505. const parsed = this.parseTransaction(tx);
  13506. if (parsed) {
  13507. error.invocation = {
  13508. method: parsed.name,
  13509. signature: parsed.signature,
  13510. args: parsed.args
  13511. };
  13512. }
  13513. return error;
  13514. }
  13515. /**
  13516. * Encodes the result data (e.g. from an ``eth_call``) for the
  13517. * specified function (see [[getFunction]] for valid values
  13518. * for %%fragment%%) with %%values%%.
  13519. *
  13520. * This is generally not used by most developers, unless trying to mock
  13521. * a result from a Contract.
  13522. */
  13523. encodeFunctionResult(fragment, values) {
  13524. if (typeof (fragment) === "string") {
  13525. const f = this.getFunction(fragment);
  13526. assertArgument(f, "unknown function", "fragment", fragment);
  13527. fragment = f;
  13528. }
  13529. return hexlify(this.#abiCoder.encode(fragment.outputs, values || []));
  13530. }
  13531. /*
  13532. spelunk(inputs: Array<ParamType>, values: ReadonlyArray<any>, processfunc: (type: string, value: any) => Promise<any>): Promise<Array<any>> {
  13533. const promises: Array<Promise<>> = [ ];
  13534. const process = function(type: ParamType, value: any): any {
  13535. if (type.baseType === "array") {
  13536. return descend(type.child
  13537. }
  13538. if (type. === "address") {
  13539. }
  13540. };
  13541. const descend = function (inputs: Array<ParamType>, values: ReadonlyArray<any>) {
  13542. if (inputs.length !== values.length) { throw new Error("length mismatch"); }
  13543. };
  13544. const result: Array<any> = [ ];
  13545. values.forEach((value, index) => {
  13546. if (value == null) {
  13547. topics.push(null);
  13548. } else if (param.baseType === "array" || param.baseType === "tuple") {
  13549. logger.throwArgumentError("filtering with tuples or arrays not supported", ("contract." + param.name), value);
  13550. } else if (Array.isArray(value)) {
  13551. topics.push(value.map((value) => encodeTopic(param, value)));
  13552. } else {
  13553. topics.push(encodeTopic(param, value));
  13554. }
  13555. });
  13556. }
  13557. */
  13558. // Create the filter for the event with search criteria (e.g. for eth_filterLog)
  13559. encodeFilterTopics(fragment, values) {
  13560. if (typeof (fragment) === "string") {
  13561. const f = this.getEvent(fragment);
  13562. assertArgument(f, "unknown event", "eventFragment", fragment);
  13563. fragment = f;
  13564. }
  13565. assert(values.length <= fragment.inputs.length, `too many arguments for ${fragment.format()}`, "UNEXPECTED_ARGUMENT", { count: values.length, expectedCount: fragment.inputs.length });
  13566. const topics = [];
  13567. if (!fragment.anonymous) {
  13568. topics.push(fragment.topicHash);
  13569. }
  13570. // @TODO: Use the coders for this; to properly support tuples, etc.
  13571. const encodeTopic = (param, value) => {
  13572. if (param.type === "string") {
  13573. return id(value);
  13574. }
  13575. else if (param.type === "bytes") {
  13576. return keccak256(hexlify(value));
  13577. }
  13578. if (param.type === "bool" && typeof (value) === "boolean") {
  13579. value = (value ? "0x01" : "0x00");
  13580. }
  13581. else if (param.type.match(/^u?int/)) {
  13582. value = toBeHex(value); // @TODO: Should this toTwos??
  13583. }
  13584. else if (param.type.match(/^bytes/)) {
  13585. value = zeroPadBytes(value, 32);
  13586. }
  13587. else if (param.type === "address") {
  13588. // Check addresses are valid
  13589. this.#abiCoder.encode(["address"], [value]);
  13590. }
  13591. return zeroPadValue(hexlify(value), 32);
  13592. };
  13593. values.forEach((value, index) => {
  13594. const param = fragment.inputs[index];
  13595. if (!param.indexed) {
  13596. assertArgument(value == null, "cannot filter non-indexed parameters; must be null", ("contract." + param.name), value);
  13597. return;
  13598. }
  13599. if (value == null) {
  13600. topics.push(null);
  13601. }
  13602. else if (param.baseType === "array" || param.baseType === "tuple") {
  13603. assertArgument(false, "filtering with tuples or arrays not supported", ("contract." + param.name), value);
  13604. }
  13605. else if (Array.isArray(value)) {
  13606. topics.push(value.map((value) => encodeTopic(param, value)));
  13607. }
  13608. else {
  13609. topics.push(encodeTopic(param, value));
  13610. }
  13611. });
  13612. // Trim off trailing nulls
  13613. while (topics.length && topics[topics.length - 1] === null) {
  13614. topics.pop();
  13615. }
  13616. return topics;
  13617. }
  13618. encodeEventLog(fragment, values) {
  13619. if (typeof (fragment) === "string") {
  13620. const f = this.getEvent(fragment);
  13621. assertArgument(f, "unknown event", "eventFragment", fragment);
  13622. fragment = f;
  13623. }
  13624. const topics = [];
  13625. const dataTypes = [];
  13626. const dataValues = [];
  13627. if (!fragment.anonymous) {
  13628. topics.push(fragment.topicHash);
  13629. }
  13630. assertArgument(values.length === fragment.inputs.length, "event arguments/values mismatch", "values", values);
  13631. fragment.inputs.forEach((param, index) => {
  13632. const value = values[index];
  13633. if (param.indexed) {
  13634. if (param.type === "string") {
  13635. topics.push(id(value));
  13636. }
  13637. else if (param.type === "bytes") {
  13638. topics.push(keccak256(value));
  13639. }
  13640. else if (param.baseType === "tuple" || param.baseType === "array") {
  13641. // @TODO
  13642. throw new Error("not implemented");
  13643. }
  13644. else {
  13645. topics.push(this.#abiCoder.encode([param.type], [value]));
  13646. }
  13647. }
  13648. else {
  13649. dataTypes.push(param);
  13650. dataValues.push(value);
  13651. }
  13652. });
  13653. return {
  13654. data: this.#abiCoder.encode(dataTypes, dataValues),
  13655. topics: topics
  13656. };
  13657. }
  13658. // Decode a filter for the event and the search criteria
  13659. decodeEventLog(fragment, data, topics) {
  13660. if (typeof (fragment) === "string") {
  13661. const f = this.getEvent(fragment);
  13662. assertArgument(f, "unknown event", "eventFragment", fragment);
  13663. fragment = f;
  13664. }
  13665. if (topics != null && !fragment.anonymous) {
  13666. const eventTopic = fragment.topicHash;
  13667. assertArgument(isHexString(topics[0], 32) && topics[0].toLowerCase() === eventTopic, "fragment/topic mismatch", "topics[0]", topics[0]);
  13668. topics = topics.slice(1);
  13669. }
  13670. const indexed = [];
  13671. const nonIndexed = [];
  13672. const dynamic = [];
  13673. fragment.inputs.forEach((param, index) => {
  13674. if (param.indexed) {
  13675. if (param.type === "string" || param.type === "bytes" || param.baseType === "tuple" || param.baseType === "array") {
  13676. indexed.push(ParamType.from({ type: "bytes32", name: param.name }));
  13677. dynamic.push(true);
  13678. }
  13679. else {
  13680. indexed.push(param);
  13681. dynamic.push(false);
  13682. }
  13683. }
  13684. else {
  13685. nonIndexed.push(param);
  13686. dynamic.push(false);
  13687. }
  13688. });
  13689. const resultIndexed = (topics != null) ? this.#abiCoder.decode(indexed, concat(topics)) : null;
  13690. const resultNonIndexed = this.#abiCoder.decode(nonIndexed, data, true);
  13691. //const result: (Array<any> & { [ key: string ]: any }) = [ ];
  13692. const values = [];
  13693. const keys = [];
  13694. let nonIndexedIndex = 0, indexedIndex = 0;
  13695. fragment.inputs.forEach((param, index) => {
  13696. let value = null;
  13697. if (param.indexed) {
  13698. if (resultIndexed == null) {
  13699. value = new Indexed(null);
  13700. }
  13701. else if (dynamic[index]) {
  13702. value = new Indexed(resultIndexed[indexedIndex++]);
  13703. }
  13704. else {
  13705. try {
  13706. value = resultIndexed[indexedIndex++];
  13707. }
  13708. catch (error) {
  13709. value = error;
  13710. }
  13711. }
  13712. }
  13713. else {
  13714. try {
  13715. value = resultNonIndexed[nonIndexedIndex++];
  13716. }
  13717. catch (error) {
  13718. value = error;
  13719. }
  13720. }
  13721. values.push(value);
  13722. keys.push(param.name || null);
  13723. });
  13724. return Result.fromItems(values, keys);
  13725. }
  13726. /**
  13727. * Parses a transaction, finding the matching function and extracts
  13728. * the parameter values along with other useful function details.
  13729. *
  13730. * If the matching function cannot be found, return null.
  13731. */
  13732. parseTransaction(tx) {
  13733. const data = getBytes(tx.data, "tx.data");
  13734. const value = getBigInt((tx.value != null) ? tx.value : 0, "tx.value");
  13735. const fragment = this.getFunction(hexlify(data.slice(0, 4)));
  13736. if (!fragment) {
  13737. return null;
  13738. }
  13739. const args = this.#abiCoder.decode(fragment.inputs, data.slice(4));
  13740. return new TransactionDescription(fragment, fragment.selector, args, value);
  13741. }
  13742. parseCallResult(data) {
  13743. throw new Error("@TODO");
  13744. }
  13745. /**
  13746. * Parses a receipt log, finding the matching event and extracts
  13747. * the parameter values along with other useful event details.
  13748. *
  13749. * If the matching event cannot be found, returns null.
  13750. */
  13751. parseLog(log) {
  13752. const fragment = this.getEvent(log.topics[0]);
  13753. if (!fragment || fragment.anonymous) {
  13754. return null;
  13755. }
  13756. // @TODO: If anonymous, and the only method, and the input count matches, should we parse?
  13757. // Probably not, because just because it is the only event in the ABI does
  13758. // not mean we have the full ABI; maybe just a fragment?
  13759. return new LogDescription(fragment, fragment.topicHash, this.decodeEventLog(fragment, log.data, log.topics));
  13760. }
  13761. /**
  13762. * Parses a revert data, finding the matching error and extracts
  13763. * the parameter values along with other useful error details.
  13764. *
  13765. * If the matching error cannot be found, returns null.
  13766. */
  13767. parseError(data) {
  13768. const hexData = hexlify(data);
  13769. const fragment = this.getError(dataSlice(hexData, 0, 4));
  13770. if (!fragment) {
  13771. return null;
  13772. }
  13773. const args = this.#abiCoder.decode(fragment.inputs, dataSlice(hexData, 4));
  13774. return new ErrorDescription(fragment, fragment.selector, args);
  13775. }
  13776. /**
  13777. * Creates a new [[Interface]] from the ABI %%value%%.
  13778. *
  13779. * The %%value%% may be provided as an existing [[Interface]] object,
  13780. * a JSON-encoded ABI or any Human-Readable ABI format.
  13781. */
  13782. static from(value) {
  13783. // Already an Interface, which is immutable
  13784. if (value instanceof Interface) {
  13785. return value;
  13786. }
  13787. // JSON
  13788. if (typeof (value) === "string") {
  13789. return new Interface(JSON.parse(value));
  13790. }
  13791. // An Interface; possibly from another v6 instance
  13792. if (typeof (value.formatJson) === "function") {
  13793. return new Interface(value.formatJson());
  13794. }
  13795. // A legacy Interface; from an older version
  13796. if (typeof (value.format) === "function") {
  13797. return new Interface(value.format("json"));
  13798. }
  13799. // Array of fragments
  13800. return new Interface(value);
  13801. }
  13802. }
  13803. //import { resolveAddress } from "@ethersproject/address";
  13804. const BN_0$2 = BigInt(0);
  13805. // -----------------------
  13806. function getValue(value) {
  13807. if (value == null) {
  13808. return null;
  13809. }
  13810. return value;
  13811. }
  13812. function toJson(value) {
  13813. if (value == null) {
  13814. return null;
  13815. }
  13816. return value.toString();
  13817. }
  13818. // @TODO? <T extends FeeData = { }> implements Required<T>
  13819. /**
  13820. * A **FeeData** wraps all the fee-related values associated with
  13821. * the network.
  13822. */
  13823. class FeeData {
  13824. /**
  13825. * The gas price for legacy networks.
  13826. */
  13827. gasPrice;
  13828. /**
  13829. * The maximum fee to pay per gas.
  13830. *
  13831. * The base fee per gas is defined by the network and based on
  13832. * congestion, increasing the cost during times of heavy load
  13833. * and lowering when less busy.
  13834. *
  13835. * The actual fee per gas will be the base fee for the block
  13836. * and the priority fee, up to the max fee per gas.
  13837. *
  13838. * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559))
  13839. */
  13840. maxFeePerGas;
  13841. /**
  13842. * The additional amout to pay per gas to encourage a validator
  13843. * to include the transaction.
  13844. *
  13845. * The purpose of this is to compensate the validator for the
  13846. * adjusted risk for including a given transaction.
  13847. *
  13848. * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559))
  13849. */
  13850. maxPriorityFeePerGas;
  13851. /**
  13852. * Creates a new FeeData for %%gasPrice%%, %%maxFeePerGas%% and
  13853. * %%maxPriorityFeePerGas%%.
  13854. */
  13855. constructor(gasPrice, maxFeePerGas, maxPriorityFeePerGas) {
  13856. defineProperties(this, {
  13857. gasPrice: getValue(gasPrice),
  13858. maxFeePerGas: getValue(maxFeePerGas),
  13859. maxPriorityFeePerGas: getValue(maxPriorityFeePerGas)
  13860. });
  13861. }
  13862. /**
  13863. * Returns a JSON-friendly value.
  13864. */
  13865. toJSON() {
  13866. const { gasPrice, maxFeePerGas, maxPriorityFeePerGas } = this;
  13867. return {
  13868. _type: "FeeData",
  13869. gasPrice: toJson(gasPrice),
  13870. maxFeePerGas: toJson(maxFeePerGas),
  13871. maxPriorityFeePerGas: toJson(maxPriorityFeePerGas),
  13872. };
  13873. }
  13874. }
  13875. /**
  13876. * Returns a copy of %%req%% with all properties coerced to their strict
  13877. * types.
  13878. */
  13879. function copyRequest(req) {
  13880. const result = {};
  13881. // These could be addresses, ENS names or Addressables
  13882. if (req.to) {
  13883. result.to = req.to;
  13884. }
  13885. if (req.from) {
  13886. result.from = req.from;
  13887. }
  13888. if (req.data) {
  13889. result.data = hexlify(req.data);
  13890. }
  13891. const bigIntKeys = "chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/);
  13892. for (const key of bigIntKeys) {
  13893. if (!(key in req) || req[key] == null) {
  13894. continue;
  13895. }
  13896. result[key] = getBigInt(req[key], `request.${key}`);
  13897. }
  13898. const numberKeys = "type,nonce".split(/,/);
  13899. for (const key of numberKeys) {
  13900. if (!(key in req) || req[key] == null) {
  13901. continue;
  13902. }
  13903. result[key] = getNumber(req[key], `request.${key}`);
  13904. }
  13905. if (req.accessList) {
  13906. result.accessList = accessListify(req.accessList);
  13907. }
  13908. if ("blockTag" in req) {
  13909. result.blockTag = req.blockTag;
  13910. }
  13911. if ("enableCcipRead" in req) {
  13912. result.enableCcipRead = !!req.enableCcipRead;
  13913. }
  13914. if ("customData" in req) {
  13915. result.customData = req.customData;
  13916. }
  13917. if ("blobVersionedHashes" in req && req.blobVersionedHashes) {
  13918. result.blobVersionedHashes = req.blobVersionedHashes.slice();
  13919. }
  13920. if ("kzg" in req) {
  13921. result.kzg = req.kzg;
  13922. }
  13923. if ("blobs" in req && req.blobs) {
  13924. result.blobs = req.blobs.map((b) => {
  13925. if (isBytesLike(b)) {
  13926. return hexlify(b);
  13927. }
  13928. return Object.assign({}, b);
  13929. });
  13930. }
  13931. return result;
  13932. }
  13933. /**
  13934. * A **Block** represents the data associated with a full block on
  13935. * Ethereum.
  13936. */
  13937. class Block {
  13938. /**
  13939. * The provider connected to the block used to fetch additional details
  13940. * if necessary.
  13941. */
  13942. provider;
  13943. /**
  13944. * The block number, sometimes called the block height. This is a
  13945. * sequential number that is one higher than the parent block.
  13946. */
  13947. number;
  13948. /**
  13949. * The block hash.
  13950. *
  13951. * This hash includes all properties, so can be safely used to identify
  13952. * an exact set of block properties.
  13953. */
  13954. hash;
  13955. /**
  13956. * The timestamp for this block, which is the number of seconds since
  13957. * epoch that this block was included.
  13958. */
  13959. timestamp;
  13960. /**
  13961. * The block hash of the parent block.
  13962. */
  13963. parentHash;
  13964. /**
  13965. * The hash tree root of the parent beacon block for the given
  13966. * execution block. See [[link-eip-4788]].
  13967. */
  13968. parentBeaconBlockRoot;
  13969. /**
  13970. * The nonce.
  13971. *
  13972. * On legacy networks, this is the random number inserted which
  13973. * permitted the difficulty target to be reached.
  13974. */
  13975. nonce;
  13976. /**
  13977. * The difficulty target.
  13978. *
  13979. * On legacy networks, this is the proof-of-work target required
  13980. * for a block to meet the protocol rules to be included.
  13981. *
  13982. * On modern networks, this is a random number arrived at using
  13983. * randao. @TODO: Find links?
  13984. */
  13985. difficulty;
  13986. /**
  13987. * The total gas limit for this block.
  13988. */
  13989. gasLimit;
  13990. /**
  13991. * The total gas used in this block.
  13992. */
  13993. gasUsed;
  13994. /**
  13995. * The root hash for the global state after applying changes
  13996. * in this block.
  13997. */
  13998. stateRoot;
  13999. /**
  14000. * The hash of the transaction receipts trie.
  14001. */
  14002. receiptsRoot;
  14003. /**
  14004. * The total amount of blob gas consumed by the transactions
  14005. * within the block. See [[link-eip-4844]].
  14006. */
  14007. blobGasUsed;
  14008. /**
  14009. * The running total of blob gas consumed in excess of the
  14010. * target, prior to the block. See [[link-eip-4844]].
  14011. */
  14012. excessBlobGas;
  14013. /**
  14014. * The miner coinbase address, wihch receives any subsidies for
  14015. * including this block.
  14016. */
  14017. miner;
  14018. /**
  14019. * The latest RANDAO mix of the post beacon state of
  14020. * the previous block.
  14021. */
  14022. prevRandao;
  14023. /**
  14024. * Any extra data the validator wished to include.
  14025. */
  14026. extraData;
  14027. /**
  14028. * The base fee per gas that all transactions in this block were
  14029. * charged.
  14030. *
  14031. * This adjusts after each block, depending on how congested the network
  14032. * is.
  14033. */
  14034. baseFeePerGas;
  14035. #transactions;
  14036. /**
  14037. * Create a new **Block** object.
  14038. *
  14039. * This should generally not be necessary as the unless implementing a
  14040. * low-level library.
  14041. */
  14042. constructor(block, provider) {
  14043. this.#transactions = block.transactions.map((tx) => {
  14044. if (typeof (tx) !== "string") {
  14045. return new TransactionResponse(tx, provider);
  14046. }
  14047. return tx;
  14048. });
  14049. defineProperties(this, {
  14050. provider,
  14051. hash: getValue(block.hash),
  14052. number: block.number,
  14053. timestamp: block.timestamp,
  14054. parentHash: block.parentHash,
  14055. parentBeaconBlockRoot: block.parentBeaconBlockRoot,
  14056. nonce: block.nonce,
  14057. difficulty: block.difficulty,
  14058. gasLimit: block.gasLimit,
  14059. gasUsed: block.gasUsed,
  14060. blobGasUsed: block.blobGasUsed,
  14061. excessBlobGas: block.excessBlobGas,
  14062. miner: block.miner,
  14063. prevRandao: getValue(block.prevRandao),
  14064. extraData: block.extraData,
  14065. baseFeePerGas: getValue(block.baseFeePerGas),
  14066. stateRoot: block.stateRoot,
  14067. receiptsRoot: block.receiptsRoot,
  14068. });
  14069. }
  14070. /**
  14071. * Returns the list of transaction hashes, in the order
  14072. * they were executed within the block.
  14073. */
  14074. get transactions() {
  14075. return this.#transactions.map((tx) => {
  14076. if (typeof (tx) === "string") {
  14077. return tx;
  14078. }
  14079. return tx.hash;
  14080. });
  14081. }
  14082. /**
  14083. * Returns the complete transactions, in the order they
  14084. * were executed within the block.
  14085. *
  14086. * This is only available for blocks which prefetched
  14087. * transactions, by passing ``true`` to %%prefetchTxs%%
  14088. * into [[Provider-getBlock]].
  14089. */
  14090. get prefetchedTransactions() {
  14091. const txs = this.#transactions.slice();
  14092. // Doesn't matter...
  14093. if (txs.length === 0) {
  14094. return [];
  14095. }
  14096. // Make sure we prefetched the transactions
  14097. assert(typeof (txs[0]) === "object", "transactions were not prefetched with block request", "UNSUPPORTED_OPERATION", {
  14098. operation: "transactionResponses()"
  14099. });
  14100. return txs;
  14101. }
  14102. /**
  14103. * Returns a JSON-friendly value.
  14104. */
  14105. toJSON() {
  14106. const { baseFeePerGas, difficulty, extraData, gasLimit, gasUsed, hash, miner, prevRandao, nonce, number, parentHash, parentBeaconBlockRoot, stateRoot, receiptsRoot, timestamp, transactions } = this;
  14107. return {
  14108. _type: "Block",
  14109. baseFeePerGas: toJson(baseFeePerGas),
  14110. difficulty: toJson(difficulty),
  14111. extraData,
  14112. gasLimit: toJson(gasLimit),
  14113. gasUsed: toJson(gasUsed),
  14114. blobGasUsed: toJson(this.blobGasUsed),
  14115. excessBlobGas: toJson(this.excessBlobGas),
  14116. hash, miner, prevRandao, nonce, number, parentHash, timestamp,
  14117. parentBeaconBlockRoot, stateRoot, receiptsRoot,
  14118. transactions,
  14119. };
  14120. }
  14121. [Symbol.iterator]() {
  14122. let index = 0;
  14123. const txs = this.transactions;
  14124. return {
  14125. next: () => {
  14126. if (index < this.length) {
  14127. return {
  14128. value: txs[index++], done: false
  14129. };
  14130. }
  14131. return { value: undefined, done: true };
  14132. }
  14133. };
  14134. }
  14135. /**
  14136. * The number of transactions in this block.
  14137. */
  14138. get length() { return this.#transactions.length; }
  14139. /**
  14140. * The [[link-js-date]] this block was included at.
  14141. */
  14142. get date() {
  14143. if (this.timestamp == null) {
  14144. return null;
  14145. }
  14146. return new Date(this.timestamp * 1000);
  14147. }
  14148. /**
  14149. * Get the transaction at %%indexe%% within this block.
  14150. */
  14151. async getTransaction(indexOrHash) {
  14152. // Find the internal value by its index or hash
  14153. let tx = undefined;
  14154. if (typeof (indexOrHash) === "number") {
  14155. tx = this.#transactions[indexOrHash];
  14156. }
  14157. else {
  14158. const hash = indexOrHash.toLowerCase();
  14159. for (const v of this.#transactions) {
  14160. if (typeof (v) === "string") {
  14161. if (v !== hash) {
  14162. continue;
  14163. }
  14164. tx = v;
  14165. break;
  14166. }
  14167. else {
  14168. if (v.hash !== hash) {
  14169. continue;
  14170. }
  14171. tx = v;
  14172. break;
  14173. }
  14174. }
  14175. }
  14176. if (tx == null) {
  14177. throw new Error("no such tx");
  14178. }
  14179. if (typeof (tx) === "string") {
  14180. return (await this.provider.getTransaction(tx));
  14181. }
  14182. else {
  14183. return tx;
  14184. }
  14185. }
  14186. /**
  14187. * If a **Block** was fetched with a request to include the transactions
  14188. * this will allow synchronous access to those transactions.
  14189. *
  14190. * If the transactions were not prefetched, this will throw.
  14191. */
  14192. getPrefetchedTransaction(indexOrHash) {
  14193. const txs = this.prefetchedTransactions;
  14194. if (typeof (indexOrHash) === "number") {
  14195. return txs[indexOrHash];
  14196. }
  14197. indexOrHash = indexOrHash.toLowerCase();
  14198. for (const tx of txs) {
  14199. if (tx.hash === indexOrHash) {
  14200. return tx;
  14201. }
  14202. }
  14203. assertArgument(false, "no matching transaction", "indexOrHash", indexOrHash);
  14204. }
  14205. /**
  14206. * Returns true if this block been mined. This provides a type guard
  14207. * for all properties on a [[MinedBlock]].
  14208. */
  14209. isMined() { return !!this.hash; }
  14210. /**
  14211. * Returns true if this block is an [[link-eip-2930]] block.
  14212. */
  14213. isLondon() {
  14214. return !!this.baseFeePerGas;
  14215. }
  14216. /**
  14217. * @_ignore:
  14218. */
  14219. orphanedEvent() {
  14220. if (!this.isMined()) {
  14221. throw new Error("");
  14222. }
  14223. return createOrphanedBlockFilter(this);
  14224. }
  14225. }
  14226. //////////////////////
  14227. // Log
  14228. /**
  14229. * A **Log** in Ethereum represents an event that has been included in a
  14230. * transaction using the ``LOG*`` opcodes, which are most commonly used by
  14231. * Solidity's emit for announcing events.
  14232. */
  14233. class Log {
  14234. /**
  14235. * The provider connected to the log used to fetch additional details
  14236. * if necessary.
  14237. */
  14238. provider;
  14239. /**
  14240. * The transaction hash of the transaction this log occurred in. Use the
  14241. * [[Log-getTransaction]] to get the [[TransactionResponse]].
  14242. */
  14243. transactionHash;
  14244. /**
  14245. * The block hash of the block this log occurred in. Use the
  14246. * [[Log-getBlock]] to get the [[Block]].
  14247. */
  14248. blockHash;
  14249. /**
  14250. * The block number of the block this log occurred in. It is preferred
  14251. * to use the [[Block-hash]] when fetching the related [[Block]],
  14252. * since in the case of an orphaned block, the block at that height may
  14253. * have changed.
  14254. */
  14255. blockNumber;
  14256. /**
  14257. * If the **Log** represents a block that was removed due to an orphaned
  14258. * block, this will be true.
  14259. *
  14260. * This can only happen within an orphan event listener.
  14261. */
  14262. removed;
  14263. /**
  14264. * The address of the contract that emitted this log.
  14265. */
  14266. address;
  14267. /**
  14268. * The data included in this log when it was emitted.
  14269. */
  14270. data;
  14271. /**
  14272. * The indexed topics included in this log when it was emitted.
  14273. *
  14274. * All topics are included in the bloom filters, so they can be
  14275. * efficiently filtered using the [[Provider-getLogs]] method.
  14276. */
  14277. topics;
  14278. /**
  14279. * The index within the block this log occurred at. This is generally
  14280. * not useful to developers, but can be used with the various roots
  14281. * to proof inclusion within a block.
  14282. */
  14283. index;
  14284. /**
  14285. * The index within the transaction of this log.
  14286. */
  14287. transactionIndex;
  14288. /**
  14289. * @_ignore:
  14290. */
  14291. constructor(log, provider) {
  14292. this.provider = provider;
  14293. const topics = Object.freeze(log.topics.slice());
  14294. defineProperties(this, {
  14295. transactionHash: log.transactionHash,
  14296. blockHash: log.blockHash,
  14297. blockNumber: log.blockNumber,
  14298. removed: log.removed,
  14299. address: log.address,
  14300. data: log.data,
  14301. topics,
  14302. index: log.index,
  14303. transactionIndex: log.transactionIndex,
  14304. });
  14305. }
  14306. /**
  14307. * Returns a JSON-compatible object.
  14308. */
  14309. toJSON() {
  14310. const { address, blockHash, blockNumber, data, index, removed, topics, transactionHash, transactionIndex } = this;
  14311. return {
  14312. _type: "log",
  14313. address, blockHash, blockNumber, data, index,
  14314. removed, topics, transactionHash, transactionIndex
  14315. };
  14316. }
  14317. /**
  14318. * Returns the block that this log occurred in.
  14319. */
  14320. async getBlock() {
  14321. const block = await this.provider.getBlock(this.blockHash);
  14322. assert(!!block, "failed to find transaction", "UNKNOWN_ERROR", {});
  14323. return block;
  14324. }
  14325. /**
  14326. * Returns the transaction that this log occurred in.
  14327. */
  14328. async getTransaction() {
  14329. const tx = await this.provider.getTransaction(this.transactionHash);
  14330. assert(!!tx, "failed to find transaction", "UNKNOWN_ERROR", {});
  14331. return tx;
  14332. }
  14333. /**
  14334. * Returns the transaction receipt fot the transaction that this
  14335. * log occurred in.
  14336. */
  14337. async getTransactionReceipt() {
  14338. const receipt = await this.provider.getTransactionReceipt(this.transactionHash);
  14339. assert(!!receipt, "failed to find transaction receipt", "UNKNOWN_ERROR", {});
  14340. return receipt;
  14341. }
  14342. /**
  14343. * @_ignore:
  14344. */
  14345. removedEvent() {
  14346. return createRemovedLogFilter(this);
  14347. }
  14348. }
  14349. //////////////////////
  14350. // Transaction Receipt
  14351. /*
  14352. export interface LegacyTransactionReceipt {
  14353. byzantium: false;
  14354. status: null;
  14355. root: string;
  14356. }
  14357. export interface ByzantiumTransactionReceipt {
  14358. byzantium: true;
  14359. status: number;
  14360. root: null;
  14361. }
  14362. */
  14363. /**
  14364. * A **TransactionReceipt** includes additional information about a
  14365. * transaction that is only available after it has been mined.
  14366. */
  14367. class TransactionReceipt {
  14368. /**
  14369. * The provider connected to the log used to fetch additional details
  14370. * if necessary.
  14371. */
  14372. provider;
  14373. /**
  14374. * The address the transaction was sent to.
  14375. */
  14376. to;
  14377. /**
  14378. * The sender of the transaction.
  14379. */
  14380. from;
  14381. /**
  14382. * The address of the contract if the transaction was directly
  14383. * responsible for deploying one.
  14384. *
  14385. * This is non-null **only** if the ``to`` is empty and the ``data``
  14386. * was successfully executed as initcode.
  14387. */
  14388. contractAddress;
  14389. /**
  14390. * The transaction hash.
  14391. */
  14392. hash;
  14393. /**
  14394. * The index of this transaction within the block transactions.
  14395. */
  14396. index;
  14397. /**
  14398. * The block hash of the [[Block]] this transaction was included in.
  14399. */
  14400. blockHash;
  14401. /**
  14402. * The block number of the [[Block]] this transaction was included in.
  14403. */
  14404. blockNumber;
  14405. /**
  14406. * The bloom filter bytes that represent all logs that occurred within
  14407. * this transaction. This is generally not useful for most developers,
  14408. * but can be used to validate the included logs.
  14409. */
  14410. logsBloom;
  14411. /**
  14412. * The actual amount of gas used by this transaction.
  14413. *
  14414. * When creating a transaction, the amount of gas that will be used can
  14415. * only be approximated, but the sender must pay the gas fee for the
  14416. * entire gas limit. After the transaction, the difference is refunded.
  14417. */
  14418. gasUsed;
  14419. /**
  14420. * The gas used for BLObs. See [[link-eip-4844]].
  14421. */
  14422. blobGasUsed;
  14423. /**
  14424. * The amount of gas used by all transactions within the block for this
  14425. * and all transactions with a lower ``index``.
  14426. *
  14427. * This is generally not useful for developers but can be used to
  14428. * validate certain aspects of execution.
  14429. */
  14430. cumulativeGasUsed;
  14431. /**
  14432. * The actual gas price used during execution.
  14433. *
  14434. * Due to the complexity of [[link-eip-1559]] this value can only
  14435. * be caluclated after the transaction has been mined, snce the base
  14436. * fee is protocol-enforced.
  14437. */
  14438. gasPrice;
  14439. /**
  14440. * The price paid per BLOB in gas. See [[link-eip-4844]].
  14441. */
  14442. blobGasPrice;
  14443. /**
  14444. * The [[link-eip-2718]] transaction type.
  14445. */
  14446. type;
  14447. //readonly byzantium!: boolean;
  14448. /**
  14449. * The status of this transaction, indicating success (i.e. ``1``) or
  14450. * a revert (i.e. ``0``).
  14451. *
  14452. * This is available in post-byzantium blocks, but some backends may
  14453. * backfill this value.
  14454. */
  14455. status;
  14456. /**
  14457. * The root hash of this transaction.
  14458. *
  14459. * This is no present and was only included in pre-byzantium blocks, but
  14460. * could be used to validate certain parts of the receipt.
  14461. */
  14462. root;
  14463. #logs;
  14464. /**
  14465. * @_ignore:
  14466. */
  14467. constructor(tx, provider) {
  14468. this.#logs = Object.freeze(tx.logs.map((log) => {
  14469. return new Log(log, provider);
  14470. }));
  14471. let gasPrice = BN_0$2;
  14472. if (tx.effectiveGasPrice != null) {
  14473. gasPrice = tx.effectiveGasPrice;
  14474. }
  14475. else if (tx.gasPrice != null) {
  14476. gasPrice = tx.gasPrice;
  14477. }
  14478. defineProperties(this, {
  14479. provider,
  14480. to: tx.to,
  14481. from: tx.from,
  14482. contractAddress: tx.contractAddress,
  14483. hash: tx.hash,
  14484. index: tx.index,
  14485. blockHash: tx.blockHash,
  14486. blockNumber: tx.blockNumber,
  14487. logsBloom: tx.logsBloom,
  14488. gasUsed: tx.gasUsed,
  14489. cumulativeGasUsed: tx.cumulativeGasUsed,
  14490. blobGasUsed: tx.blobGasUsed,
  14491. gasPrice,
  14492. blobGasPrice: tx.blobGasPrice,
  14493. type: tx.type,
  14494. //byzantium: tx.byzantium,
  14495. status: tx.status,
  14496. root: tx.root
  14497. });
  14498. }
  14499. /**
  14500. * The logs for this transaction.
  14501. */
  14502. get logs() { return this.#logs; }
  14503. /**
  14504. * Returns a JSON-compatible representation.
  14505. */
  14506. toJSON() {
  14507. const { to, from, contractAddress, hash, index, blockHash, blockNumber, logsBloom, logs, //byzantium,
  14508. status, root } = this;
  14509. return {
  14510. _type: "TransactionReceipt",
  14511. blockHash, blockNumber,
  14512. //byzantium,
  14513. contractAddress,
  14514. cumulativeGasUsed: toJson(this.cumulativeGasUsed),
  14515. from,
  14516. gasPrice: toJson(this.gasPrice),
  14517. blobGasUsed: toJson(this.blobGasUsed),
  14518. blobGasPrice: toJson(this.blobGasPrice),
  14519. gasUsed: toJson(this.gasUsed),
  14520. hash, index, logs, logsBloom, root, status, to
  14521. };
  14522. }
  14523. /**
  14524. * @_ignore:
  14525. */
  14526. get length() { return this.logs.length; }
  14527. [Symbol.iterator]() {
  14528. let index = 0;
  14529. return {
  14530. next: () => {
  14531. if (index < this.length) {
  14532. return { value: this.logs[index++], done: false };
  14533. }
  14534. return { value: undefined, done: true };
  14535. }
  14536. };
  14537. }
  14538. /**
  14539. * The total fee for this transaction, in wei.
  14540. */
  14541. get fee() {
  14542. return this.gasUsed * this.gasPrice;
  14543. }
  14544. /**
  14545. * Resolves to the block this transaction occurred in.
  14546. */
  14547. async getBlock() {
  14548. const block = await this.provider.getBlock(this.blockHash);
  14549. if (block == null) {
  14550. throw new Error("TODO");
  14551. }
  14552. return block;
  14553. }
  14554. /**
  14555. * Resolves to the transaction this transaction occurred in.
  14556. */
  14557. async getTransaction() {
  14558. const tx = await this.provider.getTransaction(this.hash);
  14559. if (tx == null) {
  14560. throw new Error("TODO");
  14561. }
  14562. return tx;
  14563. }
  14564. /**
  14565. * Resolves to the return value of the execution of this transaction.
  14566. *
  14567. * Support for this feature is limited, as it requires an archive node
  14568. * with the ``debug_`` or ``trace_`` API enabled.
  14569. */
  14570. async getResult() {
  14571. return (await this.provider.getTransactionResult(this.hash));
  14572. }
  14573. /**
  14574. * Resolves to the number of confirmations this transaction has.
  14575. */
  14576. async confirmations() {
  14577. return (await this.provider.getBlockNumber()) - this.blockNumber + 1;
  14578. }
  14579. /**
  14580. * @_ignore:
  14581. */
  14582. removedEvent() {
  14583. return createRemovedTransactionFilter(this);
  14584. }
  14585. /**
  14586. * @_ignore:
  14587. */
  14588. reorderedEvent(other) {
  14589. assert(!other || other.isMined(), "unmined 'other' transction cannot be orphaned", "UNSUPPORTED_OPERATION", { operation: "reorderedEvent(other)" });
  14590. return createReorderedTransactionFilter(this, other);
  14591. }
  14592. }
  14593. /**
  14594. * A **TransactionResponse** includes all properties about a transaction
  14595. * that was sent to the network, which may or may not be included in a
  14596. * block.
  14597. *
  14598. * The [[TransactionResponse-isMined]] can be used to check if the
  14599. * transaction has been mined as well as type guard that the otherwise
  14600. * possibly ``null`` properties are defined.
  14601. */
  14602. class TransactionResponse {
  14603. /**
  14604. * The provider this is connected to, which will influence how its
  14605. * methods will resolve its async inspection methods.
  14606. */
  14607. provider;
  14608. /**
  14609. * The block number of the block that this transaction was included in.
  14610. *
  14611. * This is ``null`` for pending transactions.
  14612. */
  14613. blockNumber;
  14614. /**
  14615. * The blockHash of the block that this transaction was included in.
  14616. *
  14617. * This is ``null`` for pending transactions.
  14618. */
  14619. blockHash;
  14620. /**
  14621. * The index within the block that this transaction resides at.
  14622. */
  14623. index;
  14624. /**
  14625. * The transaction hash.
  14626. */
  14627. hash;
  14628. /**
  14629. * The [[link-eip-2718]] transaction envelope type. This is
  14630. * ``0`` for legacy transactions types.
  14631. */
  14632. type;
  14633. /**
  14634. * The receiver of this transaction.
  14635. *
  14636. * If ``null``, then the transaction is an initcode transaction.
  14637. * This means the result of executing the [[data]] will be deployed
  14638. * as a new contract on chain (assuming it does not revert) and the
  14639. * address may be computed using [[getCreateAddress]].
  14640. */
  14641. to;
  14642. /**
  14643. * The sender of this transaction. It is implicitly computed
  14644. * from the transaction pre-image hash (as the digest) and the
  14645. * [[signature]] using ecrecover.
  14646. */
  14647. from;
  14648. /**
  14649. * The nonce, which is used to prevent replay attacks and offer
  14650. * a method to ensure transactions from a given sender are explicitly
  14651. * ordered.
  14652. *
  14653. * When sending a transaction, this must be equal to the number of
  14654. * transactions ever sent by [[from]].
  14655. */
  14656. nonce;
  14657. /**
  14658. * The maximum units of gas this transaction can consume. If execution
  14659. * exceeds this, the entries transaction is reverted and the sender
  14660. * is charged for the full amount, despite not state changes being made.
  14661. */
  14662. gasLimit;
  14663. /**
  14664. * The gas price can have various values, depending on the network.
  14665. *
  14666. * In modern networks, for transactions that are included this is
  14667. * the //effective gas price// (the fee per gas that was actually
  14668. * charged), while for transactions that have not been included yet
  14669. * is the [[maxFeePerGas]].
  14670. *
  14671. * For legacy transactions, or transactions on legacy networks, this
  14672. * is the fee that will be charged per unit of gas the transaction
  14673. * consumes.
  14674. */
  14675. gasPrice;
  14676. /**
  14677. * The maximum priority fee (per unit of gas) to allow a
  14678. * validator to charge the sender. This is inclusive of the
  14679. * [[maxFeeFeePerGas]].
  14680. */
  14681. maxPriorityFeePerGas;
  14682. /**
  14683. * The maximum fee (per unit of gas) to allow this transaction
  14684. * to charge the sender.
  14685. */
  14686. maxFeePerGas;
  14687. /**
  14688. * The [[link-eip-4844]] max fee per BLOb gas.
  14689. */
  14690. maxFeePerBlobGas;
  14691. /**
  14692. * The data.
  14693. */
  14694. data;
  14695. /**
  14696. * The value, in wei. Use [[formatEther]] to format this value
  14697. * as ether.
  14698. */
  14699. value;
  14700. /**
  14701. * The chain ID.
  14702. */
  14703. chainId;
  14704. /**
  14705. * The signature.
  14706. */
  14707. signature;
  14708. /**
  14709. * The [[link-eip-2930]] access list for transaction types that
  14710. * support it, otherwise ``null``.
  14711. */
  14712. accessList;
  14713. /**
  14714. * The [[link-eip-4844]] BLOb versioned hashes.
  14715. */
  14716. blobVersionedHashes;
  14717. #startBlock;
  14718. /**
  14719. * @_ignore:
  14720. */
  14721. constructor(tx, provider) {
  14722. this.provider = provider;
  14723. this.blockNumber = (tx.blockNumber != null) ? tx.blockNumber : null;
  14724. this.blockHash = (tx.blockHash != null) ? tx.blockHash : null;
  14725. this.hash = tx.hash;
  14726. this.index = tx.index;
  14727. this.type = tx.type;
  14728. this.from = tx.from;
  14729. this.to = tx.to || null;
  14730. this.gasLimit = tx.gasLimit;
  14731. this.nonce = tx.nonce;
  14732. this.data = tx.data;
  14733. this.value = tx.value;
  14734. this.gasPrice = tx.gasPrice;
  14735. this.maxPriorityFeePerGas = (tx.maxPriorityFeePerGas != null) ? tx.maxPriorityFeePerGas : null;
  14736. this.maxFeePerGas = (tx.maxFeePerGas != null) ? tx.maxFeePerGas : null;
  14737. this.maxFeePerBlobGas = (tx.maxFeePerBlobGas != null) ? tx.maxFeePerBlobGas : null;
  14738. this.chainId = tx.chainId;
  14739. this.signature = tx.signature;
  14740. this.accessList = (tx.accessList != null) ? tx.accessList : null;
  14741. this.blobVersionedHashes = (tx.blobVersionedHashes != null) ? tx.blobVersionedHashes : null;
  14742. this.#startBlock = -1;
  14743. }
  14744. /**
  14745. * Returns a JSON-compatible representation of this transaction.
  14746. */
  14747. toJSON() {
  14748. const { blockNumber, blockHash, index, hash, type, to, from, nonce, data, signature, accessList, blobVersionedHashes } = this;
  14749. return {
  14750. _type: "TransactionResponse",
  14751. accessList, blockNumber, blockHash,
  14752. blobVersionedHashes,
  14753. chainId: toJson(this.chainId),
  14754. data, from,
  14755. gasLimit: toJson(this.gasLimit),
  14756. gasPrice: toJson(this.gasPrice),
  14757. hash,
  14758. maxFeePerGas: toJson(this.maxFeePerGas),
  14759. maxPriorityFeePerGas: toJson(this.maxPriorityFeePerGas),
  14760. maxFeePerBlobGas: toJson(this.maxFeePerBlobGas),
  14761. nonce, signature, to, index, type,
  14762. value: toJson(this.value),
  14763. };
  14764. }
  14765. /**
  14766. * Resolves to the Block that this transaction was included in.
  14767. *
  14768. * This will return null if the transaction has not been included yet.
  14769. */
  14770. async getBlock() {
  14771. let blockNumber = this.blockNumber;
  14772. if (blockNumber == null) {
  14773. const tx = await this.getTransaction();
  14774. if (tx) {
  14775. blockNumber = tx.blockNumber;
  14776. }
  14777. }
  14778. if (blockNumber == null) {
  14779. return null;
  14780. }
  14781. const block = this.provider.getBlock(blockNumber);
  14782. if (block == null) {
  14783. throw new Error("TODO");
  14784. }
  14785. return block;
  14786. }
  14787. /**
  14788. * Resolves to this transaction being re-requested from the
  14789. * provider. This can be used if you have an unmined transaction
  14790. * and wish to get an up-to-date populated instance.
  14791. */
  14792. async getTransaction() {
  14793. return this.provider.getTransaction(this.hash);
  14794. }
  14795. /**
  14796. * Resolve to the number of confirmations this transaction has.
  14797. */
  14798. async confirmations() {
  14799. if (this.blockNumber == null) {
  14800. const { tx, blockNumber } = await resolveProperties({
  14801. tx: this.getTransaction(),
  14802. blockNumber: this.provider.getBlockNumber()
  14803. });
  14804. // Not mined yet...
  14805. if (tx == null || tx.blockNumber == null) {
  14806. return 0;
  14807. }
  14808. return blockNumber - tx.blockNumber + 1;
  14809. }
  14810. const blockNumber = await this.provider.getBlockNumber();
  14811. return blockNumber - this.blockNumber + 1;
  14812. }
  14813. /**
  14814. * Resolves once this transaction has been mined and has
  14815. * %%confirms%% blocks including it (default: ``1``) with an
  14816. * optional %%timeout%%.
  14817. *
  14818. * This can resolve to ``null`` only if %%confirms%% is ``0``
  14819. * and the transaction has not been mined, otherwise this will
  14820. * wait until enough confirmations have completed.
  14821. */
  14822. async wait(_confirms, _timeout) {
  14823. const confirms = (_confirms == null) ? 1 : _confirms;
  14824. const timeout = (_timeout == null) ? 0 : _timeout;
  14825. let startBlock = this.#startBlock;
  14826. let nextScan = -1;
  14827. let stopScanning = (startBlock === -1) ? true : false;
  14828. const checkReplacement = async () => {
  14829. // Get the current transaction count for this sender
  14830. if (stopScanning) {
  14831. return null;
  14832. }
  14833. const { blockNumber, nonce } = await resolveProperties({
  14834. blockNumber: this.provider.getBlockNumber(),
  14835. nonce: this.provider.getTransactionCount(this.from)
  14836. });
  14837. // No transaction or our nonce has not been mined yet; but we
  14838. // can start scanning later when we do start
  14839. if (nonce < this.nonce) {
  14840. startBlock = blockNumber;
  14841. return;
  14842. }
  14843. // We were mined; no replacement
  14844. if (stopScanning) {
  14845. return null;
  14846. }
  14847. const mined = await this.getTransaction();
  14848. if (mined && mined.blockNumber != null) {
  14849. return;
  14850. }
  14851. // We were replaced; start scanning for that transaction
  14852. // Starting to scan; look back a few extra blocks for safety
  14853. if (nextScan === -1) {
  14854. nextScan = startBlock - 3;
  14855. if (nextScan < this.#startBlock) {
  14856. nextScan = this.#startBlock;
  14857. }
  14858. }
  14859. while (nextScan <= blockNumber) {
  14860. // Get the next block to scan
  14861. if (stopScanning) {
  14862. return null;
  14863. }
  14864. const block = await this.provider.getBlock(nextScan, true);
  14865. // This should not happen; but we'll try again shortly
  14866. if (block == null) {
  14867. return;
  14868. }
  14869. // We were mined; no replacement
  14870. for (const hash of block) {
  14871. if (hash === this.hash) {
  14872. return;
  14873. }
  14874. }
  14875. // Search for the transaction that replaced us
  14876. for (let i = 0; i < block.length; i++) {
  14877. const tx = await block.getTransaction(i);
  14878. if (tx.from === this.from && tx.nonce === this.nonce) {
  14879. // Get the receipt
  14880. if (stopScanning) {
  14881. return null;
  14882. }
  14883. const receipt = await this.provider.getTransactionReceipt(tx.hash);
  14884. // This should not happen; but we'll try again shortly
  14885. if (receipt == null) {
  14886. return;
  14887. }
  14888. // We will retry this on the next block (this case could be optimized)
  14889. if ((blockNumber - receipt.blockNumber + 1) < confirms) {
  14890. return;
  14891. }
  14892. // The reason we were replaced
  14893. let reason = "replaced";
  14894. if (tx.data === this.data && tx.to === this.to && tx.value === this.value) {
  14895. reason = "repriced";
  14896. }
  14897. else if (tx.data === "0x" && tx.from === tx.to && tx.value === BN_0$2) {
  14898. reason = "cancelled";
  14899. }
  14900. assert(false, "transaction was replaced", "TRANSACTION_REPLACED", {
  14901. cancelled: (reason === "replaced" || reason === "cancelled"),
  14902. reason,
  14903. replacement: tx.replaceableTransaction(startBlock),
  14904. hash: tx.hash,
  14905. receipt
  14906. });
  14907. }
  14908. }
  14909. nextScan++;
  14910. }
  14911. return;
  14912. };
  14913. const checkReceipt = (receipt) => {
  14914. if (receipt == null || receipt.status !== 0) {
  14915. return receipt;
  14916. }
  14917. assert(false, "transaction execution reverted", "CALL_EXCEPTION", {
  14918. action: "sendTransaction",
  14919. data: null, reason: null, invocation: null, revert: null,
  14920. transaction: {
  14921. to: receipt.to,
  14922. from: receipt.from,
  14923. data: "" // @TODO: in v7, split out sendTransaction properties
  14924. }, receipt
  14925. });
  14926. };
  14927. const receipt = await this.provider.getTransactionReceipt(this.hash);
  14928. if (confirms === 0) {
  14929. return checkReceipt(receipt);
  14930. }
  14931. if (receipt) {
  14932. if ((await receipt.confirmations()) >= confirms) {
  14933. return checkReceipt(receipt);
  14934. }
  14935. }
  14936. else {
  14937. // Check for a replacement; throws if a replacement was found
  14938. await checkReplacement();
  14939. // Allow null only when the confirms is 0
  14940. if (confirms === 0) {
  14941. return null;
  14942. }
  14943. }
  14944. const waiter = new Promise((resolve, reject) => {
  14945. // List of things to cancel when we have a result (one way or the other)
  14946. const cancellers = [];
  14947. const cancel = () => { cancellers.forEach((c) => c()); };
  14948. // On cancel, stop scanning for replacements
  14949. cancellers.push(() => { stopScanning = true; });
  14950. // Set up any timeout requested
  14951. if (timeout > 0) {
  14952. const timer = setTimeout(() => {
  14953. cancel();
  14954. reject(makeError("wait for transaction timeout", "TIMEOUT"));
  14955. }, timeout);
  14956. cancellers.push(() => { clearTimeout(timer); });
  14957. }
  14958. const txListener = async (receipt) => {
  14959. // Done; return it!
  14960. if ((await receipt.confirmations()) >= confirms) {
  14961. cancel();
  14962. try {
  14963. resolve(checkReceipt(receipt));
  14964. }
  14965. catch (error) {
  14966. reject(error);
  14967. }
  14968. }
  14969. };
  14970. cancellers.push(() => { this.provider.off(this.hash, txListener); });
  14971. this.provider.on(this.hash, txListener);
  14972. // We support replacement detection; start checking
  14973. if (startBlock >= 0) {
  14974. const replaceListener = async () => {
  14975. try {
  14976. // Check for a replacement; this throws only if one is found
  14977. await checkReplacement();
  14978. }
  14979. catch (error) {
  14980. // We were replaced (with enough confirms); re-throw the error
  14981. if (isError(error, "TRANSACTION_REPLACED")) {
  14982. cancel();
  14983. reject(error);
  14984. return;
  14985. }
  14986. }
  14987. // Rescheudle a check on the next block
  14988. if (!stopScanning) {
  14989. this.provider.once("block", replaceListener);
  14990. }
  14991. };
  14992. cancellers.push(() => { this.provider.off("block", replaceListener); });
  14993. this.provider.once("block", replaceListener);
  14994. }
  14995. });
  14996. return await waiter;
  14997. }
  14998. /**
  14999. * Returns ``true`` if this transaction has been included.
  15000. *
  15001. * This is effective only as of the time the TransactionResponse
  15002. * was instantiated. To get up-to-date information, use
  15003. * [[getTransaction]].
  15004. *
  15005. * This provides a Type Guard that this transaction will have
  15006. * non-null property values for properties that are null for
  15007. * unmined transactions.
  15008. */
  15009. isMined() {
  15010. return (this.blockHash != null);
  15011. }
  15012. /**
  15013. * Returns true if the transaction is a legacy (i.e. ``type == 0``)
  15014. * transaction.
  15015. *
  15016. * This provides a Type Guard that this transaction will have
  15017. * the ``null``-ness for hardfork-specific properties set correctly.
  15018. */
  15019. isLegacy() {
  15020. return (this.type === 0);
  15021. }
  15022. /**
  15023. * Returns true if the transaction is a Berlin (i.e. ``type == 1``)
  15024. * transaction. See [[link-eip-2070]].
  15025. *
  15026. * This provides a Type Guard that this transaction will have
  15027. * the ``null``-ness for hardfork-specific properties set correctly.
  15028. */
  15029. isBerlin() {
  15030. return (this.type === 1);
  15031. }
  15032. /**
  15033. * Returns true if the transaction is a London (i.e. ``type == 2``)
  15034. * transaction. See [[link-eip-1559]].
  15035. *
  15036. * This provides a Type Guard that this transaction will have
  15037. * the ``null``-ness for hardfork-specific properties set correctly.
  15038. */
  15039. isLondon() {
  15040. return (this.type === 2);
  15041. }
  15042. /**
  15043. * Returns true if hte transaction is a Cancun (i.e. ``type == 3``)
  15044. * transaction. See [[link-eip-4844]].
  15045. */
  15046. isCancun() {
  15047. return (this.type === 3);
  15048. }
  15049. /**
  15050. * Returns a filter which can be used to listen for orphan events
  15051. * that evict this transaction.
  15052. */
  15053. removedEvent() {
  15054. assert(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" });
  15055. return createRemovedTransactionFilter(this);
  15056. }
  15057. /**
  15058. * Returns a filter which can be used to listen for orphan events
  15059. * that re-order this event against %%other%%.
  15060. */
  15061. reorderedEvent(other) {
  15062. assert(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" });
  15063. assert(!other || other.isMined(), "unmined 'other' transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" });
  15064. return createReorderedTransactionFilter(this, other);
  15065. }
  15066. /**
  15067. * Returns a new TransactionResponse instance which has the ability to
  15068. * detect (and throw an error) if the transaction is replaced, which
  15069. * will begin scanning at %%startBlock%%.
  15070. *
  15071. * This should generally not be used by developers and is intended
  15072. * primarily for internal use. Setting an incorrect %%startBlock%% can
  15073. * have devastating performance consequences if used incorrectly.
  15074. */
  15075. replaceableTransaction(startBlock) {
  15076. assertArgument(Number.isInteger(startBlock) && startBlock >= 0, "invalid startBlock", "startBlock", startBlock);
  15077. const tx = new TransactionResponse(this, this.provider);
  15078. tx.#startBlock = startBlock;
  15079. return tx;
  15080. }
  15081. }
  15082. function createOrphanedBlockFilter(block) {
  15083. return { orphan: "drop-block", hash: block.hash, number: block.number };
  15084. }
  15085. function createReorderedTransactionFilter(tx, other) {
  15086. return { orphan: "reorder-transaction", tx, other };
  15087. }
  15088. function createRemovedTransactionFilter(tx) {
  15089. return { orphan: "drop-transaction", tx };
  15090. }
  15091. function createRemovedLogFilter(log) {
  15092. return { orphan: "drop-log", log: {
  15093. transactionHash: log.transactionHash,
  15094. blockHash: log.blockHash,
  15095. blockNumber: log.blockNumber,
  15096. address: log.address,
  15097. data: log.data,
  15098. topics: Object.freeze(log.topics.slice()),
  15099. index: log.index
  15100. } };
  15101. }
  15102. // import from provider.ts instead of index.ts to prevent circular dep
  15103. // from EtherscanProvider
  15104. /**
  15105. * An **EventLog** contains additional properties parsed from the [[Log]].
  15106. */
  15107. class EventLog extends Log {
  15108. /**
  15109. * The Contract Interface.
  15110. */
  15111. interface;
  15112. /**
  15113. * The matching event.
  15114. */
  15115. fragment;
  15116. /**
  15117. * The parsed arguments passed to the event by ``emit``.
  15118. */
  15119. args;
  15120. /**
  15121. * @_ignore:
  15122. */
  15123. constructor(log, iface, fragment) {
  15124. super(log, log.provider);
  15125. const args = iface.decodeEventLog(fragment, log.data, log.topics);
  15126. defineProperties(this, { args, fragment, interface: iface });
  15127. }
  15128. /**
  15129. * The name of the event.
  15130. */
  15131. get eventName() { return this.fragment.name; }
  15132. /**
  15133. * The signature of the event.
  15134. */
  15135. get eventSignature() { return this.fragment.format(); }
  15136. }
  15137. /**
  15138. * An **EventLog** contains additional properties parsed from the [[Log]].
  15139. */
  15140. class UndecodedEventLog extends Log {
  15141. /**
  15142. * The error encounted when trying to decode the log.
  15143. */
  15144. error;
  15145. /**
  15146. * @_ignore:
  15147. */
  15148. constructor(log, error) {
  15149. super(log, log.provider);
  15150. defineProperties(this, { error });
  15151. }
  15152. }
  15153. /**
  15154. * A **ContractTransactionReceipt** includes the parsed logs from a
  15155. * [[TransactionReceipt]].
  15156. */
  15157. class ContractTransactionReceipt extends TransactionReceipt {
  15158. #iface;
  15159. /**
  15160. * @_ignore:
  15161. */
  15162. constructor(iface, provider, tx) {
  15163. super(tx, provider);
  15164. this.#iface = iface;
  15165. }
  15166. /**
  15167. * The parsed logs for any [[Log]] which has a matching event in the
  15168. * Contract ABI.
  15169. */
  15170. get logs() {
  15171. return super.logs.map((log) => {
  15172. const fragment = log.topics.length ? this.#iface.getEvent(log.topics[0]) : null;
  15173. if (fragment) {
  15174. try {
  15175. return new EventLog(log, this.#iface, fragment);
  15176. }
  15177. catch (error) {
  15178. return new UndecodedEventLog(log, error);
  15179. }
  15180. }
  15181. return log;
  15182. });
  15183. }
  15184. }
  15185. /**
  15186. * A **ContractTransactionResponse** will return a
  15187. * [[ContractTransactionReceipt]] when waited on.
  15188. */
  15189. class ContractTransactionResponse extends TransactionResponse {
  15190. #iface;
  15191. /**
  15192. * @_ignore:
  15193. */
  15194. constructor(iface, provider, tx) {
  15195. super(tx, provider);
  15196. this.#iface = iface;
  15197. }
  15198. /**
  15199. * Resolves once this transaction has been mined and has
  15200. * %%confirms%% blocks including it (default: ``1``) with an
  15201. * optional %%timeout%%.
  15202. *
  15203. * This can resolve to ``null`` only if %%confirms%% is ``0``
  15204. * and the transaction has not been mined, otherwise this will
  15205. * wait until enough confirmations have completed.
  15206. */
  15207. async wait(confirms, timeout) {
  15208. const receipt = await super.wait(confirms, timeout);
  15209. if (receipt == null) {
  15210. return null;
  15211. }
  15212. return new ContractTransactionReceipt(this.#iface, this.provider, receipt);
  15213. }
  15214. }
  15215. /**
  15216. * A **ContractUnknownEventPayload** is included as the last parameter to
  15217. * Contract Events when the event does not match any events in the ABI.
  15218. */
  15219. class ContractUnknownEventPayload extends EventPayload {
  15220. /**
  15221. * The log with no matching events.
  15222. */
  15223. log;
  15224. /**
  15225. * @_event:
  15226. */
  15227. constructor(contract, listener, filter, log) {
  15228. super(contract, listener, filter);
  15229. defineProperties(this, { log });
  15230. }
  15231. /**
  15232. * Resolves to the block the event occured in.
  15233. */
  15234. async getBlock() {
  15235. return await this.log.getBlock();
  15236. }
  15237. /**
  15238. * Resolves to the transaction the event occured in.
  15239. */
  15240. async getTransaction() {
  15241. return await this.log.getTransaction();
  15242. }
  15243. /**
  15244. * Resolves to the transaction receipt the event occured in.
  15245. */
  15246. async getTransactionReceipt() {
  15247. return await this.log.getTransactionReceipt();
  15248. }
  15249. }
  15250. /**
  15251. * A **ContractEventPayload** is included as the last parameter to
  15252. * Contract Events when the event is known.
  15253. */
  15254. class ContractEventPayload extends ContractUnknownEventPayload {
  15255. /**
  15256. * @_ignore:
  15257. */
  15258. constructor(contract, listener, filter, fragment, _log) {
  15259. super(contract, listener, filter, new EventLog(_log, contract.interface, fragment));
  15260. const args = contract.interface.decodeEventLog(fragment, this.log.data, this.log.topics);
  15261. defineProperties(this, { args, fragment });
  15262. }
  15263. /**
  15264. * The event name.
  15265. */
  15266. get eventName() {
  15267. return this.fragment.name;
  15268. }
  15269. /**
  15270. * The event signature.
  15271. */
  15272. get eventSignature() {
  15273. return this.fragment.format();
  15274. }
  15275. }
  15276. const BN_0$1 = BigInt(0);
  15277. function canCall(value) {
  15278. return (value && typeof (value.call) === "function");
  15279. }
  15280. function canEstimate(value) {
  15281. return (value && typeof (value.estimateGas) === "function");
  15282. }
  15283. function canResolve(value) {
  15284. return (value && typeof (value.resolveName) === "function");
  15285. }
  15286. function canSend(value) {
  15287. return (value && typeof (value.sendTransaction) === "function");
  15288. }
  15289. function getResolver(value) {
  15290. if (value != null) {
  15291. if (canResolve(value)) {
  15292. return value;
  15293. }
  15294. if (value.provider) {
  15295. return value.provider;
  15296. }
  15297. }
  15298. return undefined;
  15299. }
  15300. class PreparedTopicFilter {
  15301. #filter;
  15302. fragment;
  15303. constructor(contract, fragment, args) {
  15304. defineProperties(this, { fragment });
  15305. if (fragment.inputs.length < args.length) {
  15306. throw new Error("too many arguments");
  15307. }
  15308. // Recursively descend into args and resolve any addresses
  15309. const runner = getRunner(contract.runner, "resolveName");
  15310. const resolver = canResolve(runner) ? runner : null;
  15311. this.#filter = (async function () {
  15312. const resolvedArgs = await Promise.all(fragment.inputs.map((param, index) => {
  15313. const arg = args[index];
  15314. if (arg == null) {
  15315. return null;
  15316. }
  15317. return param.walkAsync(args[index], (type, value) => {
  15318. if (type === "address") {
  15319. if (Array.isArray(value)) {
  15320. return Promise.all(value.map((v) => resolveAddress(v, resolver)));
  15321. }
  15322. return resolveAddress(value, resolver);
  15323. }
  15324. return value;
  15325. });
  15326. }));
  15327. return contract.interface.encodeFilterTopics(fragment, resolvedArgs);
  15328. })();
  15329. }
  15330. getTopicFilter() {
  15331. return this.#filter;
  15332. }
  15333. }
  15334. // A = Arguments passed in as a tuple
  15335. // R = The result type of the call (i.e. if only one return type,
  15336. // the qualified type, otherwise Result)
  15337. // D = The type the default call will return (i.e. R for view/pure,
  15338. // TransactionResponse otherwise)
  15339. //export interface ContractMethod<A extends Array<any> = Array<any>, R = any, D extends R | ContractTransactionResponse = ContractTransactionResponse> {
  15340. function getRunner(value, feature) {
  15341. if (value == null) {
  15342. return null;
  15343. }
  15344. if (typeof (value[feature]) === "function") {
  15345. return value;
  15346. }
  15347. if (value.provider && typeof (value.provider[feature]) === "function") {
  15348. return value.provider;
  15349. }
  15350. return null;
  15351. }
  15352. function getProvider(value) {
  15353. if (value == null) {
  15354. return null;
  15355. }
  15356. return value.provider || null;
  15357. }
  15358. /**
  15359. * @_ignore:
  15360. */
  15361. async function copyOverrides(arg, allowed) {
  15362. // Make sure the overrides passed in are a valid overrides object
  15363. const _overrides = Typed.dereference(arg, "overrides");
  15364. assertArgument(typeof (_overrides) === "object", "invalid overrides parameter", "overrides", arg);
  15365. // Create a shallow copy (we'll deep-ify anything needed during normalizing)
  15366. const overrides = copyRequest(_overrides);
  15367. assertArgument(overrides.to == null || (allowed || []).indexOf("to") >= 0, "cannot override to", "overrides.to", overrides.to);
  15368. assertArgument(overrides.data == null || (allowed || []).indexOf("data") >= 0, "cannot override data", "overrides.data", overrides.data);
  15369. // Resolve any from
  15370. if (overrides.from) {
  15371. overrides.from = overrides.from;
  15372. }
  15373. return overrides;
  15374. }
  15375. /**
  15376. * @_ignore:
  15377. */
  15378. async function resolveArgs(_runner, inputs, args) {
  15379. // Recursively descend into args and resolve any addresses
  15380. const runner = getRunner(_runner, "resolveName");
  15381. const resolver = canResolve(runner) ? runner : null;
  15382. return await Promise.all(inputs.map((param, index) => {
  15383. return param.walkAsync(args[index], (type, value) => {
  15384. value = Typed.dereference(value, type);
  15385. if (type === "address") {
  15386. return resolveAddress(value, resolver);
  15387. }
  15388. return value;
  15389. });
  15390. }));
  15391. }
  15392. function buildWrappedFallback(contract) {
  15393. const populateTransaction = async function (overrides) {
  15394. // If an overrides was passed in, copy it and normalize the values
  15395. const tx = (await copyOverrides(overrides, ["data"]));
  15396. tx.to = await contract.getAddress();
  15397. if (tx.from) {
  15398. tx.from = await resolveAddress(tx.from, getResolver(contract.runner));
  15399. }
  15400. const iface = contract.interface;
  15401. const noValue = (getBigInt((tx.value || BN_0$1), "overrides.value") === BN_0$1);
  15402. const noData = ((tx.data || "0x") === "0x");
  15403. if (iface.fallback && !iface.fallback.payable && iface.receive && !noData && !noValue) {
  15404. assertArgument(false, "cannot send data to receive or send value to non-payable fallback", "overrides", overrides);
  15405. }
  15406. assertArgument(iface.fallback || noData, "cannot send data to receive-only contract", "overrides.data", tx.data);
  15407. // Only allow payable contracts to set non-zero value
  15408. const payable = iface.receive || (iface.fallback && iface.fallback.payable);
  15409. assertArgument(payable || noValue, "cannot send value to non-payable fallback", "overrides.value", tx.value);
  15410. // Only allow fallback contracts to set non-empty data
  15411. assertArgument(iface.fallback || noData, "cannot send data to receive-only contract", "overrides.data", tx.data);
  15412. return tx;
  15413. };
  15414. const staticCall = async function (overrides) {
  15415. const runner = getRunner(contract.runner, "call");
  15416. assert(canCall(runner), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { operation: "call" });
  15417. const tx = await populateTransaction(overrides);
  15418. try {
  15419. return await runner.call(tx);
  15420. }
  15421. catch (error) {
  15422. if (isCallException(error) && error.data) {
  15423. throw contract.interface.makeError(error.data, tx);
  15424. }
  15425. throw error;
  15426. }
  15427. };
  15428. const send = async function (overrides) {
  15429. const runner = contract.runner;
  15430. assert(canSend(runner), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { operation: "sendTransaction" });
  15431. const tx = await runner.sendTransaction(await populateTransaction(overrides));
  15432. const provider = getProvider(contract.runner);
  15433. // @TODO: the provider can be null; make a custom dummy provider that will throw a
  15434. // meaningful error
  15435. return new ContractTransactionResponse(contract.interface, provider, tx);
  15436. };
  15437. const estimateGas = async function (overrides) {
  15438. const runner = getRunner(contract.runner, "estimateGas");
  15439. assert(canEstimate(runner), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { operation: "estimateGas" });
  15440. return await runner.estimateGas(await populateTransaction(overrides));
  15441. };
  15442. const method = async (overrides) => {
  15443. return await send(overrides);
  15444. };
  15445. defineProperties(method, {
  15446. _contract: contract,
  15447. estimateGas,
  15448. populateTransaction,
  15449. send, staticCall
  15450. });
  15451. return method;
  15452. }
  15453. function buildWrappedMethod(contract, key) {
  15454. const getFragment = function (...args) {
  15455. const fragment = contract.interface.getFunction(key, args);
  15456. assert(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", {
  15457. operation: "fragment",
  15458. info: { key, args }
  15459. });
  15460. return fragment;
  15461. };
  15462. const populateTransaction = async function (...args) {
  15463. const fragment = getFragment(...args);
  15464. // If an overrides was passed in, copy it and normalize the values
  15465. let overrides = {};
  15466. if (fragment.inputs.length + 1 === args.length) {
  15467. overrides = await copyOverrides(args.pop());
  15468. if (overrides.from) {
  15469. overrides.from = await resolveAddress(overrides.from, getResolver(contract.runner));
  15470. }
  15471. }
  15472. if (fragment.inputs.length !== args.length) {
  15473. throw new Error("internal error: fragment inputs doesn't match arguments; should not happen");
  15474. }
  15475. const resolvedArgs = await resolveArgs(contract.runner, fragment.inputs, args);
  15476. return Object.assign({}, overrides, await resolveProperties({
  15477. to: contract.getAddress(),
  15478. data: contract.interface.encodeFunctionData(fragment, resolvedArgs)
  15479. }));
  15480. };
  15481. const staticCall = async function (...args) {
  15482. const result = await staticCallResult(...args);
  15483. if (result.length === 1) {
  15484. return result[0];
  15485. }
  15486. return result;
  15487. };
  15488. const send = async function (...args) {
  15489. const runner = contract.runner;
  15490. assert(canSend(runner), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { operation: "sendTransaction" });
  15491. const tx = await runner.sendTransaction(await populateTransaction(...args));
  15492. const provider = getProvider(contract.runner);
  15493. // @TODO: the provider can be null; make a custom dummy provider that will throw a
  15494. // meaningful error
  15495. return new ContractTransactionResponse(contract.interface, provider, tx);
  15496. };
  15497. const estimateGas = async function (...args) {
  15498. const runner = getRunner(contract.runner, "estimateGas");
  15499. assert(canEstimate(runner), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { operation: "estimateGas" });
  15500. return await runner.estimateGas(await populateTransaction(...args));
  15501. };
  15502. const staticCallResult = async function (...args) {
  15503. const runner = getRunner(contract.runner, "call");
  15504. assert(canCall(runner), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { operation: "call" });
  15505. const tx = await populateTransaction(...args);
  15506. let result = "0x";
  15507. try {
  15508. result = await runner.call(tx);
  15509. }
  15510. catch (error) {
  15511. if (isCallException(error) && error.data) {
  15512. throw contract.interface.makeError(error.data, tx);
  15513. }
  15514. throw error;
  15515. }
  15516. const fragment = getFragment(...args);
  15517. return contract.interface.decodeFunctionResult(fragment, result);
  15518. };
  15519. const method = async (...args) => {
  15520. const fragment = getFragment(...args);
  15521. if (fragment.constant) {
  15522. return await staticCall(...args);
  15523. }
  15524. return await send(...args);
  15525. };
  15526. defineProperties(method, {
  15527. name: contract.interface.getFunctionName(key),
  15528. _contract: contract, _key: key,
  15529. getFragment,
  15530. estimateGas,
  15531. populateTransaction,
  15532. send, staticCall, staticCallResult,
  15533. });
  15534. // Only works on non-ambiguous keys (refined fragment is always non-ambiguous)
  15535. Object.defineProperty(method, "fragment", {
  15536. configurable: false,
  15537. enumerable: true,
  15538. get: () => {
  15539. const fragment = contract.interface.getFunction(key);
  15540. assert(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", {
  15541. operation: "fragment",
  15542. info: { key }
  15543. });
  15544. return fragment;
  15545. }
  15546. });
  15547. return method;
  15548. }
  15549. function buildWrappedEvent(contract, key) {
  15550. const getFragment = function (...args) {
  15551. const fragment = contract.interface.getEvent(key, args);
  15552. assert(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", {
  15553. operation: "fragment",
  15554. info: { key, args }
  15555. });
  15556. return fragment;
  15557. };
  15558. const method = function (...args) {
  15559. return new PreparedTopicFilter(contract, getFragment(...args), args);
  15560. };
  15561. defineProperties(method, {
  15562. name: contract.interface.getEventName(key),
  15563. _contract: contract, _key: key,
  15564. getFragment
  15565. });
  15566. // Only works on non-ambiguous keys (refined fragment is always non-ambiguous)
  15567. Object.defineProperty(method, "fragment", {
  15568. configurable: false,
  15569. enumerable: true,
  15570. get: () => {
  15571. const fragment = contract.interface.getEvent(key);
  15572. assert(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", {
  15573. operation: "fragment",
  15574. info: { key }
  15575. });
  15576. return fragment;
  15577. }
  15578. });
  15579. return method;
  15580. }
  15581. // The combination of TypeScrype, Private Fields and Proxies makes
  15582. // the world go boom; so we hide variables with some trickery keeping
  15583. // a symbol attached to each BaseContract which its sub-class (even
  15584. // via a Proxy) can reach and use to look up its internal values.
  15585. const internal = Symbol.for("_ethersInternal_contract");
  15586. const internalValues = new WeakMap();
  15587. function setInternal(contract, values) {
  15588. internalValues.set(contract[internal], values);
  15589. }
  15590. function getInternal(contract) {
  15591. return internalValues.get(contract[internal]);
  15592. }
  15593. function isDeferred(value) {
  15594. return (value && typeof (value) === "object" && ("getTopicFilter" in value) &&
  15595. (typeof (value.getTopicFilter) === "function") && value.fragment);
  15596. }
  15597. async function getSubInfo(contract, event) {
  15598. let topics;
  15599. let fragment = null;
  15600. // Convert named events to topicHash and get the fragment for
  15601. // events which need deconstructing.
  15602. if (Array.isArray(event)) {
  15603. const topicHashify = function (name) {
  15604. if (isHexString(name, 32)) {
  15605. return name;
  15606. }
  15607. const fragment = contract.interface.getEvent(name);
  15608. assertArgument(fragment, "unknown fragment", "name", name);
  15609. return fragment.topicHash;
  15610. };
  15611. // Array of Topics and Names; e.g. `[ "0x1234...89ab", "Transfer(address)" ]`
  15612. topics = event.map((e) => {
  15613. if (e == null) {
  15614. return null;
  15615. }
  15616. if (Array.isArray(e)) {
  15617. return e.map(topicHashify);
  15618. }
  15619. return topicHashify(e);
  15620. });
  15621. }
  15622. else if (event === "*") {
  15623. topics = [null];
  15624. }
  15625. else if (typeof (event) === "string") {
  15626. if (isHexString(event, 32)) {
  15627. // Topic Hash
  15628. topics = [event];
  15629. }
  15630. else {
  15631. // Name or Signature; e.g. `"Transfer", `"Transfer(address)"`
  15632. fragment = contract.interface.getEvent(event);
  15633. assertArgument(fragment, "unknown fragment", "event", event);
  15634. topics = [fragment.topicHash];
  15635. }
  15636. }
  15637. else if (isDeferred(event)) {
  15638. // Deferred Topic Filter; e.g. `contract.filter.Transfer(from)`
  15639. topics = await event.getTopicFilter();
  15640. }
  15641. else if ("fragment" in event) {
  15642. // ContractEvent; e.g. `contract.filter.Transfer`
  15643. fragment = event.fragment;
  15644. topics = [fragment.topicHash];
  15645. }
  15646. else {
  15647. assertArgument(false, "unknown event name", "event", event);
  15648. }
  15649. // Normalize topics and sort TopicSets
  15650. topics = topics.map((t) => {
  15651. if (t == null) {
  15652. return null;
  15653. }
  15654. if (Array.isArray(t)) {
  15655. const items = Array.from(new Set(t.map((t) => t.toLowerCase())).values());
  15656. if (items.length === 1) {
  15657. return items[0];
  15658. }
  15659. items.sort();
  15660. return items;
  15661. }
  15662. return t.toLowerCase();
  15663. });
  15664. const tag = topics.map((t) => {
  15665. if (t == null) {
  15666. return "null";
  15667. }
  15668. if (Array.isArray(t)) {
  15669. return t.join("|");
  15670. }
  15671. return t;
  15672. }).join("&");
  15673. return { fragment, tag, topics };
  15674. }
  15675. async function hasSub(contract, event) {
  15676. const { subs } = getInternal(contract);
  15677. return subs.get((await getSubInfo(contract, event)).tag) || null;
  15678. }
  15679. async function getSub(contract, operation, event) {
  15680. // Make sure our runner can actually subscribe to events
  15681. const provider = getProvider(contract.runner);
  15682. assert(provider, "contract runner does not support subscribing", "UNSUPPORTED_OPERATION", { operation });
  15683. const { fragment, tag, topics } = await getSubInfo(contract, event);
  15684. const { addr, subs } = getInternal(contract);
  15685. let sub = subs.get(tag);
  15686. if (!sub) {
  15687. const address = (addr ? addr : contract);
  15688. const filter = { address, topics };
  15689. const listener = (log) => {
  15690. let foundFragment = fragment;
  15691. if (foundFragment == null) {
  15692. try {
  15693. foundFragment = contract.interface.getEvent(log.topics[0]);
  15694. }
  15695. catch (error) { }
  15696. }
  15697. // If fragment is null, we do not deconstruct the args to emit
  15698. if (foundFragment) {
  15699. const _foundFragment = foundFragment;
  15700. const args = fragment ? contract.interface.decodeEventLog(fragment, log.data, log.topics) : [];
  15701. emit(contract, event, args, (listener) => {
  15702. return new ContractEventPayload(contract, listener, event, _foundFragment, log);
  15703. });
  15704. }
  15705. else {
  15706. emit(contract, event, [], (listener) => {
  15707. return new ContractUnknownEventPayload(contract, listener, event, log);
  15708. });
  15709. }
  15710. };
  15711. let starting = [];
  15712. const start = () => {
  15713. if (starting.length) {
  15714. return;
  15715. }
  15716. starting.push(provider.on(filter, listener));
  15717. };
  15718. const stop = async () => {
  15719. if (starting.length == 0) {
  15720. return;
  15721. }
  15722. let started = starting;
  15723. starting = [];
  15724. await Promise.all(started);
  15725. provider.off(filter, listener);
  15726. };
  15727. sub = { tag, listeners: [], start, stop };
  15728. subs.set(tag, sub);
  15729. }
  15730. return sub;
  15731. }
  15732. // We use this to ensure one emit resolves before firing the next to
  15733. // ensure correct ordering (note this cannot throw and just adds the
  15734. // notice to the event queu using setTimeout).
  15735. let lastEmit = Promise.resolve();
  15736. async function _emit(contract, event, args, payloadFunc) {
  15737. await lastEmit;
  15738. const sub = await hasSub(contract, event);
  15739. if (!sub) {
  15740. return false;
  15741. }
  15742. const count = sub.listeners.length;
  15743. sub.listeners = sub.listeners.filter(({ listener, once }) => {
  15744. const passArgs = Array.from(args);
  15745. if (payloadFunc) {
  15746. passArgs.push(payloadFunc(once ? null : listener));
  15747. }
  15748. try {
  15749. listener.call(contract, ...passArgs);
  15750. }
  15751. catch (error) { }
  15752. return !once;
  15753. });
  15754. if (sub.listeners.length === 0) {
  15755. sub.stop();
  15756. getInternal(contract).subs.delete(sub.tag);
  15757. }
  15758. return (count > 0);
  15759. }
  15760. async function emit(contract, event, args, payloadFunc) {
  15761. try {
  15762. await lastEmit;
  15763. }
  15764. catch (error) { }
  15765. const resultPromise = _emit(contract, event, args, payloadFunc);
  15766. lastEmit = resultPromise;
  15767. return await resultPromise;
  15768. }
  15769. const passProperties = ["then"];
  15770. class BaseContract {
  15771. /**
  15772. * The target to connect to.
  15773. *
  15774. * This can be an address, ENS name or any [[Addressable]], such as
  15775. * another contract. To get the resovled address, use the ``getAddress``
  15776. * method.
  15777. */
  15778. target;
  15779. /**
  15780. * The contract Interface.
  15781. */
  15782. interface;
  15783. /**
  15784. * The connected runner. This is generally a [[Provider]] or a
  15785. * [[Signer]], which dictates what operations are supported.
  15786. *
  15787. * For example, a **Contract** connected to a [[Provider]] may
  15788. * only execute read-only operations.
  15789. */
  15790. runner;
  15791. /**
  15792. * All the Events available on this contract.
  15793. */
  15794. filters;
  15795. /**
  15796. * @_ignore:
  15797. */
  15798. [internal];
  15799. /**
  15800. * The fallback or receive function if any.
  15801. */
  15802. fallback;
  15803. /**
  15804. * Creates a new contract connected to %%target%% with the %%abi%% and
  15805. * optionally connected to a %%runner%% to perform operations on behalf
  15806. * of.
  15807. */
  15808. constructor(target, abi, runner, _deployTx) {
  15809. assertArgument(typeof (target) === "string" || isAddressable(target), "invalid value for Contract target", "target", target);
  15810. if (runner == null) {
  15811. runner = null;
  15812. }
  15813. const iface = Interface.from(abi);
  15814. defineProperties(this, { target, runner, interface: iface });
  15815. Object.defineProperty(this, internal, { value: {} });
  15816. let addrPromise;
  15817. let addr = null;
  15818. let deployTx = null;
  15819. if (_deployTx) {
  15820. const provider = getProvider(runner);
  15821. // @TODO: the provider can be null; make a custom dummy provider that will throw a
  15822. // meaningful error
  15823. deployTx = new ContractTransactionResponse(this.interface, provider, _deployTx);
  15824. }
  15825. let subs = new Map();
  15826. // Resolve the target as the address
  15827. if (typeof (target) === "string") {
  15828. if (isHexString(target)) {
  15829. addr = target;
  15830. addrPromise = Promise.resolve(target);
  15831. }
  15832. else {
  15833. const resolver = getRunner(runner, "resolveName");
  15834. if (!canResolve(resolver)) {
  15835. throw makeError("contract runner does not support name resolution", "UNSUPPORTED_OPERATION", {
  15836. operation: "resolveName"
  15837. });
  15838. }
  15839. addrPromise = resolver.resolveName(target).then((addr) => {
  15840. if (addr == null) {
  15841. throw makeError("an ENS name used for a contract target must be correctly configured", "UNCONFIGURED_NAME", {
  15842. value: target
  15843. });
  15844. }
  15845. getInternal(this).addr = addr;
  15846. return addr;
  15847. });
  15848. }
  15849. }
  15850. else {
  15851. addrPromise = target.getAddress().then((addr) => {
  15852. if (addr == null) {
  15853. throw new Error("TODO");
  15854. }
  15855. getInternal(this).addr = addr;
  15856. return addr;
  15857. });
  15858. }
  15859. // Set our private values
  15860. setInternal(this, { addrPromise, addr, deployTx, subs });
  15861. // Add the event filters
  15862. const filters = new Proxy({}, {
  15863. get: (target, prop, receiver) => {
  15864. // Pass important checks (like `then` for Promise) through
  15865. if (typeof (prop) === "symbol" || passProperties.indexOf(prop) >= 0) {
  15866. return Reflect.get(target, prop, receiver);
  15867. }
  15868. try {
  15869. return this.getEvent(prop);
  15870. }
  15871. catch (error) {
  15872. if (!isError(error, "INVALID_ARGUMENT") || error.argument !== "key") {
  15873. throw error;
  15874. }
  15875. }
  15876. return undefined;
  15877. },
  15878. has: (target, prop) => {
  15879. // Pass important checks (like `then` for Promise) through
  15880. if (passProperties.indexOf(prop) >= 0) {
  15881. return Reflect.has(target, prop);
  15882. }
  15883. return Reflect.has(target, prop) || this.interface.hasEvent(String(prop));
  15884. }
  15885. });
  15886. defineProperties(this, { filters });
  15887. defineProperties(this, {
  15888. fallback: ((iface.receive || iface.fallback) ? (buildWrappedFallback(this)) : null)
  15889. });
  15890. // Return a Proxy that will respond to functions
  15891. return new Proxy(this, {
  15892. get: (target, prop, receiver) => {
  15893. if (typeof (prop) === "symbol" || prop in target || passProperties.indexOf(prop) >= 0) {
  15894. return Reflect.get(target, prop, receiver);
  15895. }
  15896. // Undefined properties should return undefined
  15897. try {
  15898. return target.getFunction(prop);
  15899. }
  15900. catch (error) {
  15901. if (!isError(error, "INVALID_ARGUMENT") || error.argument !== "key") {
  15902. throw error;
  15903. }
  15904. }
  15905. return undefined;
  15906. },
  15907. has: (target, prop) => {
  15908. if (typeof (prop) === "symbol" || prop in target || passProperties.indexOf(prop) >= 0) {
  15909. return Reflect.has(target, prop);
  15910. }
  15911. return target.interface.hasFunction(prop);
  15912. }
  15913. });
  15914. }
  15915. /**
  15916. * Return a new Contract instance with the same target and ABI, but
  15917. * a different %%runner%%.
  15918. */
  15919. connect(runner) {
  15920. return new BaseContract(this.target, this.interface, runner);
  15921. }
  15922. /**
  15923. * Return a new Contract instance with the same ABI and runner, but
  15924. * a different %%target%%.
  15925. */
  15926. attach(target) {
  15927. return new BaseContract(target, this.interface, this.runner);
  15928. }
  15929. /**
  15930. * Return the resolved address of this Contract.
  15931. */
  15932. async getAddress() { return await getInternal(this).addrPromise; }
  15933. /**
  15934. * Return the deployed bytecode or null if no bytecode is found.
  15935. */
  15936. async getDeployedCode() {
  15937. const provider = getProvider(this.runner);
  15938. assert(provider, "runner does not support .provider", "UNSUPPORTED_OPERATION", { operation: "getDeployedCode" });
  15939. const code = await provider.getCode(await this.getAddress());
  15940. if (code === "0x") {
  15941. return null;
  15942. }
  15943. return code;
  15944. }
  15945. /**
  15946. * Resolve to this Contract once the bytecode has been deployed, or
  15947. * resolve immediately if already deployed.
  15948. */
  15949. async waitForDeployment() {
  15950. // We have the deployement transaction; just use that (throws if deployement fails)
  15951. const deployTx = this.deploymentTransaction();
  15952. if (deployTx) {
  15953. await deployTx.wait();
  15954. return this;
  15955. }
  15956. // Check for code
  15957. const code = await this.getDeployedCode();
  15958. if (code != null) {
  15959. return this;
  15960. }
  15961. // Make sure we can subscribe to a provider event
  15962. const provider = getProvider(this.runner);
  15963. assert(provider != null, "contract runner does not support .provider", "UNSUPPORTED_OPERATION", { operation: "waitForDeployment" });
  15964. return new Promise((resolve, reject) => {
  15965. const checkCode = async () => {
  15966. try {
  15967. const code = await this.getDeployedCode();
  15968. if (code != null) {
  15969. return resolve(this);
  15970. }
  15971. provider.once("block", checkCode);
  15972. }
  15973. catch (error) {
  15974. reject(error);
  15975. }
  15976. };
  15977. checkCode();
  15978. });
  15979. }
  15980. /**
  15981. * Return the transaction used to deploy this contract.
  15982. *
  15983. * This is only available if this instance was returned from a
  15984. * [[ContractFactory]].
  15985. */
  15986. deploymentTransaction() {
  15987. return getInternal(this).deployTx;
  15988. }
  15989. /**
  15990. * Return the function for a given name. This is useful when a contract
  15991. * method name conflicts with a JavaScript name such as ``prototype`` or
  15992. * when using a Contract programatically.
  15993. */
  15994. getFunction(key) {
  15995. if (typeof (key) !== "string") {
  15996. key = key.format();
  15997. }
  15998. const func = buildWrappedMethod(this, key);
  15999. return func;
  16000. }
  16001. /**
  16002. * Return the event for a given name. This is useful when a contract
  16003. * event name conflicts with a JavaScript name such as ``prototype`` or
  16004. * when using a Contract programatically.
  16005. */
  16006. getEvent(key) {
  16007. if (typeof (key) !== "string") {
  16008. key = key.format();
  16009. }
  16010. return buildWrappedEvent(this, key);
  16011. }
  16012. /**
  16013. * @_ignore:
  16014. */
  16015. async queryTransaction(hash) {
  16016. throw new Error("@TODO");
  16017. }
  16018. /*
  16019. // @TODO: this is a non-backwards compatible change, but will be added
  16020. // in v7 and in a potential SmartContract class in an upcoming
  16021. // v6 release
  16022. async getTransactionReceipt(hash: string): Promise<null | ContractTransactionReceipt> {
  16023. const provider = getProvider(this.runner);
  16024. assert(provider, "contract runner does not have a provider",
  16025. "UNSUPPORTED_OPERATION", { operation: "queryTransaction" });
  16026. const receipt = await provider.getTransactionReceipt(hash);
  16027. if (receipt == null) { return null; }
  16028. return new ContractTransactionReceipt(this.interface, provider, receipt);
  16029. }
  16030. */
  16031. /**
  16032. * Provide historic access to event data for %%event%% in the range
  16033. * %%fromBlock%% (default: ``0``) to %%toBlock%% (default: ``"latest"``)
  16034. * inclusive.
  16035. */
  16036. async queryFilter(event, fromBlock, toBlock) {
  16037. if (fromBlock == null) {
  16038. fromBlock = 0;
  16039. }
  16040. if (toBlock == null) {
  16041. toBlock = "latest";
  16042. }
  16043. const { addr, addrPromise } = getInternal(this);
  16044. const address = (addr ? addr : (await addrPromise));
  16045. const { fragment, topics } = await getSubInfo(this, event);
  16046. const filter = { address, topics, fromBlock, toBlock };
  16047. const provider = getProvider(this.runner);
  16048. assert(provider, "contract runner does not have a provider", "UNSUPPORTED_OPERATION", { operation: "queryFilter" });
  16049. return (await provider.getLogs(filter)).map((log) => {
  16050. let foundFragment = fragment;
  16051. if (foundFragment == null) {
  16052. try {
  16053. foundFragment = this.interface.getEvent(log.topics[0]);
  16054. }
  16055. catch (error) { }
  16056. }
  16057. if (foundFragment) {
  16058. try {
  16059. return new EventLog(log, this.interface, foundFragment);
  16060. }
  16061. catch (error) {
  16062. return new UndecodedEventLog(log, error);
  16063. }
  16064. }
  16065. return new Log(log, provider);
  16066. });
  16067. }
  16068. /**
  16069. * Add an event %%listener%% for the %%event%%.
  16070. */
  16071. async on(event, listener) {
  16072. const sub = await getSub(this, "on", event);
  16073. sub.listeners.push({ listener, once: false });
  16074. sub.start();
  16075. return this;
  16076. }
  16077. /**
  16078. * Add an event %%listener%% for the %%event%%, but remove the listener
  16079. * after it is fired once.
  16080. */
  16081. async once(event, listener) {
  16082. const sub = await getSub(this, "once", event);
  16083. sub.listeners.push({ listener, once: true });
  16084. sub.start();
  16085. return this;
  16086. }
  16087. /**
  16088. * Emit an %%event%% calling all listeners with %%args%%.
  16089. *
  16090. * Resolves to ``true`` if any listeners were called.
  16091. */
  16092. async emit(event, ...args) {
  16093. return await emit(this, event, args, null);
  16094. }
  16095. /**
  16096. * Resolves to the number of listeners of %%event%% or the total number
  16097. * of listeners if unspecified.
  16098. */
  16099. async listenerCount(event) {
  16100. if (event) {
  16101. const sub = await hasSub(this, event);
  16102. if (!sub) {
  16103. return 0;
  16104. }
  16105. return sub.listeners.length;
  16106. }
  16107. const { subs } = getInternal(this);
  16108. let total = 0;
  16109. for (const { listeners } of subs.values()) {
  16110. total += listeners.length;
  16111. }
  16112. return total;
  16113. }
  16114. /**
  16115. * Resolves to the listeners subscribed to %%event%% or all listeners
  16116. * if unspecified.
  16117. */
  16118. async listeners(event) {
  16119. if (event) {
  16120. const sub = await hasSub(this, event);
  16121. if (!sub) {
  16122. return [];
  16123. }
  16124. return sub.listeners.map(({ listener }) => listener);
  16125. }
  16126. const { subs } = getInternal(this);
  16127. let result = [];
  16128. for (const { listeners } of subs.values()) {
  16129. result = result.concat(listeners.map(({ listener }) => listener));
  16130. }
  16131. return result;
  16132. }
  16133. /**
  16134. * Remove the %%listener%% from the listeners for %%event%% or remove
  16135. * all listeners if unspecified.
  16136. */
  16137. async off(event, listener) {
  16138. const sub = await hasSub(this, event);
  16139. if (!sub) {
  16140. return this;
  16141. }
  16142. if (listener) {
  16143. const index = sub.listeners.map(({ listener }) => listener).indexOf(listener);
  16144. if (index >= 0) {
  16145. sub.listeners.splice(index, 1);
  16146. }
  16147. }
  16148. if (listener == null || sub.listeners.length === 0) {
  16149. sub.stop();
  16150. getInternal(this).subs.delete(sub.tag);
  16151. }
  16152. return this;
  16153. }
  16154. /**
  16155. * Remove all the listeners for %%event%% or remove all listeners if
  16156. * unspecified.
  16157. */
  16158. async removeAllListeners(event) {
  16159. if (event) {
  16160. const sub = await hasSub(this, event);
  16161. if (!sub) {
  16162. return this;
  16163. }
  16164. sub.stop();
  16165. getInternal(this).subs.delete(sub.tag);
  16166. }
  16167. else {
  16168. const { subs } = getInternal(this);
  16169. for (const { tag, stop } of subs.values()) {
  16170. stop();
  16171. subs.delete(tag);
  16172. }
  16173. }
  16174. return this;
  16175. }
  16176. /**
  16177. * Alias for [on].
  16178. */
  16179. async addListener(event, listener) {
  16180. return await this.on(event, listener);
  16181. }
  16182. /**
  16183. * Alias for [off].
  16184. */
  16185. async removeListener(event, listener) {
  16186. return await this.off(event, listener);
  16187. }
  16188. /**
  16189. * Create a new Class for the %%abi%%.
  16190. */
  16191. static buildClass(abi) {
  16192. class CustomContract extends BaseContract {
  16193. constructor(address, runner = null) {
  16194. super(address, abi, runner);
  16195. }
  16196. }
  16197. return CustomContract;
  16198. }
  16199. ;
  16200. /**
  16201. * Create a new BaseContract with a specified Interface.
  16202. */
  16203. static from(target, abi, runner) {
  16204. if (runner == null) {
  16205. runner = null;
  16206. }
  16207. const contract = new this(target, abi, runner);
  16208. return contract;
  16209. }
  16210. }
  16211. function _ContractBase() {
  16212. return BaseContract;
  16213. }
  16214. /**
  16215. * A [[BaseContract]] with no type guards on its methods or events.
  16216. */
  16217. class Contract extends _ContractBase() {
  16218. }
  16219. // A = Arguments to the constructor
  16220. // I = Interface of deployed contracts
  16221. /**
  16222. * A **ContractFactory** is used to deploy a Contract to the blockchain.
  16223. */
  16224. class ContractFactory {
  16225. /**
  16226. * The Contract Interface.
  16227. */
  16228. interface;
  16229. /**
  16230. * The Contract deployment bytecode. Often called the initcode.
  16231. */
  16232. bytecode;
  16233. /**
  16234. * The ContractRunner to deploy the Contract as.
  16235. */
  16236. runner;
  16237. /**
  16238. * Create a new **ContractFactory** with %%abi%% and %%bytecode%%,
  16239. * optionally connected to %%runner%%.
  16240. *
  16241. * The %%bytecode%% may be the ``bytecode`` property within the
  16242. * standard Solidity JSON output.
  16243. */
  16244. constructor(abi, bytecode, runner) {
  16245. const iface = Interface.from(abi);
  16246. // Dereference Solidity bytecode objects and allow a missing `0x`-prefix
  16247. if (bytecode instanceof Uint8Array) {
  16248. bytecode = hexlify(getBytes(bytecode));
  16249. }
  16250. else {
  16251. if (typeof (bytecode) === "object") {
  16252. bytecode = bytecode.object;
  16253. }
  16254. if (!bytecode.startsWith("0x")) {
  16255. bytecode = "0x" + bytecode;
  16256. }
  16257. bytecode = hexlify(getBytes(bytecode));
  16258. }
  16259. defineProperties(this, {
  16260. bytecode, interface: iface, runner: (runner || null)
  16261. });
  16262. }
  16263. attach(target) {
  16264. return new BaseContract(target, this.interface, this.runner);
  16265. }
  16266. /**
  16267. * Resolves to the transaction to deploy the contract, passing %%args%%
  16268. * into the constructor.
  16269. */
  16270. async getDeployTransaction(...args) {
  16271. let overrides = {};
  16272. const fragment = this.interface.deploy;
  16273. if (fragment.inputs.length + 1 === args.length) {
  16274. overrides = await copyOverrides(args.pop());
  16275. }
  16276. if (fragment.inputs.length !== args.length) {
  16277. throw new Error("incorrect number of arguments to constructor");
  16278. }
  16279. const resolvedArgs = await resolveArgs(this.runner, fragment.inputs, args);
  16280. const data = concat([this.bytecode, this.interface.encodeDeploy(resolvedArgs)]);
  16281. return Object.assign({}, overrides, { data });
  16282. }
  16283. /**
  16284. * Resolves to the Contract deployed by passing %%args%% into the
  16285. * constructor.
  16286. *
  16287. * This will resolve to the Contract before it has been deployed to the
  16288. * network, so the [[BaseContract-waitForDeployment]] should be used before
  16289. * sending any transactions to it.
  16290. */
  16291. async deploy(...args) {
  16292. const tx = await this.getDeployTransaction(...args);
  16293. assert(this.runner && typeof (this.runner.sendTransaction) === "function", "factory runner does not support sending transactions", "UNSUPPORTED_OPERATION", {
  16294. operation: "sendTransaction"
  16295. });
  16296. const sentTx = await this.runner.sendTransaction(tx);
  16297. const address = getCreateAddress(sentTx);
  16298. return new BaseContract(address, this.interface, this.runner, sentTx);
  16299. }
  16300. /**
  16301. * Return a new **ContractFactory** with the same ABI and bytecode,
  16302. * but connected to %%runner%%.
  16303. */
  16304. connect(runner) {
  16305. return new ContractFactory(this.interface, this.bytecode, runner);
  16306. }
  16307. /**
  16308. * Create a new **ContractFactory** from the standard Solidity JSON output.
  16309. */
  16310. static fromSolidity(output, runner) {
  16311. assertArgument(output != null, "bad compiler output", "output", output);
  16312. if (typeof (output) === "string") {
  16313. output = JSON.parse(output);
  16314. }
  16315. const abi = output.abi;
  16316. let bytecode = "";
  16317. if (output.bytecode) {
  16318. bytecode = output.bytecode;
  16319. }
  16320. else if (output.evm && output.evm.bytecode) {
  16321. bytecode = output.evm.bytecode;
  16322. }
  16323. return new this(abi, bytecode, runner);
  16324. }
  16325. }
  16326. /**
  16327. * ENS is a service which allows easy-to-remember names to map to
  16328. * network addresses.
  16329. *
  16330. * @_section: api/providers/ens-resolver:ENS Resolver [about-ens-rsolver]
  16331. */
  16332. // @TODO: This should use the fetch-data:ipfs gateway
  16333. // Trim off the ipfs:// prefix and return the default gateway URL
  16334. function getIpfsLink(link) {
  16335. if (link.match(/^ipfs:\/\/ipfs\//i)) {
  16336. link = link.substring(12);
  16337. }
  16338. else if (link.match(/^ipfs:\/\//i)) {
  16339. link = link.substring(7);
  16340. }
  16341. else {
  16342. assertArgument(false, "unsupported IPFS format", "link", link);
  16343. }
  16344. return `https:/\/gateway.ipfs.io/ipfs/${link}`;
  16345. }
  16346. /**
  16347. * A provider plugin super-class for processing multicoin address types.
  16348. */
  16349. class MulticoinProviderPlugin {
  16350. /**
  16351. * The name.
  16352. */
  16353. name;
  16354. /**
  16355. * Creates a new **MulticoinProviderPluing** for %%name%%.
  16356. */
  16357. constructor(name) {
  16358. defineProperties(this, { name });
  16359. }
  16360. connect(proivder) {
  16361. return this;
  16362. }
  16363. /**
  16364. * Returns ``true`` if %%coinType%% is supported by this plugin.
  16365. */
  16366. supportsCoinType(coinType) {
  16367. return false;
  16368. }
  16369. /**
  16370. * Resolves to the encoded %%address%% for %%coinType%%.
  16371. */
  16372. async encodeAddress(coinType, address) {
  16373. throw new Error("unsupported coin");
  16374. }
  16375. /**
  16376. * Resolves to the decoded %%data%% for %%coinType%%.
  16377. */
  16378. async decodeAddress(coinType, data) {
  16379. throw new Error("unsupported coin");
  16380. }
  16381. }
  16382. const matcherIpfs = new RegExp("^(ipfs):/\/(.*)$", "i");
  16383. const matchers = [
  16384. new RegExp("^(https):/\/(.*)$", "i"),
  16385. new RegExp("^(data):(.*)$", "i"),
  16386. matcherIpfs,
  16387. new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$", "i"),
  16388. ];
  16389. /**
  16390. * A connected object to a resolved ENS name resolver, which can be
  16391. * used to query additional details.
  16392. */
  16393. class EnsResolver {
  16394. /**
  16395. * The connected provider.
  16396. */
  16397. provider;
  16398. /**
  16399. * The address of the resolver.
  16400. */
  16401. address;
  16402. /**
  16403. * The name this resolver was resolved against.
  16404. */
  16405. name;
  16406. // For EIP-2544 names, the ancestor that provided the resolver
  16407. #supports2544;
  16408. #resolver;
  16409. constructor(provider, address, name) {
  16410. defineProperties(this, { provider, address, name });
  16411. this.#supports2544 = null;
  16412. this.#resolver = new Contract(address, [
  16413. "function supportsInterface(bytes4) view returns (bool)",
  16414. "function resolve(bytes, bytes) view returns (bytes)",
  16415. "function addr(bytes32) view returns (address)",
  16416. "function addr(bytes32, uint) view returns (bytes)",
  16417. "function text(bytes32, string) view returns (string)",
  16418. "function contenthash(bytes32) view returns (bytes)",
  16419. ], provider);
  16420. }
  16421. /**
  16422. * Resolves to true if the resolver supports wildcard resolution.
  16423. */
  16424. async supportsWildcard() {
  16425. if (this.#supports2544 == null) {
  16426. this.#supports2544 = (async () => {
  16427. try {
  16428. return await this.#resolver.supportsInterface("0x9061b923");
  16429. }
  16430. catch (error) {
  16431. // Wildcard resolvers must understand supportsInterface
  16432. // and return true.
  16433. if (isError(error, "CALL_EXCEPTION")) {
  16434. return false;
  16435. }
  16436. // Let future attempts try again...
  16437. this.#supports2544 = null;
  16438. throw error;
  16439. }
  16440. })();
  16441. }
  16442. return await this.#supports2544;
  16443. }
  16444. async #fetch(funcName, params) {
  16445. params = (params || []).slice();
  16446. const iface = this.#resolver.interface;
  16447. // The first parameters is always the nodehash
  16448. params.unshift(namehash(this.name));
  16449. let fragment = null;
  16450. if (await this.supportsWildcard()) {
  16451. fragment = iface.getFunction(funcName);
  16452. assert(fragment, "missing fragment", "UNKNOWN_ERROR", {
  16453. info: { funcName }
  16454. });
  16455. params = [
  16456. dnsEncode(this.name, 255),
  16457. iface.encodeFunctionData(fragment, params)
  16458. ];
  16459. funcName = "resolve(bytes,bytes)";
  16460. }
  16461. params.push({
  16462. enableCcipRead: true
  16463. });
  16464. try {
  16465. const result = await this.#resolver[funcName](...params);
  16466. if (fragment) {
  16467. return iface.decodeFunctionResult(fragment, result)[0];
  16468. }
  16469. return result;
  16470. }
  16471. catch (error) {
  16472. if (!isError(error, "CALL_EXCEPTION")) {
  16473. throw error;
  16474. }
  16475. }
  16476. return null;
  16477. }
  16478. /**
  16479. * Resolves to the address for %%coinType%% or null if the
  16480. * provided %%coinType%% has not been configured.
  16481. */
  16482. async getAddress(coinType) {
  16483. if (coinType == null) {
  16484. coinType = 60;
  16485. }
  16486. if (coinType === 60) {
  16487. try {
  16488. const result = await this.#fetch("addr(bytes32)");
  16489. // No address
  16490. if (result == null || result === ZeroAddress) {
  16491. return null;
  16492. }
  16493. return result;
  16494. }
  16495. catch (error) {
  16496. if (isError(error, "CALL_EXCEPTION")) {
  16497. return null;
  16498. }
  16499. throw error;
  16500. }
  16501. }
  16502. // Try decoding its EVM canonical chain as an EVM chain address first
  16503. if (coinType >= 0 && coinType < 0x80000000) {
  16504. let ethCoinType = coinType + 0x80000000;
  16505. const data = await this.#fetch("addr(bytes32,uint)", [ethCoinType]);
  16506. if (isHexString(data, 20)) {
  16507. return getAddress(data);
  16508. }
  16509. }
  16510. let coinPlugin = null;
  16511. for (const plugin of this.provider.plugins) {
  16512. if (!(plugin instanceof MulticoinProviderPlugin)) {
  16513. continue;
  16514. }
  16515. if (plugin.supportsCoinType(coinType)) {
  16516. coinPlugin = plugin;
  16517. break;
  16518. }
  16519. }
  16520. if (coinPlugin == null) {
  16521. return null;
  16522. }
  16523. // keccak256("addr(bytes32,uint256")
  16524. const data = await this.#fetch("addr(bytes32,uint)", [coinType]);
  16525. // No address
  16526. if (data == null || data === "0x") {
  16527. return null;
  16528. }
  16529. // Compute the address
  16530. const address = await coinPlugin.decodeAddress(coinType, data);
  16531. if (address != null) {
  16532. return address;
  16533. }
  16534. assert(false, `invalid coin data`, "UNSUPPORTED_OPERATION", {
  16535. operation: `getAddress(${coinType})`,
  16536. info: { coinType, data }
  16537. });
  16538. }
  16539. /**
  16540. * Resolves to the EIP-634 text record for %%key%%, or ``null``
  16541. * if unconfigured.
  16542. */
  16543. async getText(key) {
  16544. const data = await this.#fetch("text(bytes32,string)", [key]);
  16545. if (data == null || data === "0x") {
  16546. return null;
  16547. }
  16548. return data;
  16549. }
  16550. /**
  16551. * Rsolves to the content-hash or ``null`` if unconfigured.
  16552. */
  16553. async getContentHash() {
  16554. // keccak256("contenthash()")
  16555. const data = await this.#fetch("contenthash(bytes32)");
  16556. // No contenthash
  16557. if (data == null || data === "0x") {
  16558. return null;
  16559. }
  16560. // IPFS (CID: 1, Type: 70=DAG-PB, 72=libp2p-key)
  16561. const ipfs = data.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);
  16562. if (ipfs) {
  16563. const scheme = (ipfs[1] === "e3010170") ? "ipfs" : "ipns";
  16564. const length = parseInt(ipfs[4], 16);
  16565. if (ipfs[5].length === length * 2) {
  16566. return `${scheme}:/\/${encodeBase58("0x" + ipfs[2])}`;
  16567. }
  16568. }
  16569. // Swarm (CID: 1, Type: swarm-manifest; hash/length hard-coded to keccak256/32)
  16570. const swarm = data.match(/^0xe40101fa011b20([0-9a-f]*)$/);
  16571. if (swarm && swarm[1].length === 64) {
  16572. return `bzz:/\/${swarm[1]}`;
  16573. }
  16574. assert(false, `invalid or unsupported content hash data`, "UNSUPPORTED_OPERATION", {
  16575. operation: "getContentHash()",
  16576. info: { data }
  16577. });
  16578. }
  16579. /**
  16580. * Resolves to the avatar url or ``null`` if the avatar is either
  16581. * unconfigured or incorrectly configured (e.g. references an NFT
  16582. * not owned by the address).
  16583. *
  16584. * If diagnosing issues with configurations, the [[_getAvatar]]
  16585. * method may be useful.
  16586. */
  16587. async getAvatar() {
  16588. const avatar = await this._getAvatar();
  16589. return avatar.url;
  16590. }
  16591. /**
  16592. * When resolving an avatar, there are many steps involved, such
  16593. * fetching metadata and possibly validating ownership of an
  16594. * NFT.
  16595. *
  16596. * This method can be used to examine each step and the value it
  16597. * was working from.
  16598. */
  16599. async _getAvatar() {
  16600. const linkage = [{ type: "name", value: this.name }];
  16601. try {
  16602. // test data for ricmoo.eth
  16603. //const avatar = "eip155:1/erc721:0x265385c7f4132228A0d54EB1A9e7460b91c0cC68/29233";
  16604. const avatar = await this.getText("avatar");
  16605. if (avatar == null) {
  16606. linkage.push({ type: "!avatar", value: "" });
  16607. return { url: null, linkage };
  16608. }
  16609. linkage.push({ type: "avatar", value: avatar });
  16610. for (let i = 0; i < matchers.length; i++) {
  16611. const match = avatar.match(matchers[i]);
  16612. if (match == null) {
  16613. continue;
  16614. }
  16615. const scheme = match[1].toLowerCase();
  16616. switch (scheme) {
  16617. case "https":
  16618. case "data":
  16619. linkage.push({ type: "url", value: avatar });
  16620. return { linkage, url: avatar };
  16621. case "ipfs": {
  16622. const url = getIpfsLink(avatar);
  16623. linkage.push({ type: "ipfs", value: avatar });
  16624. linkage.push({ type: "url", value: url });
  16625. return { linkage, url };
  16626. }
  16627. case "erc721":
  16628. case "erc1155": {
  16629. // Depending on the ERC type, use tokenURI(uint256) or url(uint256)
  16630. const selector = (scheme === "erc721") ? "tokenURI(uint256)" : "uri(uint256)";
  16631. linkage.push({ type: scheme, value: avatar });
  16632. // The owner of this name
  16633. const owner = await this.getAddress();
  16634. if (owner == null) {
  16635. linkage.push({ type: "!owner", value: "" });
  16636. return { url: null, linkage };
  16637. }
  16638. const comps = (match[2] || "").split("/");
  16639. if (comps.length !== 2) {
  16640. linkage.push({ type: `!${scheme}caip`, value: (match[2] || "") });
  16641. return { url: null, linkage };
  16642. }
  16643. const tokenId = comps[1];
  16644. const contract = new Contract(comps[0], [
  16645. // ERC-721
  16646. "function tokenURI(uint) view returns (string)",
  16647. "function ownerOf(uint) view returns (address)",
  16648. // ERC-1155
  16649. "function uri(uint) view returns (string)",
  16650. "function balanceOf(address, uint256) view returns (uint)"
  16651. ], this.provider);
  16652. // Check that this account owns the token
  16653. if (scheme === "erc721") {
  16654. const tokenOwner = await contract.ownerOf(tokenId);
  16655. if (owner !== tokenOwner) {
  16656. linkage.push({ type: "!owner", value: tokenOwner });
  16657. return { url: null, linkage };
  16658. }
  16659. linkage.push({ type: "owner", value: tokenOwner });
  16660. }
  16661. else if (scheme === "erc1155") {
  16662. const balance = await contract.balanceOf(owner, tokenId);
  16663. if (!balance) {
  16664. linkage.push({ type: "!balance", value: "0" });
  16665. return { url: null, linkage };
  16666. }
  16667. linkage.push({ type: "balance", value: balance.toString() });
  16668. }
  16669. // Call the token contract for the metadata URL
  16670. let metadataUrl = await contract[selector](tokenId);
  16671. if (metadataUrl == null || metadataUrl === "0x") {
  16672. linkage.push({ type: "!metadata-url", value: "" });
  16673. return { url: null, linkage };
  16674. }
  16675. linkage.push({ type: "metadata-url-base", value: metadataUrl });
  16676. // ERC-1155 allows a generic {id} in the URL
  16677. if (scheme === "erc1155") {
  16678. metadataUrl = metadataUrl.replace("{id}", toBeHex(tokenId, 32).substring(2));
  16679. linkage.push({ type: "metadata-url-expanded", value: metadataUrl });
  16680. }
  16681. // Transform IPFS metadata links
  16682. if (metadataUrl.match(/^ipfs:/i)) {
  16683. metadataUrl = getIpfsLink(metadataUrl);
  16684. }
  16685. linkage.push({ type: "metadata-url", value: metadataUrl });
  16686. // Get the token metadata
  16687. let metadata = {};
  16688. const response = await (new FetchRequest(metadataUrl)).send();
  16689. response.assertOk();
  16690. try {
  16691. metadata = response.bodyJson;
  16692. }
  16693. catch (error) {
  16694. try {
  16695. linkage.push({ type: "!metadata", value: response.bodyText });
  16696. }
  16697. catch (error) {
  16698. const bytes = response.body;
  16699. if (bytes) {
  16700. linkage.push({ type: "!metadata", value: hexlify(bytes) });
  16701. }
  16702. return { url: null, linkage };
  16703. }
  16704. return { url: null, linkage };
  16705. }
  16706. if (!metadata) {
  16707. linkage.push({ type: "!metadata", value: "" });
  16708. return { url: null, linkage };
  16709. }
  16710. linkage.push({ type: "metadata", value: JSON.stringify(metadata) });
  16711. // Pull the image URL out
  16712. let imageUrl = metadata.image;
  16713. if (typeof (imageUrl) !== "string") {
  16714. linkage.push({ type: "!imageUrl", value: "" });
  16715. return { url: null, linkage };
  16716. }
  16717. if (imageUrl.match(/^(https:\/\/|data:)/i)) {
  16718. // Allow
  16719. }
  16720. else {
  16721. // Transform IPFS link to gateway
  16722. const ipfs = imageUrl.match(matcherIpfs);
  16723. if (ipfs == null) {
  16724. linkage.push({ type: "!imageUrl-ipfs", value: imageUrl });
  16725. return { url: null, linkage };
  16726. }
  16727. linkage.push({ type: "imageUrl-ipfs", value: imageUrl });
  16728. imageUrl = getIpfsLink(imageUrl);
  16729. }
  16730. linkage.push({ type: "url", value: imageUrl });
  16731. return { linkage, url: imageUrl };
  16732. }
  16733. }
  16734. }
  16735. }
  16736. catch (error) { }
  16737. return { linkage, url: null };
  16738. }
  16739. static async getEnsAddress(provider) {
  16740. const network = await provider.getNetwork();
  16741. const ensPlugin = network.getPlugin("org.ethers.plugins.network.Ens");
  16742. // No ENS...
  16743. assert(ensPlugin, "network does not support ENS", "UNSUPPORTED_OPERATION", {
  16744. operation: "getEnsAddress", info: { network }
  16745. });
  16746. return ensPlugin.address;
  16747. }
  16748. static async #getResolver(provider, name) {
  16749. const ensAddr = await EnsResolver.getEnsAddress(provider);
  16750. try {
  16751. const contract = new Contract(ensAddr, [
  16752. "function resolver(bytes32) view returns (address)"
  16753. ], provider);
  16754. const addr = await contract.resolver(namehash(name), {
  16755. enableCcipRead: true
  16756. });
  16757. if (addr === ZeroAddress) {
  16758. return null;
  16759. }
  16760. return addr;
  16761. }
  16762. catch (error) {
  16763. // ENS registry cannot throw errors on resolver(bytes32),
  16764. // so probably a link error
  16765. throw error;
  16766. }
  16767. return null;
  16768. }
  16769. /**
  16770. * Resolve to the ENS resolver for %%name%% using %%provider%% or
  16771. * ``null`` if unconfigured.
  16772. */
  16773. static async fromName(provider, name) {
  16774. let currentName = name;
  16775. while (true) {
  16776. if (currentName === "" || currentName === ".") {
  16777. return null;
  16778. }
  16779. // Optimization since the eth node cannot change and does
  16780. // not have a wildcard resolver
  16781. if (name !== "eth" && currentName === "eth") {
  16782. return null;
  16783. }
  16784. // Check the current node for a resolver
  16785. const addr = await EnsResolver.#getResolver(provider, currentName);
  16786. // Found a resolver!
  16787. if (addr != null) {
  16788. const resolver = new EnsResolver(provider, addr, name);
  16789. // Legacy resolver found, using EIP-2544 so it isn't safe to use
  16790. if (currentName !== name && !(await resolver.supportsWildcard())) {
  16791. return null;
  16792. }
  16793. return resolver;
  16794. }
  16795. // Get the parent node
  16796. currentName = currentName.split(".").slice(1).join(".");
  16797. }
  16798. }
  16799. }
  16800. /**
  16801. * @_ignore
  16802. */
  16803. const BN_0 = BigInt(0);
  16804. function allowNull(format, nullValue) {
  16805. return (function (value) {
  16806. if (value == null) {
  16807. return nullValue;
  16808. }
  16809. return format(value);
  16810. });
  16811. }
  16812. function arrayOf(format, allowNull) {
  16813. return ((array) => {
  16814. if (allowNull && array == null) {
  16815. return null;
  16816. }
  16817. if (!Array.isArray(array)) {
  16818. throw new Error("not an array");
  16819. }
  16820. return array.map((i) => format(i));
  16821. });
  16822. }
  16823. // Requires an object which matches a fleet of other formatters
  16824. // Any FormatFunc may return `undefined` to have the value omitted
  16825. // from the result object. Calls preserve `this`.
  16826. function object(format, altNames) {
  16827. return ((value) => {
  16828. const result = {};
  16829. for (const key in format) {
  16830. let srcKey = key;
  16831. if (altNames && key in altNames && !(srcKey in value)) {
  16832. for (const altKey of altNames[key]) {
  16833. if (altKey in value) {
  16834. srcKey = altKey;
  16835. break;
  16836. }
  16837. }
  16838. }
  16839. try {
  16840. const nv = format[key](value[srcKey]);
  16841. if (nv !== undefined) {
  16842. result[key] = nv;
  16843. }
  16844. }
  16845. catch (error) {
  16846. const message = (error instanceof Error) ? error.message : "not-an-error";
  16847. assert(false, `invalid value for value.${key} (${message})`, "BAD_DATA", { value });
  16848. }
  16849. }
  16850. return result;
  16851. });
  16852. }
  16853. function formatBoolean(value) {
  16854. switch (value) {
  16855. case true:
  16856. case "true":
  16857. return true;
  16858. case false:
  16859. case "false":
  16860. return false;
  16861. }
  16862. assertArgument(false, `invalid boolean; ${JSON.stringify(value)}`, "value", value);
  16863. }
  16864. function formatData(value) {
  16865. assertArgument(isHexString(value, true), "invalid data", "value", value);
  16866. return value;
  16867. }
  16868. function formatHash(value) {
  16869. assertArgument(isHexString(value, 32), "invalid hash", "value", value);
  16870. return value;
  16871. }
  16872. const _formatLog = object({
  16873. address: getAddress,
  16874. blockHash: formatHash,
  16875. blockNumber: getNumber,
  16876. data: formatData,
  16877. index: getNumber,
  16878. removed: allowNull(formatBoolean, false),
  16879. topics: arrayOf(formatHash),
  16880. transactionHash: formatHash,
  16881. transactionIndex: getNumber,
  16882. }, {
  16883. index: ["logIndex"]
  16884. });
  16885. function formatLog(value) {
  16886. return _formatLog(value);
  16887. }
  16888. const _formatBlock = object({
  16889. hash: allowNull(formatHash),
  16890. parentHash: formatHash,
  16891. parentBeaconBlockRoot: allowNull(formatHash, null),
  16892. number: getNumber,
  16893. timestamp: getNumber,
  16894. nonce: allowNull(formatData),
  16895. difficulty: getBigInt,
  16896. gasLimit: getBigInt,
  16897. gasUsed: getBigInt,
  16898. stateRoot: allowNull(formatHash, null),
  16899. receiptsRoot: allowNull(formatHash, null),
  16900. blobGasUsed: allowNull(getBigInt, null),
  16901. excessBlobGas: allowNull(getBigInt, null),
  16902. miner: allowNull(getAddress),
  16903. prevRandao: allowNull(formatHash, null),
  16904. extraData: formatData,
  16905. baseFeePerGas: allowNull(getBigInt)
  16906. }, {
  16907. prevRandao: ["mixHash"]
  16908. });
  16909. function formatBlock(value) {
  16910. const result = _formatBlock(value);
  16911. result.transactions = value.transactions.map((tx) => {
  16912. if (typeof (tx) === "string") {
  16913. return tx;
  16914. }
  16915. return formatTransactionResponse(tx);
  16916. });
  16917. return result;
  16918. }
  16919. const _formatReceiptLog = object({
  16920. transactionIndex: getNumber,
  16921. blockNumber: getNumber,
  16922. transactionHash: formatHash,
  16923. address: getAddress,
  16924. topics: arrayOf(formatHash),
  16925. data: formatData,
  16926. index: getNumber,
  16927. blockHash: formatHash,
  16928. }, {
  16929. index: ["logIndex"]
  16930. });
  16931. function formatReceiptLog(value) {
  16932. return _formatReceiptLog(value);
  16933. }
  16934. const _formatTransactionReceipt = object({
  16935. to: allowNull(getAddress, null),
  16936. from: allowNull(getAddress, null),
  16937. contractAddress: allowNull(getAddress, null),
  16938. // should be allowNull(hash), but broken-EIP-658 support is handled in receipt
  16939. index: getNumber,
  16940. root: allowNull(hexlify),
  16941. gasUsed: getBigInt,
  16942. blobGasUsed: allowNull(getBigInt, null),
  16943. logsBloom: allowNull(formatData),
  16944. blockHash: formatHash,
  16945. hash: formatHash,
  16946. logs: arrayOf(formatReceiptLog),
  16947. blockNumber: getNumber,
  16948. //confirmations: allowNull(getNumber, null),
  16949. cumulativeGasUsed: getBigInt,
  16950. effectiveGasPrice: allowNull(getBigInt),
  16951. blobGasPrice: allowNull(getBigInt, null),
  16952. status: allowNull(getNumber),
  16953. type: allowNull(getNumber, 0)
  16954. }, {
  16955. effectiveGasPrice: ["gasPrice"],
  16956. hash: ["transactionHash"],
  16957. index: ["transactionIndex"],
  16958. });
  16959. function formatTransactionReceipt(value) {
  16960. return _formatTransactionReceipt(value);
  16961. }
  16962. function formatTransactionResponse(value) {
  16963. // Some clients (TestRPC) do strange things like return 0x0 for the
  16964. // 0 address; correct this to be a real address
  16965. if (value.to && getBigInt(value.to) === BN_0) {
  16966. value.to = "0x0000000000000000000000000000000000000000";
  16967. }
  16968. const result = object({
  16969. hash: formatHash,
  16970. // Some nodes do not return this, usually test nodes (like Ganache)
  16971. index: allowNull(getNumber, undefined),
  16972. type: (value) => {
  16973. if (value === "0x" || value == null) {
  16974. return 0;
  16975. }
  16976. return getNumber(value);
  16977. },
  16978. accessList: allowNull(accessListify, null),
  16979. blobVersionedHashes: allowNull(arrayOf(formatHash, true), null),
  16980. blockHash: allowNull(formatHash, null),
  16981. blockNumber: allowNull(getNumber, null),
  16982. transactionIndex: allowNull(getNumber, null),
  16983. from: getAddress,
  16984. // either (gasPrice) or (maxPriorityFeePerGas + maxFeePerGas) must be set
  16985. gasPrice: allowNull(getBigInt),
  16986. maxPriorityFeePerGas: allowNull(getBigInt),
  16987. maxFeePerGas: allowNull(getBigInt),
  16988. maxFeePerBlobGas: allowNull(getBigInt, null),
  16989. gasLimit: getBigInt,
  16990. to: allowNull(getAddress, null),
  16991. value: getBigInt,
  16992. nonce: getNumber,
  16993. data: formatData,
  16994. creates: allowNull(getAddress, null),
  16995. chainId: allowNull(getBigInt, null)
  16996. }, {
  16997. data: ["input"],
  16998. gasLimit: ["gas"],
  16999. index: ["transactionIndex"]
  17000. })(value);
  17001. // If to and creates are empty, populate the creates from the value
  17002. if (result.to == null && result.creates == null) {
  17003. result.creates = getCreateAddress(result);
  17004. }
  17005. // @TODO: Check fee data
  17006. // Add an access list to supported transaction types
  17007. if ((value.type === 1 || value.type === 2) && value.accessList == null) {
  17008. result.accessList = [];
  17009. }
  17010. // Compute the signature
  17011. if (value.signature) {
  17012. result.signature = Signature.from(value.signature);
  17013. }
  17014. else {
  17015. result.signature = Signature.from(value);
  17016. }
  17017. // Some backends omit ChainId on legacy transactions, but we can compute it
  17018. if (result.chainId == null) {
  17019. const chainId = result.signature.legacyChainId;
  17020. if (chainId != null) {
  17021. result.chainId = chainId;
  17022. }
  17023. }
  17024. // @TODO: check chainID
  17025. /*
  17026. if (value.chainId != null) {
  17027. let chainId = value.chainId;
  17028. if (isHexString(chainId)) {
  17029. chainId = BigNumber.from(chainId).toNumber();
  17030. }
  17031. result.chainId = chainId;
  17032. } else {
  17033. let chainId = value.networkId;
  17034. // geth-etc returns chainId
  17035. if (chainId == null && result.v == null) {
  17036. chainId = value.chainId;
  17037. }
  17038. if (isHexString(chainId)) {
  17039. chainId = BigNumber.from(chainId).toNumber();
  17040. }
  17041. if (typeof(chainId) !== "number" && result.v != null) {
  17042. chainId = (result.v - 35) / 2;
  17043. if (chainId < 0) { chainId = 0; }
  17044. chainId = parseInt(chainId);
  17045. }
  17046. if (typeof(chainId) !== "number") { chainId = 0; }
  17047. result.chainId = chainId;
  17048. }
  17049. */
  17050. // 0x0000... should actually be null
  17051. if (result.blockHash && getBigInt(result.blockHash) === BN_0) {
  17052. result.blockHash = null;
  17053. }
  17054. return result;
  17055. }
  17056. const EnsAddress = "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e";
  17057. /**
  17058. * A **NetworkPlugin** provides additional functionality on a [[Network]].
  17059. */
  17060. class NetworkPlugin {
  17061. /**
  17062. * The name of the plugin.
  17063. *
  17064. * It is recommended to use reverse-domain-notation, which permits
  17065. * unique names with a known authority as well as hierarchal entries.
  17066. */
  17067. name;
  17068. /**
  17069. * Creates a new **NetworkPlugin**.
  17070. */
  17071. constructor(name) {
  17072. defineProperties(this, { name });
  17073. }
  17074. /**
  17075. * Creates a copy of this plugin.
  17076. */
  17077. clone() {
  17078. return new NetworkPlugin(this.name);
  17079. }
  17080. }
  17081. /**
  17082. * A **GasCostPlugin** allows a network to provide alternative values when
  17083. * computing the intrinsic gas required for a transaction.
  17084. */
  17085. class GasCostPlugin extends NetworkPlugin {
  17086. /**
  17087. * The block number to treat these values as valid from.
  17088. *
  17089. * This allows a hardfork to have updated values included as well as
  17090. * mulutiple hardforks to be supported.
  17091. */
  17092. effectiveBlock;
  17093. /**
  17094. * The transactions base fee.
  17095. */
  17096. txBase;
  17097. /**
  17098. * The fee for creating a new account.
  17099. */
  17100. txCreate;
  17101. /**
  17102. * The fee per zero-byte in the data.
  17103. */
  17104. txDataZero;
  17105. /**
  17106. * The fee per non-zero-byte in the data.
  17107. */
  17108. txDataNonzero;
  17109. /**
  17110. * The fee per storage key in the [[link-eip-2930]] access list.
  17111. */
  17112. txAccessListStorageKey;
  17113. /**
  17114. * The fee per address in the [[link-eip-2930]] access list.
  17115. */
  17116. txAccessListAddress;
  17117. /**
  17118. * Creates a new GasCostPlugin from %%effectiveBlock%% until the
  17119. * latest block or another GasCostPlugin supercedes that block number,
  17120. * with the associated %%costs%%.
  17121. */
  17122. constructor(effectiveBlock, costs) {
  17123. if (effectiveBlock == null) {
  17124. effectiveBlock = 0;
  17125. }
  17126. super(`org.ethers.network.plugins.GasCost#${(effectiveBlock || 0)}`);
  17127. const props = { effectiveBlock };
  17128. function set(name, nullish) {
  17129. let value = (costs || {})[name];
  17130. if (value == null) {
  17131. value = nullish;
  17132. }
  17133. assertArgument(typeof (value) === "number", `invalud value for ${name}`, "costs", costs);
  17134. props[name] = value;
  17135. }
  17136. set("txBase", 21000);
  17137. set("txCreate", 32000);
  17138. set("txDataZero", 4);
  17139. set("txDataNonzero", 16);
  17140. set("txAccessListStorageKey", 1900);
  17141. set("txAccessListAddress", 2400);
  17142. defineProperties(this, props);
  17143. }
  17144. clone() {
  17145. return new GasCostPlugin(this.effectiveBlock, this);
  17146. }
  17147. }
  17148. /**
  17149. * An **EnsPlugin** allows a [[Network]] to specify the ENS Registry
  17150. * Contract address and the target network to use when using that
  17151. * contract.
  17152. *
  17153. * Various testnets have their own instance of the contract to use, but
  17154. * in general, the mainnet instance supports multi-chain addresses and
  17155. * should be used.
  17156. */
  17157. class EnsPlugin extends NetworkPlugin {
  17158. /**
  17159. * The ENS Registrty Contract address.
  17160. */
  17161. address;
  17162. /**
  17163. * The chain ID that the ENS contract lives on.
  17164. */
  17165. targetNetwork;
  17166. /**
  17167. * Creates a new **EnsPlugin** connected to %%address%% on the
  17168. * %%targetNetwork%%. The default ENS address and mainnet is used
  17169. * if unspecified.
  17170. */
  17171. constructor(address, targetNetwork) {
  17172. super("org.ethers.plugins.network.Ens");
  17173. defineProperties(this, {
  17174. address: (address || EnsAddress),
  17175. targetNetwork: ((targetNetwork == null) ? 1 : targetNetwork)
  17176. });
  17177. }
  17178. clone() {
  17179. return new EnsPlugin(this.address, this.targetNetwork);
  17180. }
  17181. }
  17182. /**
  17183. * A **FeeDataNetworkPlugin** allows a network to provide and alternate
  17184. * means to specify its fee data.
  17185. *
  17186. * For example, a network which does not support [[link-eip-1559]] may
  17187. * choose to use a Gas Station site to approximate the gas price.
  17188. */
  17189. class FeeDataNetworkPlugin extends NetworkPlugin {
  17190. #feeDataFunc;
  17191. /**
  17192. * The fee data function provided to the constructor.
  17193. */
  17194. get feeDataFunc() {
  17195. return this.#feeDataFunc;
  17196. }
  17197. /**
  17198. * Creates a new **FeeDataNetworkPlugin**.
  17199. */
  17200. constructor(feeDataFunc) {
  17201. super("org.ethers.plugins.network.FeeData");
  17202. this.#feeDataFunc = feeDataFunc;
  17203. }
  17204. /**
  17205. * Resolves to the fee data.
  17206. */
  17207. async getFeeData(provider) {
  17208. return await this.#feeDataFunc(provider);
  17209. }
  17210. clone() {
  17211. return new FeeDataNetworkPlugin(this.#feeDataFunc);
  17212. }
  17213. }
  17214. class FetchUrlFeeDataNetworkPlugin extends NetworkPlugin {
  17215. #url;
  17216. #processFunc;
  17217. /**
  17218. * The URL to initialize the FetchRequest with in %%processFunc%%.
  17219. */
  17220. get url() { return this.#url; }
  17221. /**
  17222. * The callback to use when computing the FeeData.
  17223. */
  17224. get processFunc() { return this.#processFunc; }
  17225. /**
  17226. * Creates a new **FetchUrlFeeDataNetworkPlugin** which will
  17227. * be used when computing the fee data for the network.
  17228. */
  17229. constructor(url, processFunc) {
  17230. super("org.ethers.plugins.network.FetchUrlFeeDataPlugin");
  17231. this.#url = url;
  17232. this.#processFunc = processFunc;
  17233. }
  17234. // We are immutable, so we can serve as our own clone
  17235. clone() { return this; }
  17236. }
  17237. /*
  17238. export class CustomBlockNetworkPlugin extends NetworkPlugin {
  17239. readonly #blockFunc: (provider: Provider, block: BlockParams<string>) => Block<string>;
  17240. readonly #blockWithTxsFunc: (provider: Provider, block: BlockParams<TransactionResponseParams>) => Block<TransactionResponse>;
  17241. constructor(blockFunc: (provider: Provider, block: BlockParams<string>) => Block<string>, blockWithTxsFunc: (provider: Provider, block: BlockParams<TransactionResponseParams>) => Block<TransactionResponse>) {
  17242. super("org.ethers.network-plugins.custom-block");
  17243. this.#blockFunc = blockFunc;
  17244. this.#blockWithTxsFunc = blockWithTxsFunc;
  17245. }
  17246. async getBlock(provider: Provider, block: BlockParams<string>): Promise<Block<string>> {
  17247. return await this.#blockFunc(provider, block);
  17248. }
  17249. async getBlockions(provider: Provider, block: BlockParams<TransactionResponseParams>): Promise<Block<TransactionResponse>> {
  17250. return await this.#blockWithTxsFunc(provider, block);
  17251. }
  17252. clone(): CustomBlockNetworkPlugin {
  17253. return new CustomBlockNetworkPlugin(this.#blockFunc, this.#blockWithTxsFunc);
  17254. }
  17255. }
  17256. */
  17257. /**
  17258. * A **Network** encapsulates the various properties required to
  17259. * interact with a specific chain.
  17260. *
  17261. * @_subsection: api/providers:Networks [networks]
  17262. */
  17263. /* * * *
  17264. // Networks which operation against an L2 can use this plugin to
  17265. // specify how to access L1, for the purpose of resolving ENS,
  17266. // for example.
  17267. export class LayerOneConnectionPlugin extends NetworkPlugin {
  17268. readonly provider!: Provider;
  17269. // @TODO: Rename to ChainAccess and allow for connecting to any chain
  17270. constructor(provider: Provider) {
  17271. super("org.ethers.plugins.layer-one-connection");
  17272. defineProperties<LayerOneConnectionPlugin>(this, { provider });
  17273. }
  17274. clone(): LayerOneConnectionPlugin {
  17275. return new LayerOneConnectionPlugin(this.provider);
  17276. }
  17277. }
  17278. */
  17279. const Networks = new Map();
  17280. /**
  17281. * A **Network** provides access to a chain's properties and allows
  17282. * for plug-ins to extend functionality.
  17283. */
  17284. class Network {
  17285. #name;
  17286. #chainId;
  17287. #plugins;
  17288. /**
  17289. * Creates a new **Network** for %%name%% and %%chainId%%.
  17290. */
  17291. constructor(name, chainId) {
  17292. this.#name = name;
  17293. this.#chainId = getBigInt(chainId);
  17294. this.#plugins = new Map();
  17295. }
  17296. /**
  17297. * Returns a JSON-compatible representation of a Network.
  17298. */
  17299. toJSON() {
  17300. return { name: this.name, chainId: String(this.chainId) };
  17301. }
  17302. /**
  17303. * The network common name.
  17304. *
  17305. * This is the canonical name, as networks migh have multiple
  17306. * names.
  17307. */
  17308. get name() { return this.#name; }
  17309. set name(value) { this.#name = value; }
  17310. /**
  17311. * The network chain ID.
  17312. */
  17313. get chainId() { return this.#chainId; }
  17314. set chainId(value) { this.#chainId = getBigInt(value, "chainId"); }
  17315. /**
  17316. * Returns true if %%other%% matches this network. Any chain ID
  17317. * must match, and if no chain ID is present, the name must match.
  17318. *
  17319. * This method does not currently check for additional properties,
  17320. * such as ENS address or plug-in compatibility.
  17321. */
  17322. matches(other) {
  17323. if (other == null) {
  17324. return false;
  17325. }
  17326. if (typeof (other) === "string") {
  17327. try {
  17328. return (this.chainId === getBigInt(other));
  17329. }
  17330. catch (error) { }
  17331. return (this.name === other);
  17332. }
  17333. if (typeof (other) === "number" || typeof (other) === "bigint") {
  17334. try {
  17335. return (this.chainId === getBigInt(other));
  17336. }
  17337. catch (error) { }
  17338. return false;
  17339. }
  17340. if (typeof (other) === "object") {
  17341. if (other.chainId != null) {
  17342. try {
  17343. return (this.chainId === getBigInt(other.chainId));
  17344. }
  17345. catch (error) { }
  17346. return false;
  17347. }
  17348. if (other.name != null) {
  17349. return (this.name === other.name);
  17350. }
  17351. return false;
  17352. }
  17353. return false;
  17354. }
  17355. /**
  17356. * Returns the list of plugins currently attached to this Network.
  17357. */
  17358. get plugins() {
  17359. return Array.from(this.#plugins.values());
  17360. }
  17361. /**
  17362. * Attach a new %%plugin%% to this Network. The network name
  17363. * must be unique, excluding any fragment.
  17364. */
  17365. attachPlugin(plugin) {
  17366. if (this.#plugins.get(plugin.name)) {
  17367. throw new Error(`cannot replace existing plugin: ${plugin.name} `);
  17368. }
  17369. this.#plugins.set(plugin.name, plugin.clone());
  17370. return this;
  17371. }
  17372. /**
  17373. * Return the plugin, if any, matching %%name%% exactly. Plugins
  17374. * with fragments will not be returned unless %%name%% includes
  17375. * a fragment.
  17376. */
  17377. getPlugin(name) {
  17378. return (this.#plugins.get(name)) || null;
  17379. }
  17380. /**
  17381. * Gets a list of all plugins that match %%name%%, with otr without
  17382. * a fragment.
  17383. */
  17384. getPlugins(basename) {
  17385. return (this.plugins.filter((p) => (p.name.split("#")[0] === basename)));
  17386. }
  17387. /**
  17388. * Create a copy of this Network.
  17389. */
  17390. clone() {
  17391. const clone = new Network(this.name, this.chainId);
  17392. this.plugins.forEach((plugin) => {
  17393. clone.attachPlugin(plugin.clone());
  17394. });
  17395. return clone;
  17396. }
  17397. /**
  17398. * Compute the intrinsic gas required for a transaction.
  17399. *
  17400. * A GasCostPlugin can be attached to override the default
  17401. * values.
  17402. */
  17403. computeIntrinsicGas(tx) {
  17404. const costs = this.getPlugin("org.ethers.plugins.network.GasCost") || (new GasCostPlugin());
  17405. let gas = costs.txBase;
  17406. if (tx.to == null) {
  17407. gas += costs.txCreate;
  17408. }
  17409. if (tx.data) {
  17410. for (let i = 2; i < tx.data.length; i += 2) {
  17411. if (tx.data.substring(i, i + 2) === "00") {
  17412. gas += costs.txDataZero;
  17413. }
  17414. else {
  17415. gas += costs.txDataNonzero;
  17416. }
  17417. }
  17418. }
  17419. if (tx.accessList) {
  17420. const accessList = accessListify(tx.accessList);
  17421. for (const addr in accessList) {
  17422. gas += costs.txAccessListAddress + costs.txAccessListStorageKey * accessList[addr].storageKeys.length;
  17423. }
  17424. }
  17425. return gas;
  17426. }
  17427. /**
  17428. * Returns a new Network for the %%network%% name or chainId.
  17429. */
  17430. static from(network) {
  17431. injectCommonNetworks();
  17432. // Default network
  17433. if (network == null) {
  17434. return Network.from("mainnet");
  17435. }
  17436. // Canonical name or chain ID
  17437. if (typeof (network) === "number") {
  17438. network = BigInt(network);
  17439. }
  17440. if (typeof (network) === "string" || typeof (network) === "bigint") {
  17441. const networkFunc = Networks.get(network);
  17442. if (networkFunc) {
  17443. return networkFunc();
  17444. }
  17445. if (typeof (network) === "bigint") {
  17446. return new Network("unknown", network);
  17447. }
  17448. assertArgument(false, "unknown network", "network", network);
  17449. }
  17450. // Clonable with network-like abilities
  17451. if (typeof (network.clone) === "function") {
  17452. const clone = network.clone();
  17453. //if (typeof(network.name) !== "string" || typeof(network.chainId) !== "number") {
  17454. //}
  17455. return clone;
  17456. }
  17457. // Networkish
  17458. if (typeof (network) === "object") {
  17459. assertArgument(typeof (network.name) === "string" && typeof (network.chainId) === "number", "invalid network object name or chainId", "network", network);
  17460. const custom = new Network((network.name), (network.chainId));
  17461. if (network.ensAddress || network.ensNetwork != null) {
  17462. custom.attachPlugin(new EnsPlugin(network.ensAddress, network.ensNetwork));
  17463. }
  17464. //if ((<any>network).layerOneConnection) {
  17465. // custom.attachPlugin(new LayerOneConnectionPlugin((<any>network).layerOneConnection));
  17466. //}
  17467. return custom;
  17468. }
  17469. assertArgument(false, "invalid network", "network", network);
  17470. }
  17471. /**
  17472. * Register %%nameOrChainId%% with a function which returns
  17473. * an instance of a Network representing that chain.
  17474. */
  17475. static register(nameOrChainId, networkFunc) {
  17476. if (typeof (nameOrChainId) === "number") {
  17477. nameOrChainId = BigInt(nameOrChainId);
  17478. }
  17479. const existing = Networks.get(nameOrChainId);
  17480. if (existing) {
  17481. assertArgument(false, `conflicting network for ${JSON.stringify(existing.name)}`, "nameOrChainId", nameOrChainId);
  17482. }
  17483. Networks.set(nameOrChainId, networkFunc);
  17484. }
  17485. }
  17486. // We don't want to bring in formatUnits because it is backed by
  17487. // FixedNumber and we want to keep Networks tiny. The values
  17488. // included by the Gas Stations are also IEEE 754 with lots of
  17489. // rounding issues and exceed the strict checks formatUnits has.
  17490. function parseUnits(_value, decimals) {
  17491. const value = String(_value);
  17492. if (!value.match(/^[0-9.]+$/)) {
  17493. throw new Error(`invalid gwei value: ${_value}`);
  17494. }
  17495. // Break into [ whole, fraction ]
  17496. const comps = value.split(".");
  17497. if (comps.length === 1) {
  17498. comps.push("");
  17499. }
  17500. // More than 1 decimal point or too many fractional positions
  17501. if (comps.length !== 2) {
  17502. throw new Error(`invalid gwei value: ${_value}`);
  17503. }
  17504. // Pad the fraction to 9 decimalplaces
  17505. while (comps[1].length < decimals) {
  17506. comps[1] += "0";
  17507. }
  17508. // Too many decimals and some non-zero ending, take the ceiling
  17509. if (comps[1].length > 9) {
  17510. let frac = BigInt(comps[1].substring(0, 9));
  17511. if (!comps[1].substring(9).match(/^0+$/)) {
  17512. frac++;
  17513. }
  17514. comps[1] = frac.toString();
  17515. }
  17516. return BigInt(comps[0] + comps[1]);
  17517. }
  17518. // Used by Polygon to use a gas station for fee data
  17519. function getGasStationPlugin(url) {
  17520. return new FetchUrlFeeDataNetworkPlugin(url, async (fetchFeeData, provider, request) => {
  17521. // Prevent Cloudflare from blocking our request in node.js
  17522. request.setHeader("User-Agent", "ethers");
  17523. let response;
  17524. try {
  17525. const [_response, _feeData] = await Promise.all([
  17526. request.send(), fetchFeeData()
  17527. ]);
  17528. response = _response;
  17529. const payload = response.bodyJson.standard;
  17530. const feeData = {
  17531. gasPrice: _feeData.gasPrice,
  17532. maxFeePerGas: parseUnits(payload.maxFee, 9),
  17533. maxPriorityFeePerGas: parseUnits(payload.maxPriorityFee, 9),
  17534. };
  17535. return feeData;
  17536. }
  17537. catch (error) {
  17538. assert(false, `error encountered with polygon gas station (${JSON.stringify(request.url)})`, "SERVER_ERROR", { request, response, error });
  17539. }
  17540. });
  17541. }
  17542. // See: https://chainlist.org
  17543. let injected = false;
  17544. function injectCommonNetworks() {
  17545. if (injected) {
  17546. return;
  17547. }
  17548. injected = true;
  17549. /// Register popular Ethereum networks
  17550. function registerEth(name, chainId, options) {
  17551. const func = function () {
  17552. const network = new Network(name, chainId);
  17553. // We use 0 to disable ENS
  17554. if (options.ensNetwork != null) {
  17555. network.attachPlugin(new EnsPlugin(null, options.ensNetwork));
  17556. }
  17557. network.attachPlugin(new GasCostPlugin());
  17558. (options.plugins || []).forEach((plugin) => {
  17559. network.attachPlugin(plugin);
  17560. });
  17561. return network;
  17562. };
  17563. // Register the network by name and chain ID
  17564. Network.register(name, func);
  17565. Network.register(chainId, func);
  17566. if (options.altNames) {
  17567. options.altNames.forEach((name) => {
  17568. Network.register(name, func);
  17569. });
  17570. }
  17571. }
  17572. registerEth("mainnet", 1, { ensNetwork: 1, altNames: ["homestead"] });
  17573. registerEth("ropsten", 3, { ensNetwork: 3 });
  17574. registerEth("rinkeby", 4, { ensNetwork: 4 });
  17575. registerEth("goerli", 5, { ensNetwork: 5 });
  17576. registerEth("kovan", 42, { ensNetwork: 42 });
  17577. registerEth("sepolia", 11155111, { ensNetwork: 11155111 });
  17578. registerEth("holesky", 17000, { ensNetwork: 17000 });
  17579. registerEth("classic", 61, {});
  17580. registerEth("classicKotti", 6, {});
  17581. registerEth("arbitrum", 42161, {
  17582. ensNetwork: 1,
  17583. });
  17584. registerEth("arbitrum-goerli", 421613, {});
  17585. registerEth("arbitrum-sepolia", 421614, {});
  17586. registerEth("base", 8453, { ensNetwork: 1 });
  17587. registerEth("base-goerli", 84531, {});
  17588. registerEth("base-sepolia", 84532, {});
  17589. registerEth("bnb", 56, { ensNetwork: 1 });
  17590. registerEth("bnbt", 97, {});
  17591. registerEth("linea", 59144, { ensNetwork: 1 });
  17592. registerEth("linea-goerli", 59140, {});
  17593. registerEth("linea-sepolia", 59141, {});
  17594. registerEth("matic", 137, {
  17595. ensNetwork: 1,
  17596. plugins: [
  17597. getGasStationPlugin("https:/\/gasstation.polygon.technology/v2")
  17598. ]
  17599. });
  17600. registerEth("matic-amoy", 80002, {});
  17601. registerEth("matic-mumbai", 80001, {
  17602. altNames: ["maticMumbai", "maticmum"],
  17603. plugins: [
  17604. getGasStationPlugin("https:/\/gasstation-testnet.polygon.technology/v2")
  17605. ]
  17606. });
  17607. registerEth("optimism", 10, {
  17608. ensNetwork: 1,
  17609. plugins: []
  17610. });
  17611. registerEth("optimism-goerli", 420, {});
  17612. registerEth("optimism-sepolia", 11155420, {});
  17613. registerEth("xdai", 100, { ensNetwork: 1 });
  17614. }
  17615. function copy$2(obj) {
  17616. return JSON.parse(JSON.stringify(obj));
  17617. }
  17618. // @TODO: refactor this
  17619. /**
  17620. * A **PollingBlockSubscriber** polls at a regular interval for a change
  17621. * in the block number.
  17622. *
  17623. * @_docloc: api/providers/abstract-provider
  17624. */
  17625. class PollingBlockSubscriber {
  17626. #provider;
  17627. #poller;
  17628. #interval;
  17629. // The most recent block we have scanned for events. The value -2
  17630. // indicates we still need to fetch an initial block number
  17631. #blockNumber;
  17632. /**
  17633. * Create a new **PollingBlockSubscriber** attached to %%provider%%.
  17634. */
  17635. constructor(provider) {
  17636. this.#provider = provider;
  17637. this.#poller = null;
  17638. this.#interval = 4000;
  17639. this.#blockNumber = -2;
  17640. }
  17641. /**
  17642. * The polling interval.
  17643. */
  17644. get pollingInterval() { return this.#interval; }
  17645. set pollingInterval(value) { this.#interval = value; }
  17646. async #poll() {
  17647. try {
  17648. const blockNumber = await this.#provider.getBlockNumber();
  17649. // Bootstrap poll to setup our initial block number
  17650. if (this.#blockNumber === -2) {
  17651. this.#blockNumber = blockNumber;
  17652. return;
  17653. }
  17654. // @TODO: Put a cap on the maximum number of events per loop?
  17655. if (blockNumber !== this.#blockNumber) {
  17656. for (let b = this.#blockNumber + 1; b <= blockNumber; b++) {
  17657. // We have been stopped
  17658. if (this.#poller == null) {
  17659. return;
  17660. }
  17661. await this.#provider.emit("block", b);
  17662. }
  17663. this.#blockNumber = blockNumber;
  17664. }
  17665. }
  17666. catch (error) {
  17667. // @TODO: Minor bump, add an "error" event to let subscribers
  17668. // know things went awry.
  17669. //console.log(error);
  17670. }
  17671. // We have been stopped
  17672. if (this.#poller == null) {
  17673. return;
  17674. }
  17675. this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval);
  17676. }
  17677. start() {
  17678. if (this.#poller) {
  17679. return;
  17680. }
  17681. this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval);
  17682. this.#poll();
  17683. }
  17684. stop() {
  17685. if (!this.#poller) {
  17686. return;
  17687. }
  17688. this.#provider._clearTimeout(this.#poller);
  17689. this.#poller = null;
  17690. }
  17691. pause(dropWhilePaused) {
  17692. this.stop();
  17693. if (dropWhilePaused) {
  17694. this.#blockNumber = -2;
  17695. }
  17696. }
  17697. resume() {
  17698. this.start();
  17699. }
  17700. }
  17701. /**
  17702. * An **OnBlockSubscriber** can be sub-classed, with a [[_poll]]
  17703. * implmentation which will be called on every new block.
  17704. *
  17705. * @_docloc: api/providers/abstract-provider
  17706. */
  17707. class OnBlockSubscriber {
  17708. #provider;
  17709. #poll;
  17710. #running;
  17711. /**
  17712. * Create a new **OnBlockSubscriber** attached to %%provider%%.
  17713. */
  17714. constructor(provider) {
  17715. this.#provider = provider;
  17716. this.#running = false;
  17717. this.#poll = (blockNumber) => {
  17718. this._poll(blockNumber, this.#provider);
  17719. };
  17720. }
  17721. /**
  17722. * Called on every new block.
  17723. */
  17724. async _poll(blockNumber, provider) {
  17725. throw new Error("sub-classes must override this");
  17726. }
  17727. start() {
  17728. if (this.#running) {
  17729. return;
  17730. }
  17731. this.#running = true;
  17732. this.#poll(-2);
  17733. this.#provider.on("block", this.#poll);
  17734. }
  17735. stop() {
  17736. if (!this.#running) {
  17737. return;
  17738. }
  17739. this.#running = false;
  17740. this.#provider.off("block", this.#poll);
  17741. }
  17742. pause(dropWhilePaused) { this.stop(); }
  17743. resume() { this.start(); }
  17744. }
  17745. class PollingBlockTagSubscriber extends OnBlockSubscriber {
  17746. #tag;
  17747. #lastBlock;
  17748. constructor(provider, tag) {
  17749. super(provider);
  17750. this.#tag = tag;
  17751. this.#lastBlock = -2;
  17752. }
  17753. pause(dropWhilePaused) {
  17754. if (dropWhilePaused) {
  17755. this.#lastBlock = -2;
  17756. }
  17757. super.pause(dropWhilePaused);
  17758. }
  17759. async _poll(blockNumber, provider) {
  17760. const block = await provider.getBlock(this.#tag);
  17761. if (block == null) {
  17762. return;
  17763. }
  17764. if (this.#lastBlock === -2) {
  17765. this.#lastBlock = block.number;
  17766. }
  17767. else if (block.number > this.#lastBlock) {
  17768. provider.emit(this.#tag, block.number);
  17769. this.#lastBlock = block.number;
  17770. }
  17771. }
  17772. }
  17773. /**
  17774. * @_ignore:
  17775. *
  17776. * @_docloc: api/providers/abstract-provider
  17777. */
  17778. class PollingOrphanSubscriber extends OnBlockSubscriber {
  17779. #filter;
  17780. constructor(provider, filter) {
  17781. super(provider);
  17782. this.#filter = copy$2(filter);
  17783. }
  17784. async _poll(blockNumber, provider) {
  17785. throw new Error("@TODO");
  17786. }
  17787. }
  17788. /**
  17789. * A **PollingTransactionSubscriber** will poll for a given transaction
  17790. * hash for its receipt.
  17791. *
  17792. * @_docloc: api/providers/abstract-provider
  17793. */
  17794. class PollingTransactionSubscriber extends OnBlockSubscriber {
  17795. #hash;
  17796. /**
  17797. * Create a new **PollingTransactionSubscriber** attached to
  17798. * %%provider%%, listening for %%hash%%.
  17799. */
  17800. constructor(provider, hash) {
  17801. super(provider);
  17802. this.#hash = hash;
  17803. }
  17804. async _poll(blockNumber, provider) {
  17805. const tx = await provider.getTransactionReceipt(this.#hash);
  17806. if (tx) {
  17807. provider.emit(this.#hash, tx);
  17808. }
  17809. }
  17810. }
  17811. /**
  17812. * A **PollingEventSubscriber** will poll for a given filter for its logs.
  17813. *
  17814. * @_docloc: api/providers/abstract-provider
  17815. */
  17816. class PollingEventSubscriber {
  17817. #provider;
  17818. #filter;
  17819. #poller;
  17820. #running;
  17821. // The most recent block we have scanned for events. The value -2
  17822. // indicates we still need to fetch an initial block number
  17823. #blockNumber;
  17824. /**
  17825. * Create a new **PollingTransactionSubscriber** attached to
  17826. * %%provider%%, listening for %%filter%%.
  17827. */
  17828. constructor(provider, filter) {
  17829. this.#provider = provider;
  17830. this.#filter = copy$2(filter);
  17831. this.#poller = this.#poll.bind(this);
  17832. this.#running = false;
  17833. this.#blockNumber = -2;
  17834. }
  17835. async #poll(blockNumber) {
  17836. // The initial block hasn't been determined yet
  17837. if (this.#blockNumber === -2) {
  17838. return;
  17839. }
  17840. const filter = copy$2(this.#filter);
  17841. filter.fromBlock = this.#blockNumber + 1;
  17842. filter.toBlock = blockNumber;
  17843. const logs = await this.#provider.getLogs(filter);
  17844. // No logs could just mean the node has not indexed them yet,
  17845. // so we keep a sliding window of 60 blocks to keep scanning
  17846. if (logs.length === 0) {
  17847. if (this.#blockNumber < blockNumber - 60) {
  17848. this.#blockNumber = blockNumber - 60;
  17849. }
  17850. return;
  17851. }
  17852. for (const log of logs) {
  17853. this.#provider.emit(this.#filter, log);
  17854. // Only advance the block number when logs were found to
  17855. // account for networks (like BNB and Polygon) which may
  17856. // sacrifice event consistency for block event speed
  17857. this.#blockNumber = log.blockNumber;
  17858. }
  17859. }
  17860. start() {
  17861. if (this.#running) {
  17862. return;
  17863. }
  17864. this.#running = true;
  17865. if (this.#blockNumber === -2) {
  17866. this.#provider.getBlockNumber().then((blockNumber) => {
  17867. this.#blockNumber = blockNumber;
  17868. });
  17869. }
  17870. this.#provider.on("block", this.#poller);
  17871. }
  17872. stop() {
  17873. if (!this.#running) {
  17874. return;
  17875. }
  17876. this.#running = false;
  17877. this.#provider.off("block", this.#poller);
  17878. }
  17879. pause(dropWhilePaused) {
  17880. this.stop();
  17881. if (dropWhilePaused) {
  17882. this.#blockNumber = -2;
  17883. }
  17884. }
  17885. resume() {
  17886. this.start();
  17887. }
  17888. }
  17889. /**
  17890. * The available providers should suffice for most developers purposes,
  17891. * but the [[AbstractProvider]] class has many features which enable
  17892. * sub-classing it for specific purposes.
  17893. *
  17894. * @_section: api/providers/abstract-provider: Subclassing Provider [abstract-provider]
  17895. */
  17896. // @TODO
  17897. // Event coalescence
  17898. // When we register an event with an async value (e.g. address is a Signer
  17899. // or ENS name), we need to add it immeidately for the Event API, but also
  17900. // need time to resolve the address. Upon resolving the address, we need to
  17901. // migrate the listener to the static event. We also need to maintain a map
  17902. // of Signer/ENS name to address so we can sync respond to listenerCount.
  17903. // Constants
  17904. const BN_2$1 = BigInt(2);
  17905. const MAX_CCIP_REDIRECTS = 10;
  17906. function isPromise$1(value) {
  17907. return (value && typeof (value.then) === "function");
  17908. }
  17909. function getTag(prefix, value) {
  17910. return prefix + ":" + JSON.stringify(value, (k, v) => {
  17911. if (v == null) {
  17912. return "null";
  17913. }
  17914. if (typeof (v) === "bigint") {
  17915. return `bigint:${v.toString()}`;
  17916. }
  17917. if (typeof (v) === "string") {
  17918. return v.toLowerCase();
  17919. }
  17920. // Sort object keys
  17921. if (typeof (v) === "object" && !Array.isArray(v)) {
  17922. const keys = Object.keys(v);
  17923. keys.sort();
  17924. return keys.reduce((accum, key) => {
  17925. accum[key] = v[key];
  17926. return accum;
  17927. }, {});
  17928. }
  17929. return v;
  17930. });
  17931. }
  17932. /**
  17933. * An **UnmanagedSubscriber** is useful for events which do not require
  17934. * any additional management, such as ``"debug"`` which only requires
  17935. * emit in synchronous event loop triggered calls.
  17936. */
  17937. class UnmanagedSubscriber {
  17938. /**
  17939. * The name fof the event.
  17940. */
  17941. name;
  17942. /**
  17943. * Create a new UnmanagedSubscriber with %%name%%.
  17944. */
  17945. constructor(name) { defineProperties(this, { name }); }
  17946. start() { }
  17947. stop() { }
  17948. pause(dropWhilePaused) { }
  17949. resume() { }
  17950. }
  17951. function copy$1(value) {
  17952. return JSON.parse(JSON.stringify(value));
  17953. }
  17954. function concisify(items) {
  17955. items = Array.from((new Set(items)).values());
  17956. items.sort();
  17957. return items;
  17958. }
  17959. async function getSubscription(_event, provider) {
  17960. if (_event == null) {
  17961. throw new Error("invalid event");
  17962. }
  17963. // Normalize topic array info an EventFilter
  17964. if (Array.isArray(_event)) {
  17965. _event = { topics: _event };
  17966. }
  17967. if (typeof (_event) === "string") {
  17968. switch (_event) {
  17969. case "block":
  17970. case "debug":
  17971. case "error":
  17972. case "finalized":
  17973. case "network":
  17974. case "pending":
  17975. case "safe": {
  17976. return { type: _event, tag: _event };
  17977. }
  17978. }
  17979. }
  17980. if (isHexString(_event, 32)) {
  17981. const hash = _event.toLowerCase();
  17982. return { type: "transaction", tag: getTag("tx", { hash }), hash };
  17983. }
  17984. if (_event.orphan) {
  17985. const event = _event;
  17986. // @TODO: Should lowercase and whatnot things here instead of copy...
  17987. return { type: "orphan", tag: getTag("orphan", event), filter: copy$1(event) };
  17988. }
  17989. if ((_event.address || _event.topics)) {
  17990. const event = _event;
  17991. const filter = {
  17992. topics: ((event.topics || []).map((t) => {
  17993. if (t == null) {
  17994. return null;
  17995. }
  17996. if (Array.isArray(t)) {
  17997. return concisify(t.map((t) => t.toLowerCase()));
  17998. }
  17999. return t.toLowerCase();
  18000. }))
  18001. };
  18002. if (event.address) {
  18003. const addresses = [];
  18004. const promises = [];
  18005. const addAddress = (addr) => {
  18006. if (isHexString(addr)) {
  18007. addresses.push(addr);
  18008. }
  18009. else {
  18010. promises.push((async () => {
  18011. addresses.push(await resolveAddress(addr, provider));
  18012. })());
  18013. }
  18014. };
  18015. if (Array.isArray(event.address)) {
  18016. event.address.forEach(addAddress);
  18017. }
  18018. else {
  18019. addAddress(event.address);
  18020. }
  18021. if (promises.length) {
  18022. await Promise.all(promises);
  18023. }
  18024. filter.address = concisify(addresses.map((a) => a.toLowerCase()));
  18025. }
  18026. return { filter, tag: getTag("event", filter), type: "event" };
  18027. }
  18028. assertArgument(false, "unknown ProviderEvent", "event", _event);
  18029. }
  18030. function getTime$1() { return (new Date()).getTime(); }
  18031. const defaultOptions$1 = {
  18032. cacheTimeout: 250,
  18033. pollingInterval: 4000
  18034. };
  18035. /**
  18036. * An **AbstractProvider** provides a base class for other sub-classes to
  18037. * implement the [[Provider]] API by normalizing input arguments and
  18038. * formatting output results as well as tracking events for consistent
  18039. * behaviour on an eventually-consistent network.
  18040. */
  18041. class AbstractProvider {
  18042. #subs;
  18043. #plugins;
  18044. // null=unpaused, true=paused+dropWhilePaused, false=paused
  18045. #pausedState;
  18046. #destroyed;
  18047. #networkPromise;
  18048. #anyNetwork;
  18049. #performCache;
  18050. // The most recent block number if running an event or -1 if no "block" event
  18051. #lastBlockNumber;
  18052. #nextTimer;
  18053. #timers;
  18054. #disableCcipRead;
  18055. #options;
  18056. /**
  18057. * Create a new **AbstractProvider** connected to %%network%%, or
  18058. * use the various network detection capabilities to discover the
  18059. * [[Network]] if necessary.
  18060. */
  18061. constructor(_network, options) {
  18062. this.#options = Object.assign({}, defaultOptions$1, options || {});
  18063. if (_network === "any") {
  18064. this.#anyNetwork = true;
  18065. this.#networkPromise = null;
  18066. }
  18067. else if (_network) {
  18068. const network = Network.from(_network);
  18069. this.#anyNetwork = false;
  18070. this.#networkPromise = Promise.resolve(network);
  18071. setTimeout(() => { this.emit("network", network, null); }, 0);
  18072. }
  18073. else {
  18074. this.#anyNetwork = false;
  18075. this.#networkPromise = null;
  18076. }
  18077. this.#lastBlockNumber = -1;
  18078. this.#performCache = new Map();
  18079. this.#subs = new Map();
  18080. this.#plugins = new Map();
  18081. this.#pausedState = null;
  18082. this.#destroyed = false;
  18083. this.#nextTimer = 1;
  18084. this.#timers = new Map();
  18085. this.#disableCcipRead = false;
  18086. }
  18087. get pollingInterval() { return this.#options.pollingInterval; }
  18088. /**
  18089. * Returns ``this``, to allow an **AbstractProvider** to implement
  18090. * the [[ContractRunner]] interface.
  18091. */
  18092. get provider() { return this; }
  18093. /**
  18094. * Returns all the registered plug-ins.
  18095. */
  18096. get plugins() {
  18097. return Array.from(this.#plugins.values());
  18098. }
  18099. /**
  18100. * Attach a new plug-in.
  18101. */
  18102. attachPlugin(plugin) {
  18103. if (this.#plugins.get(plugin.name)) {
  18104. throw new Error(`cannot replace existing plugin: ${plugin.name} `);
  18105. }
  18106. this.#plugins.set(plugin.name, plugin.connect(this));
  18107. return this;
  18108. }
  18109. /**
  18110. * Get a plugin by name.
  18111. */
  18112. getPlugin(name) {
  18113. return (this.#plugins.get(name)) || null;
  18114. }
  18115. /**
  18116. * Prevent any CCIP-read operation, regardless of whether requested
  18117. * in a [[call]] using ``enableCcipRead``.
  18118. */
  18119. get disableCcipRead() { return this.#disableCcipRead; }
  18120. set disableCcipRead(value) { this.#disableCcipRead = !!value; }
  18121. // Shares multiple identical requests made during the same 250ms
  18122. async #perform(req) {
  18123. const timeout = this.#options.cacheTimeout;
  18124. // Caching disabled
  18125. if (timeout < 0) {
  18126. return await this._perform(req);
  18127. }
  18128. // Create a tag
  18129. const tag = getTag(req.method, req);
  18130. let perform = this.#performCache.get(tag);
  18131. if (!perform) {
  18132. perform = this._perform(req);
  18133. this.#performCache.set(tag, perform);
  18134. setTimeout(() => {
  18135. if (this.#performCache.get(tag) === perform) {
  18136. this.#performCache.delete(tag);
  18137. }
  18138. }, timeout);
  18139. }
  18140. return await perform;
  18141. }
  18142. /**
  18143. * Resolves to the data for executing the CCIP-read operations.
  18144. */
  18145. async ccipReadFetch(tx, calldata, urls) {
  18146. if (this.disableCcipRead || urls.length === 0 || tx.to == null) {
  18147. return null;
  18148. }
  18149. const sender = tx.to.toLowerCase();
  18150. const data = calldata.toLowerCase();
  18151. const errorMessages = [];
  18152. for (let i = 0; i < urls.length; i++) {
  18153. const url = urls[i];
  18154. // URL expansion
  18155. const href = url.replace("{sender}", sender).replace("{data}", data);
  18156. // If no {data} is present, use POST; otherwise GET
  18157. //const json: string | null = (url.indexOf("{data}") >= 0) ? null: JSON.stringify({ data, sender });
  18158. //const result = await fetchJson({ url: href, errorPassThrough: true }, json, (value, response) => {
  18159. // value.status = response.statusCode;
  18160. // return value;
  18161. //});
  18162. const request = new FetchRequest(href);
  18163. if (url.indexOf("{data}") === -1) {
  18164. request.body = { data, sender };
  18165. }
  18166. this.emit("debug", { action: "sendCcipReadFetchRequest", request, index: i, urls });
  18167. let errorMessage = "unknown error";
  18168. // Fetch the resource...
  18169. let resp;
  18170. try {
  18171. resp = await request.send();
  18172. }
  18173. catch (error) {
  18174. // ...low-level fetch error (missing host, bad SSL, etc.),
  18175. // so try next URL
  18176. errorMessages.push(error.message);
  18177. this.emit("debug", { action: "receiveCcipReadFetchError", request, result: { error } });
  18178. continue;
  18179. }
  18180. try {
  18181. const result = resp.bodyJson;
  18182. if (result.data) {
  18183. this.emit("debug", { action: "receiveCcipReadFetchResult", request, result });
  18184. return result.data;
  18185. }
  18186. if (result.message) {
  18187. errorMessage = result.message;
  18188. }
  18189. this.emit("debug", { action: "receiveCcipReadFetchError", request, result });
  18190. }
  18191. catch (error) { }
  18192. // 4xx indicates the result is not present; stop
  18193. assert(resp.statusCode < 400 || resp.statusCode >= 500, `response not found during CCIP fetch: ${errorMessage}`, "OFFCHAIN_FAULT", { reason: "404_MISSING_RESOURCE", transaction: tx, info: { url, errorMessage } });
  18194. // 5xx indicates server issue; try the next url
  18195. errorMessages.push(errorMessage);
  18196. }
  18197. assert(false, `error encountered during CCIP fetch: ${errorMessages.map((m) => JSON.stringify(m)).join(", ")}`, "OFFCHAIN_FAULT", {
  18198. reason: "500_SERVER_ERROR",
  18199. transaction: tx, info: { urls, errorMessages }
  18200. });
  18201. }
  18202. /**
  18203. * Provides the opportunity for a sub-class to wrap a block before
  18204. * returning it, to add additional properties or an alternate
  18205. * sub-class of [[Block]].
  18206. */
  18207. _wrapBlock(value, network) {
  18208. return new Block(formatBlock(value), this);
  18209. }
  18210. /**
  18211. * Provides the opportunity for a sub-class to wrap a log before
  18212. * returning it, to add additional properties or an alternate
  18213. * sub-class of [[Log]].
  18214. */
  18215. _wrapLog(value, network) {
  18216. return new Log(formatLog(value), this);
  18217. }
  18218. /**
  18219. * Provides the opportunity for a sub-class to wrap a transaction
  18220. * receipt before returning it, to add additional properties or an
  18221. * alternate sub-class of [[TransactionReceipt]].
  18222. */
  18223. _wrapTransactionReceipt(value, network) {
  18224. return new TransactionReceipt(formatTransactionReceipt(value), this);
  18225. }
  18226. /**
  18227. * Provides the opportunity for a sub-class to wrap a transaction
  18228. * response before returning it, to add additional properties or an
  18229. * alternate sub-class of [[TransactionResponse]].
  18230. */
  18231. _wrapTransactionResponse(tx, network) {
  18232. return new TransactionResponse(formatTransactionResponse(tx), this);
  18233. }
  18234. /**
  18235. * Resolves to the Network, forcing a network detection using whatever
  18236. * technique the sub-class requires.
  18237. *
  18238. * Sub-classes **must** override this.
  18239. */
  18240. _detectNetwork() {
  18241. assert(false, "sub-classes must implement this", "UNSUPPORTED_OPERATION", {
  18242. operation: "_detectNetwork"
  18243. });
  18244. }
  18245. /**
  18246. * Sub-classes should use this to perform all built-in operations. All
  18247. * methods sanitizes and normalizes the values passed into this.
  18248. *
  18249. * Sub-classes **must** override this.
  18250. */
  18251. async _perform(req) {
  18252. assert(false, `unsupported method: ${req.method}`, "UNSUPPORTED_OPERATION", {
  18253. operation: req.method,
  18254. info: req
  18255. });
  18256. }
  18257. // State
  18258. async getBlockNumber() {
  18259. const blockNumber = getNumber(await this.#perform({ method: "getBlockNumber" }), "%response");
  18260. if (this.#lastBlockNumber >= 0) {
  18261. this.#lastBlockNumber = blockNumber;
  18262. }
  18263. return blockNumber;
  18264. }
  18265. /**
  18266. * Returns or resolves to the address for %%address%%, resolving ENS
  18267. * names and [[Addressable]] objects and returning if already an
  18268. * address.
  18269. */
  18270. _getAddress(address) {
  18271. return resolveAddress(address, this);
  18272. }
  18273. /**
  18274. * Returns or resolves to a valid block tag for %%blockTag%%, resolving
  18275. * negative values and returning if already a valid block tag.
  18276. */
  18277. _getBlockTag(blockTag) {
  18278. if (blockTag == null) {
  18279. return "latest";
  18280. }
  18281. switch (blockTag) {
  18282. case "earliest":
  18283. return "0x0";
  18284. case "finalized":
  18285. case "latest":
  18286. case "pending":
  18287. case "safe":
  18288. return blockTag;
  18289. }
  18290. if (isHexString(blockTag)) {
  18291. if (isHexString(blockTag, 32)) {
  18292. return blockTag;
  18293. }
  18294. return toQuantity(blockTag);
  18295. }
  18296. if (typeof (blockTag) === "bigint") {
  18297. blockTag = getNumber(blockTag, "blockTag");
  18298. }
  18299. if (typeof (blockTag) === "number") {
  18300. if (blockTag >= 0) {
  18301. return toQuantity(blockTag);
  18302. }
  18303. if (this.#lastBlockNumber >= 0) {
  18304. return toQuantity(this.#lastBlockNumber + blockTag);
  18305. }
  18306. return this.getBlockNumber().then((b) => toQuantity(b + blockTag));
  18307. }
  18308. assertArgument(false, "invalid blockTag", "blockTag", blockTag);
  18309. }
  18310. /**
  18311. * Returns or resolves to a filter for %%filter%%, resolving any ENS
  18312. * names or [[Addressable]] object and returning if already a valid
  18313. * filter.
  18314. */
  18315. _getFilter(filter) {
  18316. // Create a canonical representation of the topics
  18317. const topics = (filter.topics || []).map((t) => {
  18318. if (t == null) {
  18319. return null;
  18320. }
  18321. if (Array.isArray(t)) {
  18322. return concisify(t.map((t) => t.toLowerCase()));
  18323. }
  18324. return t.toLowerCase();
  18325. });
  18326. const blockHash = ("blockHash" in filter) ? filter.blockHash : undefined;
  18327. const resolve = (_address, fromBlock, toBlock) => {
  18328. let address = undefined;
  18329. switch (_address.length) {
  18330. case 0: break;
  18331. case 1:
  18332. address = _address[0];
  18333. break;
  18334. default:
  18335. _address.sort();
  18336. address = _address;
  18337. }
  18338. if (blockHash) {
  18339. if (fromBlock != null || toBlock != null) {
  18340. throw new Error("invalid filter");
  18341. }
  18342. }
  18343. const filter = {};
  18344. if (address) {
  18345. filter.address = address;
  18346. }
  18347. if (topics.length) {
  18348. filter.topics = topics;
  18349. }
  18350. if (fromBlock) {
  18351. filter.fromBlock = fromBlock;
  18352. }
  18353. if (toBlock) {
  18354. filter.toBlock = toBlock;
  18355. }
  18356. if (blockHash) {
  18357. filter.blockHash = blockHash;
  18358. }
  18359. return filter;
  18360. };
  18361. // Addresses could be async (ENS names or Addressables)
  18362. let address = [];
  18363. if (filter.address) {
  18364. if (Array.isArray(filter.address)) {
  18365. for (const addr of filter.address) {
  18366. address.push(this._getAddress(addr));
  18367. }
  18368. }
  18369. else {
  18370. address.push(this._getAddress(filter.address));
  18371. }
  18372. }
  18373. let fromBlock = undefined;
  18374. if ("fromBlock" in filter) {
  18375. fromBlock = this._getBlockTag(filter.fromBlock);
  18376. }
  18377. let toBlock = undefined;
  18378. if ("toBlock" in filter) {
  18379. toBlock = this._getBlockTag(filter.toBlock);
  18380. }
  18381. if (address.filter((a) => (typeof (a) !== "string")).length ||
  18382. (fromBlock != null && typeof (fromBlock) !== "string") ||
  18383. (toBlock != null && typeof (toBlock) !== "string")) {
  18384. return Promise.all([Promise.all(address), fromBlock, toBlock]).then((result) => {
  18385. return resolve(result[0], result[1], result[2]);
  18386. });
  18387. }
  18388. return resolve(address, fromBlock, toBlock);
  18389. }
  18390. /**
  18391. * Returns or resolves to a transaction for %%request%%, resolving
  18392. * any ENS names or [[Addressable]] and returning if already a valid
  18393. * transaction.
  18394. */
  18395. _getTransactionRequest(_request) {
  18396. const request = copyRequest(_request);
  18397. const promises = [];
  18398. ["to", "from"].forEach((key) => {
  18399. if (request[key] == null) {
  18400. return;
  18401. }
  18402. const addr = resolveAddress(request[key], this);
  18403. if (isPromise$1(addr)) {
  18404. promises.push((async function () { request[key] = await addr; })());
  18405. }
  18406. else {
  18407. request[key] = addr;
  18408. }
  18409. });
  18410. if (request.blockTag != null) {
  18411. const blockTag = this._getBlockTag(request.blockTag);
  18412. if (isPromise$1(blockTag)) {
  18413. promises.push((async function () { request.blockTag = await blockTag; })());
  18414. }
  18415. else {
  18416. request.blockTag = blockTag;
  18417. }
  18418. }
  18419. if (promises.length) {
  18420. return (async function () {
  18421. await Promise.all(promises);
  18422. return request;
  18423. })();
  18424. }
  18425. return request;
  18426. }
  18427. async getNetwork() {
  18428. // No explicit network was set and this is our first time
  18429. if (this.#networkPromise == null) {
  18430. // Detect the current network (shared with all calls)
  18431. const detectNetwork = (async () => {
  18432. try {
  18433. const network = await this._detectNetwork();
  18434. this.emit("network", network, null);
  18435. return network;
  18436. }
  18437. catch (error) {
  18438. if (this.#networkPromise === detectNetwork) {
  18439. this.#networkPromise = null;
  18440. }
  18441. throw error;
  18442. }
  18443. })();
  18444. this.#networkPromise = detectNetwork;
  18445. return (await detectNetwork).clone();
  18446. }
  18447. const networkPromise = this.#networkPromise;
  18448. const [expected, actual] = await Promise.all([
  18449. networkPromise,
  18450. this._detectNetwork() // The actual connected network
  18451. ]);
  18452. if (expected.chainId !== actual.chainId) {
  18453. if (this.#anyNetwork) {
  18454. // The "any" network can change, so notify listeners
  18455. this.emit("network", actual, expected);
  18456. // Update the network if something else hasn't already changed it
  18457. if (this.#networkPromise === networkPromise) {
  18458. this.#networkPromise = Promise.resolve(actual);
  18459. }
  18460. }
  18461. else {
  18462. // Otherwise, we do not allow changes to the underlying network
  18463. assert(false, `network changed: ${expected.chainId} => ${actual.chainId} `, "NETWORK_ERROR", {
  18464. event: "changed"
  18465. });
  18466. }
  18467. }
  18468. return expected.clone();
  18469. }
  18470. async getFeeData() {
  18471. const network = await this.getNetwork();
  18472. const getFeeDataFunc = async () => {
  18473. const { _block, gasPrice, priorityFee } = await resolveProperties({
  18474. _block: this.#getBlock("latest", false),
  18475. gasPrice: ((async () => {
  18476. try {
  18477. const value = await this.#perform({ method: "getGasPrice" });
  18478. return getBigInt(value, "%response");
  18479. }
  18480. catch (error) { }
  18481. return null;
  18482. })()),
  18483. priorityFee: ((async () => {
  18484. try {
  18485. const value = await this.#perform({ method: "getPriorityFee" });
  18486. return getBigInt(value, "%response");
  18487. }
  18488. catch (error) { }
  18489. return null;
  18490. })())
  18491. });
  18492. let maxFeePerGas = null;
  18493. let maxPriorityFeePerGas = null;
  18494. // These are the recommended EIP-1559 heuristics for fee data
  18495. const block = this._wrapBlock(_block, network);
  18496. if (block && block.baseFeePerGas) {
  18497. maxPriorityFeePerGas = (priorityFee != null) ? priorityFee : BigInt("1000000000");
  18498. maxFeePerGas = (block.baseFeePerGas * BN_2$1) + maxPriorityFeePerGas;
  18499. }
  18500. return new FeeData(gasPrice, maxFeePerGas, maxPriorityFeePerGas);
  18501. };
  18502. // Check for a FeeDataNetWorkPlugin
  18503. const plugin = network.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin");
  18504. if (plugin) {
  18505. const req = new FetchRequest(plugin.url);
  18506. const feeData = await plugin.processFunc(getFeeDataFunc, this, req);
  18507. return new FeeData(feeData.gasPrice, feeData.maxFeePerGas, feeData.maxPriorityFeePerGas);
  18508. }
  18509. return await getFeeDataFunc();
  18510. }
  18511. async estimateGas(_tx) {
  18512. let tx = this._getTransactionRequest(_tx);
  18513. if (isPromise$1(tx)) {
  18514. tx = await tx;
  18515. }
  18516. return getBigInt(await this.#perform({
  18517. method: "estimateGas", transaction: tx
  18518. }), "%response");
  18519. }
  18520. async #call(tx, blockTag, attempt) {
  18521. assert(attempt < MAX_CCIP_REDIRECTS, "CCIP read exceeded maximum redirections", "OFFCHAIN_FAULT", {
  18522. reason: "TOO_MANY_REDIRECTS",
  18523. transaction: Object.assign({}, tx, { blockTag, enableCcipRead: true })
  18524. });
  18525. // This came in as a PerformActionTransaction, so to/from are safe; we can cast
  18526. const transaction = copyRequest(tx);
  18527. try {
  18528. return hexlify(await this._perform({ method: "call", transaction, blockTag }));
  18529. }
  18530. catch (error) {
  18531. // CCIP Read OffchainLookup
  18532. if (!this.disableCcipRead && isCallException(error) && error.data && attempt >= 0 && blockTag === "latest" && transaction.to != null && dataSlice(error.data, 0, 4) === "0x556f1830") {
  18533. const data = error.data;
  18534. const txSender = await resolveAddress(transaction.to, this);
  18535. // Parse the CCIP Read Arguments
  18536. let ccipArgs;
  18537. try {
  18538. ccipArgs = parseOffchainLookup(dataSlice(error.data, 4));
  18539. }
  18540. catch (error) {
  18541. assert(false, error.message, "OFFCHAIN_FAULT", {
  18542. reason: "BAD_DATA", transaction, info: { data }
  18543. });
  18544. }
  18545. // Check the sender of the OffchainLookup matches the transaction
  18546. assert(ccipArgs.sender.toLowerCase() === txSender.toLowerCase(), "CCIP Read sender mismatch", "CALL_EXCEPTION", {
  18547. action: "call",
  18548. data,
  18549. reason: "OffchainLookup",
  18550. transaction: transaction,
  18551. invocation: null,
  18552. revert: {
  18553. signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
  18554. name: "OffchainLookup",
  18555. args: ccipArgs.errorArgs
  18556. }
  18557. });
  18558. const ccipResult = await this.ccipReadFetch(transaction, ccipArgs.calldata, ccipArgs.urls);
  18559. assert(ccipResult != null, "CCIP Read failed to fetch data", "OFFCHAIN_FAULT", {
  18560. reason: "FETCH_FAILED", transaction, info: { data: error.data, errorArgs: ccipArgs.errorArgs }
  18561. });
  18562. const tx = {
  18563. to: txSender,
  18564. data: concat([ccipArgs.selector, encodeBytes([ccipResult, ccipArgs.extraData])])
  18565. };
  18566. this.emit("debug", { action: "sendCcipReadCall", transaction: tx });
  18567. try {
  18568. const result = await this.#call(tx, blockTag, attempt + 1);
  18569. this.emit("debug", { action: "receiveCcipReadCallResult", transaction: Object.assign({}, tx), result });
  18570. return result;
  18571. }
  18572. catch (error) {
  18573. this.emit("debug", { action: "receiveCcipReadCallError", transaction: Object.assign({}, tx), error });
  18574. throw error;
  18575. }
  18576. }
  18577. throw error;
  18578. }
  18579. }
  18580. async #checkNetwork(promise) {
  18581. const { value } = await resolveProperties({
  18582. network: this.getNetwork(),
  18583. value: promise
  18584. });
  18585. return value;
  18586. }
  18587. async call(_tx) {
  18588. const { tx, blockTag } = await resolveProperties({
  18589. tx: this._getTransactionRequest(_tx),
  18590. blockTag: this._getBlockTag(_tx.blockTag)
  18591. });
  18592. return await this.#checkNetwork(this.#call(tx, blockTag, _tx.enableCcipRead ? 0 : -1));
  18593. }
  18594. // Account
  18595. async #getAccountValue(request, _address, _blockTag) {
  18596. let address = this._getAddress(_address);
  18597. let blockTag = this._getBlockTag(_blockTag);
  18598. if (typeof (address) !== "string" || typeof (blockTag) !== "string") {
  18599. [address, blockTag] = await Promise.all([address, blockTag]);
  18600. }
  18601. return await this.#checkNetwork(this.#perform(Object.assign(request, { address, blockTag })));
  18602. }
  18603. async getBalance(address, blockTag) {
  18604. return getBigInt(await this.#getAccountValue({ method: "getBalance" }, address, blockTag), "%response");
  18605. }
  18606. async getTransactionCount(address, blockTag) {
  18607. return getNumber(await this.#getAccountValue({ method: "getTransactionCount" }, address, blockTag), "%response");
  18608. }
  18609. async getCode(address, blockTag) {
  18610. return hexlify(await this.#getAccountValue({ method: "getCode" }, address, blockTag));
  18611. }
  18612. async getStorage(address, _position, blockTag) {
  18613. const position = getBigInt(_position, "position");
  18614. return hexlify(await this.#getAccountValue({ method: "getStorage", position }, address, blockTag));
  18615. }
  18616. // Write
  18617. async broadcastTransaction(signedTx) {
  18618. const { blockNumber, hash, network } = await resolveProperties({
  18619. blockNumber: this.getBlockNumber(),
  18620. hash: this._perform({
  18621. method: "broadcastTransaction",
  18622. signedTransaction: signedTx
  18623. }),
  18624. network: this.getNetwork()
  18625. });
  18626. const tx = Transaction.from(signedTx);
  18627. if (tx.hash !== hash) {
  18628. throw new Error("@TODO: the returned hash did not match");
  18629. }
  18630. return this._wrapTransactionResponse(tx, network).replaceableTransaction(blockNumber);
  18631. }
  18632. async #getBlock(block, includeTransactions) {
  18633. // @TODO: Add CustomBlockPlugin check
  18634. if (isHexString(block, 32)) {
  18635. return await this.#perform({
  18636. method: "getBlock", blockHash: block, includeTransactions
  18637. });
  18638. }
  18639. let blockTag = this._getBlockTag(block);
  18640. if (typeof (blockTag) !== "string") {
  18641. blockTag = await blockTag;
  18642. }
  18643. return await this.#perform({
  18644. method: "getBlock", blockTag, includeTransactions
  18645. });
  18646. }
  18647. // Queries
  18648. async getBlock(block, prefetchTxs) {
  18649. const { network, params } = await resolveProperties({
  18650. network: this.getNetwork(),
  18651. params: this.#getBlock(block, !!prefetchTxs)
  18652. });
  18653. if (params == null) {
  18654. return null;
  18655. }
  18656. return this._wrapBlock(params, network);
  18657. }
  18658. async getTransaction(hash) {
  18659. const { network, params } = await resolveProperties({
  18660. network: this.getNetwork(),
  18661. params: this.#perform({ method: "getTransaction", hash })
  18662. });
  18663. if (params == null) {
  18664. return null;
  18665. }
  18666. return this._wrapTransactionResponse(params, network);
  18667. }
  18668. async getTransactionReceipt(hash) {
  18669. const { network, params } = await resolveProperties({
  18670. network: this.getNetwork(),
  18671. params: this.#perform({ method: "getTransactionReceipt", hash })
  18672. });
  18673. if (params == null) {
  18674. return null;
  18675. }
  18676. // Some backends did not backfill the effectiveGasPrice into old transactions
  18677. // in the receipt, so we look it up manually and inject it.
  18678. if (params.gasPrice == null && params.effectiveGasPrice == null) {
  18679. const tx = await this.#perform({ method: "getTransaction", hash });
  18680. if (tx == null) {
  18681. throw new Error("report this; could not find tx or effectiveGasPrice");
  18682. }
  18683. params.effectiveGasPrice = tx.gasPrice;
  18684. }
  18685. return this._wrapTransactionReceipt(params, network);
  18686. }
  18687. async getTransactionResult(hash) {
  18688. const { result } = await resolveProperties({
  18689. network: this.getNetwork(),
  18690. result: this.#perform({ method: "getTransactionResult", hash })
  18691. });
  18692. if (result == null) {
  18693. return null;
  18694. }
  18695. return hexlify(result);
  18696. }
  18697. // Bloom-filter Queries
  18698. async getLogs(_filter) {
  18699. let filter = this._getFilter(_filter);
  18700. if (isPromise$1(filter)) {
  18701. filter = await filter;
  18702. }
  18703. const { network, params } = await resolveProperties({
  18704. network: this.getNetwork(),
  18705. params: this.#perform({ method: "getLogs", filter })
  18706. });
  18707. return params.map((p) => this._wrapLog(p, network));
  18708. }
  18709. // ENS
  18710. _getProvider(chainId) {
  18711. assert(false, "provider cannot connect to target network", "UNSUPPORTED_OPERATION", {
  18712. operation: "_getProvider()"
  18713. });
  18714. }
  18715. async getResolver(name) {
  18716. return await EnsResolver.fromName(this, name);
  18717. }
  18718. async getAvatar(name) {
  18719. const resolver = await this.getResolver(name);
  18720. if (resolver) {
  18721. return await resolver.getAvatar();
  18722. }
  18723. return null;
  18724. }
  18725. async resolveName(name) {
  18726. const resolver = await this.getResolver(name);
  18727. if (resolver) {
  18728. return await resolver.getAddress();
  18729. }
  18730. return null;
  18731. }
  18732. async lookupAddress(address) {
  18733. address = getAddress(address);
  18734. const node = namehash(address.substring(2).toLowerCase() + ".addr.reverse");
  18735. try {
  18736. const ensAddr = await EnsResolver.getEnsAddress(this);
  18737. const ensContract = new Contract(ensAddr, [
  18738. "function resolver(bytes32) view returns (address)"
  18739. ], this);
  18740. const resolver = await ensContract.resolver(node);
  18741. if (resolver == null || resolver === ZeroAddress) {
  18742. return null;
  18743. }
  18744. const resolverContract = new Contract(resolver, [
  18745. "function name(bytes32) view returns (string)"
  18746. ], this);
  18747. const name = await resolverContract.name(node);
  18748. // Failed forward resolution
  18749. const check = await this.resolveName(name);
  18750. if (check !== address) {
  18751. return null;
  18752. }
  18753. return name;
  18754. }
  18755. catch (error) {
  18756. // No data was returned from the resolver
  18757. if (isError(error, "BAD_DATA") && error.value === "0x") {
  18758. return null;
  18759. }
  18760. // Something reerted
  18761. if (isError(error, "CALL_EXCEPTION")) {
  18762. return null;
  18763. }
  18764. throw error;
  18765. }
  18766. return null;
  18767. }
  18768. async waitForTransaction(hash, _confirms, timeout) {
  18769. const confirms = (_confirms != null) ? _confirms : 1;
  18770. if (confirms === 0) {
  18771. return this.getTransactionReceipt(hash);
  18772. }
  18773. return new Promise(async (resolve, reject) => {
  18774. let timer = null;
  18775. const listener = (async (blockNumber) => {
  18776. try {
  18777. const receipt = await this.getTransactionReceipt(hash);
  18778. if (receipt != null) {
  18779. if (blockNumber - receipt.blockNumber + 1 >= confirms) {
  18780. resolve(receipt);
  18781. //this.off("block", listener);
  18782. if (timer) {
  18783. clearTimeout(timer);
  18784. timer = null;
  18785. }
  18786. return;
  18787. }
  18788. }
  18789. }
  18790. catch (error) {
  18791. console.log("EEE", error);
  18792. }
  18793. this.once("block", listener);
  18794. });
  18795. if (timeout != null) {
  18796. timer = setTimeout(() => {
  18797. if (timer == null) {
  18798. return;
  18799. }
  18800. timer = null;
  18801. this.off("block", listener);
  18802. reject(makeError("timeout", "TIMEOUT", { reason: "timeout" }));
  18803. }, timeout);
  18804. }
  18805. listener(await this.getBlockNumber());
  18806. });
  18807. }
  18808. async waitForBlock(blockTag) {
  18809. assert(false, "not implemented yet", "NOT_IMPLEMENTED", {
  18810. operation: "waitForBlock"
  18811. });
  18812. }
  18813. /**
  18814. * Clear a timer created using the [[_setTimeout]] method.
  18815. */
  18816. _clearTimeout(timerId) {
  18817. const timer = this.#timers.get(timerId);
  18818. if (!timer) {
  18819. return;
  18820. }
  18821. if (timer.timer) {
  18822. clearTimeout(timer.timer);
  18823. }
  18824. this.#timers.delete(timerId);
  18825. }
  18826. /**
  18827. * Create a timer that will execute %%func%% after at least %%timeout%%
  18828. * (in ms). If %%timeout%% is unspecified, then %%func%% will execute
  18829. * in the next event loop.
  18830. *
  18831. * [Pausing](AbstractProvider-paused) the provider will pause any
  18832. * associated timers.
  18833. */
  18834. _setTimeout(_func, timeout) {
  18835. if (timeout == null) {
  18836. timeout = 0;
  18837. }
  18838. const timerId = this.#nextTimer++;
  18839. const func = () => {
  18840. this.#timers.delete(timerId);
  18841. _func();
  18842. };
  18843. if (this.paused) {
  18844. this.#timers.set(timerId, { timer: null, func, time: timeout });
  18845. }
  18846. else {
  18847. const timer = setTimeout(func, timeout);
  18848. this.#timers.set(timerId, { timer, func, time: getTime$1() });
  18849. }
  18850. return timerId;
  18851. }
  18852. /**
  18853. * Perform %%func%% on each subscriber.
  18854. */
  18855. _forEachSubscriber(func) {
  18856. for (const sub of this.#subs.values()) {
  18857. func(sub.subscriber);
  18858. }
  18859. }
  18860. /**
  18861. * Sub-classes may override this to customize subscription
  18862. * implementations.
  18863. */
  18864. _getSubscriber(sub) {
  18865. switch (sub.type) {
  18866. case "debug":
  18867. case "error":
  18868. case "network":
  18869. return new UnmanagedSubscriber(sub.type);
  18870. case "block": {
  18871. const subscriber = new PollingBlockSubscriber(this);
  18872. subscriber.pollingInterval = this.pollingInterval;
  18873. return subscriber;
  18874. }
  18875. case "safe":
  18876. case "finalized":
  18877. return new PollingBlockTagSubscriber(this, sub.type);
  18878. case "event":
  18879. return new PollingEventSubscriber(this, sub.filter);
  18880. case "transaction":
  18881. return new PollingTransactionSubscriber(this, sub.hash);
  18882. case "orphan":
  18883. return new PollingOrphanSubscriber(this, sub.filter);
  18884. }
  18885. throw new Error(`unsupported event: ${sub.type}`);
  18886. }
  18887. /**
  18888. * If a [[Subscriber]] fails and needs to replace itself, this
  18889. * method may be used.
  18890. *
  18891. * For example, this is used for providers when using the
  18892. * ``eth_getFilterChanges`` method, which can return null if state
  18893. * filters are not supported by the backend, allowing the Subscriber
  18894. * to swap in a [[PollingEventSubscriber]].
  18895. */
  18896. _recoverSubscriber(oldSub, newSub) {
  18897. for (const sub of this.#subs.values()) {
  18898. if (sub.subscriber === oldSub) {
  18899. if (sub.started) {
  18900. sub.subscriber.stop();
  18901. }
  18902. sub.subscriber = newSub;
  18903. if (sub.started) {
  18904. newSub.start();
  18905. }
  18906. if (this.#pausedState != null) {
  18907. newSub.pause(this.#pausedState);
  18908. }
  18909. break;
  18910. }
  18911. }
  18912. }
  18913. async #hasSub(event, emitArgs) {
  18914. let sub = await getSubscription(event, this);
  18915. // This is a log that is removing an existing log; we actually want
  18916. // to emit an orphan event for the removed log
  18917. if (sub.type === "event" && emitArgs && emitArgs.length > 0 && emitArgs[0].removed === true) {
  18918. sub = await getSubscription({ orphan: "drop-log", log: emitArgs[0] }, this);
  18919. }
  18920. return this.#subs.get(sub.tag) || null;
  18921. }
  18922. async #getSub(event) {
  18923. const subscription = await getSubscription(event, this);
  18924. // Prevent tampering with our tag in any subclass' _getSubscriber
  18925. const tag = subscription.tag;
  18926. let sub = this.#subs.get(tag);
  18927. if (!sub) {
  18928. const subscriber = this._getSubscriber(subscription);
  18929. const addressableMap = new WeakMap();
  18930. const nameMap = new Map();
  18931. sub = { subscriber, tag, addressableMap, nameMap, started: false, listeners: [] };
  18932. this.#subs.set(tag, sub);
  18933. }
  18934. return sub;
  18935. }
  18936. async on(event, listener) {
  18937. const sub = await this.#getSub(event);
  18938. sub.listeners.push({ listener, once: false });
  18939. if (!sub.started) {
  18940. sub.subscriber.start();
  18941. sub.started = true;
  18942. if (this.#pausedState != null) {
  18943. sub.subscriber.pause(this.#pausedState);
  18944. }
  18945. }
  18946. return this;
  18947. }
  18948. async once(event, listener) {
  18949. const sub = await this.#getSub(event);
  18950. sub.listeners.push({ listener, once: true });
  18951. if (!sub.started) {
  18952. sub.subscriber.start();
  18953. sub.started = true;
  18954. if (this.#pausedState != null) {
  18955. sub.subscriber.pause(this.#pausedState);
  18956. }
  18957. }
  18958. return this;
  18959. }
  18960. async emit(event, ...args) {
  18961. const sub = await this.#hasSub(event, args);
  18962. // If there is not subscription or if a recent emit removed
  18963. // the last of them (which also deleted the sub) do nothing
  18964. if (!sub || sub.listeners.length === 0) {
  18965. return false;
  18966. }
  18967. const count = sub.listeners.length;
  18968. sub.listeners = sub.listeners.filter(({ listener, once }) => {
  18969. const payload = new EventPayload(this, (once ? null : listener), event);
  18970. try {
  18971. listener.call(this, ...args, payload);
  18972. }
  18973. catch (error) { }
  18974. return !once;
  18975. });
  18976. if (sub.listeners.length === 0) {
  18977. if (sub.started) {
  18978. sub.subscriber.stop();
  18979. }
  18980. this.#subs.delete(sub.tag);
  18981. }
  18982. return (count > 0);
  18983. }
  18984. async listenerCount(event) {
  18985. if (event) {
  18986. const sub = await this.#hasSub(event);
  18987. if (!sub) {
  18988. return 0;
  18989. }
  18990. return sub.listeners.length;
  18991. }
  18992. let total = 0;
  18993. for (const { listeners } of this.#subs.values()) {
  18994. total += listeners.length;
  18995. }
  18996. return total;
  18997. }
  18998. async listeners(event) {
  18999. if (event) {
  19000. const sub = await this.#hasSub(event);
  19001. if (!sub) {
  19002. return [];
  19003. }
  19004. return sub.listeners.map(({ listener }) => listener);
  19005. }
  19006. let result = [];
  19007. for (const { listeners } of this.#subs.values()) {
  19008. result = result.concat(listeners.map(({ listener }) => listener));
  19009. }
  19010. return result;
  19011. }
  19012. async off(event, listener) {
  19013. const sub = await this.#hasSub(event);
  19014. if (!sub) {
  19015. return this;
  19016. }
  19017. if (listener) {
  19018. const index = sub.listeners.map(({ listener }) => listener).indexOf(listener);
  19019. if (index >= 0) {
  19020. sub.listeners.splice(index, 1);
  19021. }
  19022. }
  19023. if (!listener || sub.listeners.length === 0) {
  19024. if (sub.started) {
  19025. sub.subscriber.stop();
  19026. }
  19027. this.#subs.delete(sub.tag);
  19028. }
  19029. return this;
  19030. }
  19031. async removeAllListeners(event) {
  19032. if (event) {
  19033. const { tag, started, subscriber } = await this.#getSub(event);
  19034. if (started) {
  19035. subscriber.stop();
  19036. }
  19037. this.#subs.delete(tag);
  19038. }
  19039. else {
  19040. for (const [tag, { started, subscriber }] of this.#subs) {
  19041. if (started) {
  19042. subscriber.stop();
  19043. }
  19044. this.#subs.delete(tag);
  19045. }
  19046. }
  19047. return this;
  19048. }
  19049. // Alias for "on"
  19050. async addListener(event, listener) {
  19051. return await this.on(event, listener);
  19052. }
  19053. // Alias for "off"
  19054. async removeListener(event, listener) {
  19055. return this.off(event, listener);
  19056. }
  19057. /**
  19058. * If this provider has been destroyed using the [[destroy]] method.
  19059. *
  19060. * Once destroyed, all resources are reclaimed, internal event loops
  19061. * and timers are cleaned up and no further requests may be sent to
  19062. * the provider.
  19063. */
  19064. get destroyed() {
  19065. return this.#destroyed;
  19066. }
  19067. /**
  19068. * Sub-classes may use this to shutdown any sockets or release their
  19069. * resources and reject any pending requests.
  19070. *
  19071. * Sub-classes **must** call ``super.destroy()``.
  19072. */
  19073. destroy() {
  19074. // Stop all listeners
  19075. this.removeAllListeners();
  19076. // Shut down all tiemrs
  19077. for (const timerId of this.#timers.keys()) {
  19078. this._clearTimeout(timerId);
  19079. }
  19080. this.#destroyed = true;
  19081. }
  19082. /**
  19083. * Whether the provider is currently paused.
  19084. *
  19085. * A paused provider will not emit any events, and generally should
  19086. * not make any requests to the network, but that is up to sub-classes
  19087. * to manage.
  19088. *
  19089. * Setting ``paused = true`` is identical to calling ``.pause(false)``,
  19090. * which will buffer any events that occur while paused until the
  19091. * provider is unpaused.
  19092. */
  19093. get paused() { return (this.#pausedState != null); }
  19094. set paused(pause) {
  19095. if (!!pause === this.paused) {
  19096. return;
  19097. }
  19098. if (this.paused) {
  19099. this.resume();
  19100. }
  19101. else {
  19102. this.pause(false);
  19103. }
  19104. }
  19105. /**
  19106. * Pause the provider. If %%dropWhilePaused%%, any events that occur
  19107. * while paused are dropped, otherwise all events will be emitted once
  19108. * the provider is unpaused.
  19109. */
  19110. pause(dropWhilePaused) {
  19111. this.#lastBlockNumber = -1;
  19112. if (this.#pausedState != null) {
  19113. if (this.#pausedState == !!dropWhilePaused) {
  19114. return;
  19115. }
  19116. assert(false, "cannot change pause type; resume first", "UNSUPPORTED_OPERATION", {
  19117. operation: "pause"
  19118. });
  19119. }
  19120. this._forEachSubscriber((s) => s.pause(dropWhilePaused));
  19121. this.#pausedState = !!dropWhilePaused;
  19122. for (const timer of this.#timers.values()) {
  19123. // Clear the timer
  19124. if (timer.timer) {
  19125. clearTimeout(timer.timer);
  19126. }
  19127. // Remaining time needed for when we become unpaused
  19128. timer.time = getTime$1() - timer.time;
  19129. }
  19130. }
  19131. /**
  19132. * Resume the provider.
  19133. */
  19134. resume() {
  19135. if (this.#pausedState == null) {
  19136. return;
  19137. }
  19138. this._forEachSubscriber((s) => s.resume());
  19139. this.#pausedState = null;
  19140. for (const timer of this.#timers.values()) {
  19141. // Remaining time when we were paused
  19142. let timeout = timer.time;
  19143. if (timeout < 0) {
  19144. timeout = 0;
  19145. }
  19146. // Start time (in cause paused, so we con compute remaininf time)
  19147. timer.time = getTime$1();
  19148. // Start the timer
  19149. setTimeout(timer.func, timeout);
  19150. }
  19151. }
  19152. }
  19153. function _parseString(result, start) {
  19154. try {
  19155. const bytes = _parseBytes(result, start);
  19156. if (bytes) {
  19157. return toUtf8String(bytes);
  19158. }
  19159. }
  19160. catch (error) { }
  19161. return null;
  19162. }
  19163. function _parseBytes(result, start) {
  19164. if (result === "0x") {
  19165. return null;
  19166. }
  19167. try {
  19168. const offset = getNumber(dataSlice(result, start, start + 32));
  19169. const length = getNumber(dataSlice(result, offset, offset + 32));
  19170. return dataSlice(result, offset + 32, offset + 32 + length);
  19171. }
  19172. catch (error) { }
  19173. return null;
  19174. }
  19175. function numPad(value) {
  19176. const result = toBeArray(value);
  19177. if (result.length > 32) {
  19178. throw new Error("internal; should not happen");
  19179. }
  19180. const padded = new Uint8Array(32);
  19181. padded.set(result, 32 - result.length);
  19182. return padded;
  19183. }
  19184. function bytesPad(value) {
  19185. if ((value.length % 32) === 0) {
  19186. return value;
  19187. }
  19188. const result = new Uint8Array(Math.ceil(value.length / 32) * 32);
  19189. result.set(value);
  19190. return result;
  19191. }
  19192. const empty = new Uint8Array([]);
  19193. // ABI Encodes a series of (bytes, bytes, ...)
  19194. function encodeBytes(datas) {
  19195. const result = [];
  19196. let byteCount = 0;
  19197. // Add place-holders for pointers as we add items
  19198. for (let i = 0; i < datas.length; i++) {
  19199. result.push(empty);
  19200. byteCount += 32;
  19201. }
  19202. for (let i = 0; i < datas.length; i++) {
  19203. const data = getBytes(datas[i]);
  19204. // Update the bytes offset
  19205. result[i] = numPad(byteCount);
  19206. // The length and padded value of data
  19207. result.push(numPad(data.length));
  19208. result.push(bytesPad(data));
  19209. byteCount += 32 + Math.ceil(data.length / 32) * 32;
  19210. }
  19211. return concat(result);
  19212. }
  19213. const zeros = "0x0000000000000000000000000000000000000000000000000000000000000000";
  19214. function parseOffchainLookup(data) {
  19215. const result = {
  19216. sender: "", urls: [], calldata: "", selector: "", extraData: "", errorArgs: []
  19217. };
  19218. assert(dataLength(data) >= 5 * 32, "insufficient OffchainLookup data", "OFFCHAIN_FAULT", {
  19219. reason: "insufficient OffchainLookup data"
  19220. });
  19221. const sender = dataSlice(data, 0, 32);
  19222. assert(dataSlice(sender, 0, 12) === dataSlice(zeros, 0, 12), "corrupt OffchainLookup sender", "OFFCHAIN_FAULT", {
  19223. reason: "corrupt OffchainLookup sender"
  19224. });
  19225. result.sender = dataSlice(sender, 12);
  19226. // Read the URLs from the response
  19227. try {
  19228. const urls = [];
  19229. const urlsOffset = getNumber(dataSlice(data, 32, 64));
  19230. const urlsLength = getNumber(dataSlice(data, urlsOffset, urlsOffset + 32));
  19231. const urlsData = dataSlice(data, urlsOffset + 32);
  19232. for (let u = 0; u < urlsLength; u++) {
  19233. const url = _parseString(urlsData, u * 32);
  19234. if (url == null) {
  19235. throw new Error("abort");
  19236. }
  19237. urls.push(url);
  19238. }
  19239. result.urls = urls;
  19240. }
  19241. catch (error) {
  19242. assert(false, "corrupt OffchainLookup urls", "OFFCHAIN_FAULT", {
  19243. reason: "corrupt OffchainLookup urls"
  19244. });
  19245. }
  19246. // Get the CCIP calldata to forward
  19247. try {
  19248. const calldata = _parseBytes(data, 64);
  19249. if (calldata == null) {
  19250. throw new Error("abort");
  19251. }
  19252. result.calldata = calldata;
  19253. }
  19254. catch (error) {
  19255. assert(false, "corrupt OffchainLookup calldata", "OFFCHAIN_FAULT", {
  19256. reason: "corrupt OffchainLookup calldata"
  19257. });
  19258. }
  19259. // Get the callbackSelector (bytes4)
  19260. assert(dataSlice(data, 100, 128) === dataSlice(zeros, 0, 28), "corrupt OffchainLookup callbaackSelector", "OFFCHAIN_FAULT", {
  19261. reason: "corrupt OffchainLookup callbaackSelector"
  19262. });
  19263. result.selector = dataSlice(data, 96, 100);
  19264. // Get the extra data to send back to the contract as context
  19265. try {
  19266. const extraData = _parseBytes(data, 128);
  19267. if (extraData == null) {
  19268. throw new Error("abort");
  19269. }
  19270. result.extraData = extraData;
  19271. }
  19272. catch (error) {
  19273. assert(false, "corrupt OffchainLookup extraData", "OFFCHAIN_FAULT", {
  19274. reason: "corrupt OffchainLookup extraData"
  19275. });
  19276. }
  19277. result.errorArgs = "sender,urls,calldata,selector,extraData".split(/,/).map((k) => result[k]);
  19278. return result;
  19279. }
  19280. /**
  19281. * Generally the [[Wallet]] and [[JsonRpcSigner]] and their sub-classes
  19282. * are sufficent for most developers, but this is provided to
  19283. * fascilitate more complex Signers.
  19284. *
  19285. * @_section: api/providers/abstract-signer: Subclassing Signer [abstract-signer]
  19286. */
  19287. function checkProvider(signer, operation) {
  19288. if (signer.provider) {
  19289. return signer.provider;
  19290. }
  19291. assert(false, "missing provider", "UNSUPPORTED_OPERATION", { operation });
  19292. }
  19293. async function populate(signer, tx) {
  19294. let pop = copyRequest(tx);
  19295. if (pop.to != null) {
  19296. pop.to = resolveAddress(pop.to, signer);
  19297. }
  19298. if (pop.from != null) {
  19299. const from = pop.from;
  19300. pop.from = Promise.all([
  19301. signer.getAddress(),
  19302. resolveAddress(from, signer)
  19303. ]).then(([address, from]) => {
  19304. assertArgument(address.toLowerCase() === from.toLowerCase(), "transaction from mismatch", "tx.from", from);
  19305. return address;
  19306. });
  19307. }
  19308. else {
  19309. pop.from = signer.getAddress();
  19310. }
  19311. return await resolveProperties(pop);
  19312. }
  19313. /**
  19314. * An **AbstractSigner** includes most of teh functionality required
  19315. * to get a [[Signer]] working as expected, but requires a few
  19316. * Signer-specific methods be overridden.
  19317. *
  19318. */
  19319. class AbstractSigner {
  19320. /**
  19321. * The provider this signer is connected to.
  19322. */
  19323. provider;
  19324. /**
  19325. * Creates a new Signer connected to %%provider%%.
  19326. */
  19327. constructor(provider) {
  19328. defineProperties(this, { provider: (provider || null) });
  19329. }
  19330. async getNonce(blockTag) {
  19331. return checkProvider(this, "getTransactionCount").getTransactionCount(await this.getAddress(), blockTag);
  19332. }
  19333. async populateCall(tx) {
  19334. const pop = await populate(this, tx);
  19335. return pop;
  19336. }
  19337. async populateTransaction(tx) {
  19338. const provider = checkProvider(this, "populateTransaction");
  19339. const pop = await populate(this, tx);
  19340. if (pop.nonce == null) {
  19341. pop.nonce = await this.getNonce("pending");
  19342. }
  19343. if (pop.gasLimit == null) {
  19344. pop.gasLimit = await this.estimateGas(pop);
  19345. }
  19346. // Populate the chain ID
  19347. const network = await (this.provider).getNetwork();
  19348. if (pop.chainId != null) {
  19349. const chainId = getBigInt(pop.chainId);
  19350. assertArgument(chainId === network.chainId, "transaction chainId mismatch", "tx.chainId", tx.chainId);
  19351. }
  19352. else {
  19353. pop.chainId = network.chainId;
  19354. }
  19355. // Do not allow mixing pre-eip-1559 and eip-1559 properties
  19356. const hasEip1559 = (pop.maxFeePerGas != null || pop.maxPriorityFeePerGas != null);
  19357. if (pop.gasPrice != null && (pop.type === 2 || hasEip1559)) {
  19358. assertArgument(false, "eip-1559 transaction do not support gasPrice", "tx", tx);
  19359. }
  19360. else if ((pop.type === 0 || pop.type === 1) && hasEip1559) {
  19361. assertArgument(false, "pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas", "tx", tx);
  19362. }
  19363. if ((pop.type === 2 || pop.type == null) && (pop.maxFeePerGas != null && pop.maxPriorityFeePerGas != null)) {
  19364. // Fully-formed EIP-1559 transaction (skip getFeeData)
  19365. pop.type = 2;
  19366. }
  19367. else if (pop.type === 0 || pop.type === 1) {
  19368. // Explicit Legacy or EIP-2930 transaction
  19369. // We need to get fee data to determine things
  19370. const feeData = await provider.getFeeData();
  19371. assert(feeData.gasPrice != null, "network does not support gasPrice", "UNSUPPORTED_OPERATION", {
  19372. operation: "getGasPrice"
  19373. });
  19374. // Populate missing gasPrice
  19375. if (pop.gasPrice == null) {
  19376. pop.gasPrice = feeData.gasPrice;
  19377. }
  19378. }
  19379. else {
  19380. // We need to get fee data to determine things
  19381. const feeData = await provider.getFeeData();
  19382. if (pop.type == null) {
  19383. // We need to auto-detect the intended type of this transaction...
  19384. if (feeData.maxFeePerGas != null && feeData.maxPriorityFeePerGas != null) {
  19385. // The network supports EIP-1559!
  19386. // Upgrade transaction from null to eip-1559
  19387. pop.type = 2;
  19388. if (pop.gasPrice != null) {
  19389. // Using legacy gasPrice property on an eip-1559 network,
  19390. // so use gasPrice as both fee properties
  19391. const gasPrice = pop.gasPrice;
  19392. delete pop.gasPrice;
  19393. pop.maxFeePerGas = gasPrice;
  19394. pop.maxPriorityFeePerGas = gasPrice;
  19395. }
  19396. else {
  19397. // Populate missing fee data
  19398. if (pop.maxFeePerGas == null) {
  19399. pop.maxFeePerGas = feeData.maxFeePerGas;
  19400. }
  19401. if (pop.maxPriorityFeePerGas == null) {
  19402. pop.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas;
  19403. }
  19404. }
  19405. }
  19406. else if (feeData.gasPrice != null) {
  19407. // Network doesn't support EIP-1559...
  19408. // ...but they are trying to use EIP-1559 properties
  19409. assert(!hasEip1559, "network does not support EIP-1559", "UNSUPPORTED_OPERATION", {
  19410. operation: "populateTransaction"
  19411. });
  19412. // Populate missing fee data
  19413. if (pop.gasPrice == null) {
  19414. pop.gasPrice = feeData.gasPrice;
  19415. }
  19416. // Explicitly set untyped transaction to legacy
  19417. // @TODO: Maybe this shold allow type 1?
  19418. pop.type = 0;
  19419. }
  19420. else {
  19421. // getFeeData has failed us.
  19422. assert(false, "failed to get consistent fee data", "UNSUPPORTED_OPERATION", {
  19423. operation: "signer.getFeeData"
  19424. });
  19425. }
  19426. }
  19427. else if (pop.type === 2 || pop.type === 3) {
  19428. // Explicitly using EIP-1559 or EIP-4844
  19429. // Populate missing fee data
  19430. if (pop.maxFeePerGas == null) {
  19431. pop.maxFeePerGas = feeData.maxFeePerGas;
  19432. }
  19433. if (pop.maxPriorityFeePerGas == null) {
  19434. pop.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas;
  19435. }
  19436. }
  19437. }
  19438. //@TOOD: Don't await all over the place; save them up for
  19439. // the end for better batching
  19440. return await resolveProperties(pop);
  19441. }
  19442. async estimateGas(tx) {
  19443. return checkProvider(this, "estimateGas").estimateGas(await this.populateCall(tx));
  19444. }
  19445. async call(tx) {
  19446. return checkProvider(this, "call").call(await this.populateCall(tx));
  19447. }
  19448. async resolveName(name) {
  19449. const provider = checkProvider(this, "resolveName");
  19450. return await provider.resolveName(name);
  19451. }
  19452. async sendTransaction(tx) {
  19453. const provider = checkProvider(this, "sendTransaction");
  19454. const pop = await this.populateTransaction(tx);
  19455. delete pop.from;
  19456. const txObj = Transaction.from(pop);
  19457. return await provider.broadcastTransaction(await this.signTransaction(txObj));
  19458. }
  19459. }
  19460. /**
  19461. * A **VoidSigner** is a class deisgned to allow an address to be used
  19462. * in any API which accepts a Signer, but for which there are no
  19463. * credentials available to perform any actual signing.
  19464. *
  19465. * This for example allow impersonating an account for the purpose of
  19466. * static calls or estimating gas, but does not allow sending transactions.
  19467. */
  19468. class VoidSigner extends AbstractSigner {
  19469. /**
  19470. * The signer address.
  19471. */
  19472. address;
  19473. /**
  19474. * Creates a new **VoidSigner** with %%address%% attached to
  19475. * %%provider%%.
  19476. */
  19477. constructor(address, provider) {
  19478. super(provider);
  19479. defineProperties(this, { address });
  19480. }
  19481. async getAddress() { return this.address; }
  19482. connect(provider) {
  19483. return new VoidSigner(this.address, provider);
  19484. }
  19485. #throwUnsupported(suffix, operation) {
  19486. assert(false, `VoidSigner cannot sign ${suffix}`, "UNSUPPORTED_OPERATION", { operation });
  19487. }
  19488. async signTransaction(tx) {
  19489. this.#throwUnsupported("transactions", "signTransaction");
  19490. }
  19491. async signMessage(message) {
  19492. this.#throwUnsupported("messages", "signMessage");
  19493. }
  19494. async signTypedData(domain, types, value) {
  19495. this.#throwUnsupported("typed-data", "signTypedData");
  19496. }
  19497. }
  19498. /**
  19499. * There are many awesome community services that provide Ethereum
  19500. * nodes both for developers just starting out and for large-scale
  19501. * communities.
  19502. *
  19503. * @_section: api/providers/thirdparty: Community Providers [thirdparty]
  19504. */
  19505. // Show the throttle message only once per service
  19506. const shown = new Set();
  19507. /**
  19508. * Displays a warning in tht console when the community resource is
  19509. * being used too heavily by the app, recommending the developer
  19510. * acquire their own credentials instead of using the community
  19511. * credentials.
  19512. *
  19513. * The notification will only occur once per service.
  19514. */
  19515. function showThrottleMessage(service) {
  19516. if (shown.has(service)) {
  19517. return;
  19518. }
  19519. shown.add(service);
  19520. console.log("========= NOTICE =========");
  19521. console.log(`Request-Rate Exceeded for ${service} (this message will not be repeated)`);
  19522. console.log("");
  19523. console.log("The default API keys for each service are provided as a highly-throttled,");
  19524. console.log("community resource for low-traffic projects and early prototyping.");
  19525. console.log("");
  19526. console.log("While your application will continue to function, we highly recommended");
  19527. console.log("signing up for your own API keys to improve performance, increase your");
  19528. console.log("request rate/limit and enable other perks, such as metrics and advanced APIs.");
  19529. console.log("");
  19530. console.log("For more details: https:/\/docs.ethers.org/api-keys/");
  19531. console.log("==========================");
  19532. }
  19533. function copy(obj) {
  19534. return JSON.parse(JSON.stringify(obj));
  19535. }
  19536. /**
  19537. * Some backends support subscribing to events using a Filter ID.
  19538. *
  19539. * When subscribing with this technique, the node issues a unique
  19540. * //Filter ID//. At this point the node dedicates resources to
  19541. * the filter, so that periodic calls to follow up on the //Filter ID//
  19542. * will receive any events since the last call.
  19543. *
  19544. * @_docloc: api/providers/abstract-provider
  19545. */
  19546. class FilterIdSubscriber {
  19547. #provider;
  19548. #filterIdPromise;
  19549. #poller;
  19550. #running;
  19551. #network;
  19552. #hault;
  19553. /**
  19554. * Creates a new **FilterIdSubscriber** which will used [[_subscribe]]
  19555. * and [[_emitResults]] to setup the subscription and provide the event
  19556. * to the %%provider%%.
  19557. */
  19558. constructor(provider) {
  19559. this.#provider = provider;
  19560. this.#filterIdPromise = null;
  19561. this.#poller = this.#poll.bind(this);
  19562. this.#running = false;
  19563. this.#network = null;
  19564. this.#hault = false;
  19565. }
  19566. /**
  19567. * Sub-classes **must** override this to begin the subscription.
  19568. */
  19569. _subscribe(provider) {
  19570. throw new Error("subclasses must override this");
  19571. }
  19572. /**
  19573. * Sub-classes **must** override this handle the events.
  19574. */
  19575. _emitResults(provider, result) {
  19576. throw new Error("subclasses must override this");
  19577. }
  19578. /**
  19579. * Sub-classes **must** override this handle recovery on errors.
  19580. */
  19581. _recover(provider) {
  19582. throw new Error("subclasses must override this");
  19583. }
  19584. async #poll(blockNumber) {
  19585. try {
  19586. // Subscribe if necessary
  19587. if (this.#filterIdPromise == null) {
  19588. this.#filterIdPromise = this._subscribe(this.#provider);
  19589. }
  19590. // Get the Filter ID
  19591. let filterId = null;
  19592. try {
  19593. filterId = await this.#filterIdPromise;
  19594. }
  19595. catch (error) {
  19596. if (!isError(error, "UNSUPPORTED_OPERATION") || error.operation !== "eth_newFilter") {
  19597. throw error;
  19598. }
  19599. }
  19600. // The backend does not support Filter ID; downgrade to
  19601. // polling
  19602. if (filterId == null) {
  19603. this.#filterIdPromise = null;
  19604. this.#provider._recoverSubscriber(this, this._recover(this.#provider));
  19605. return;
  19606. }
  19607. const network = await this.#provider.getNetwork();
  19608. if (!this.#network) {
  19609. this.#network = network;
  19610. }
  19611. if (this.#network.chainId !== network.chainId) {
  19612. throw new Error("chaid changed");
  19613. }
  19614. if (this.#hault) {
  19615. return;
  19616. }
  19617. const result = await this.#provider.send("eth_getFilterChanges", [filterId]);
  19618. await this._emitResults(this.#provider, result);
  19619. }
  19620. catch (error) {
  19621. console.log("@TODO", error);
  19622. }
  19623. this.#provider.once("block", this.#poller);
  19624. }
  19625. #teardown() {
  19626. const filterIdPromise = this.#filterIdPromise;
  19627. if (filterIdPromise) {
  19628. this.#filterIdPromise = null;
  19629. filterIdPromise.then((filterId) => {
  19630. if (this.#provider.destroyed) {
  19631. return;
  19632. }
  19633. this.#provider.send("eth_uninstallFilter", [filterId]);
  19634. });
  19635. }
  19636. }
  19637. start() {
  19638. if (this.#running) {
  19639. return;
  19640. }
  19641. this.#running = true;
  19642. this.#poll(-2);
  19643. }
  19644. stop() {
  19645. if (!this.#running) {
  19646. return;
  19647. }
  19648. this.#running = false;
  19649. this.#hault = true;
  19650. this.#teardown();
  19651. this.#provider.off("block", this.#poller);
  19652. }
  19653. pause(dropWhilePaused) {
  19654. if (dropWhilePaused) {
  19655. this.#teardown();
  19656. }
  19657. this.#provider.off("block", this.#poller);
  19658. }
  19659. resume() { this.start(); }
  19660. }
  19661. /**
  19662. * A **FilterIdSubscriber** for receiving contract events.
  19663. *
  19664. * @_docloc: api/providers/abstract-provider
  19665. */
  19666. class FilterIdEventSubscriber extends FilterIdSubscriber {
  19667. #event;
  19668. /**
  19669. * Creates a new **FilterIdEventSubscriber** attached to %%provider%%
  19670. * listening for %%filter%%.
  19671. */
  19672. constructor(provider, filter) {
  19673. super(provider);
  19674. this.#event = copy(filter);
  19675. }
  19676. _recover(provider) {
  19677. return new PollingEventSubscriber(provider, this.#event);
  19678. }
  19679. async _subscribe(provider) {
  19680. const filterId = await provider.send("eth_newFilter", [this.#event]);
  19681. return filterId;
  19682. }
  19683. async _emitResults(provider, results) {
  19684. for (const result of results) {
  19685. provider.emit(this.#event, provider._wrapLog(result, provider._network));
  19686. }
  19687. }
  19688. }
  19689. /**
  19690. * A **FilterIdSubscriber** for receiving pending transactions events.
  19691. *
  19692. * @_docloc: api/providers/abstract-provider
  19693. */
  19694. class FilterIdPendingSubscriber extends FilterIdSubscriber {
  19695. async _subscribe(provider) {
  19696. return await provider.send("eth_newPendingTransactionFilter", []);
  19697. }
  19698. async _emitResults(provider, results) {
  19699. for (const result of results) {
  19700. provider.emit("pending", result);
  19701. }
  19702. }
  19703. }
  19704. /**
  19705. * One of the most common ways to interact with the blockchain is
  19706. * by a node running a JSON-RPC interface which can be connected to,
  19707. * based on the transport, using:
  19708. *
  19709. * - HTTP or HTTPS - [[JsonRpcProvider]]
  19710. * - WebSocket - [[WebSocketProvider]]
  19711. * - IPC - [[IpcSocketProvider]]
  19712. *
  19713. * @_section: api/providers/jsonrpc:JSON-RPC Provider [about-jsonrpcProvider]
  19714. */
  19715. // @TODO:
  19716. // - Add the batching API
  19717. // https://playground.open-rpc.org/?schemaUrl=https://raw.githubusercontent.com/ethereum/eth1.0-apis/assembled-spec/openrpc.json&uiSchema%5BappBar%5D%5Bui:splitView%5D=true&uiSchema%5BappBar%5D%5Bui:input%5D=false&uiSchema%5BappBar%5D%5Bui:examplesDropdown%5D=false
  19718. const Primitive = "bigint,boolean,function,number,string,symbol".split(/,/g);
  19719. //const Methods = "getAddress,then".split(/,/g);
  19720. function deepCopy(value) {
  19721. if (value == null || Primitive.indexOf(typeof (value)) >= 0) {
  19722. return value;
  19723. }
  19724. // Keep any Addressable
  19725. if (typeof (value.getAddress) === "function") {
  19726. return value;
  19727. }
  19728. if (Array.isArray(value)) {
  19729. return (value.map(deepCopy));
  19730. }
  19731. if (typeof (value) === "object") {
  19732. return Object.keys(value).reduce((accum, key) => {
  19733. accum[key] = value[key];
  19734. return accum;
  19735. }, {});
  19736. }
  19737. throw new Error(`should not happen: ${value} (${typeof (value)})`);
  19738. }
  19739. function stall$3(duration) {
  19740. return new Promise((resolve) => { setTimeout(resolve, duration); });
  19741. }
  19742. function getLowerCase(value) {
  19743. if (value) {
  19744. return value.toLowerCase();
  19745. }
  19746. return value;
  19747. }
  19748. function isPollable(value) {
  19749. return (value && typeof (value.pollingInterval) === "number");
  19750. }
  19751. const defaultOptions = {
  19752. polling: false,
  19753. staticNetwork: null,
  19754. batchStallTime: 10,
  19755. batchMaxSize: (1 << 20),
  19756. batchMaxCount: 100,
  19757. cacheTimeout: 250,
  19758. pollingInterval: 4000
  19759. };
  19760. // @TODO: Unchecked Signers
  19761. class JsonRpcSigner extends AbstractSigner {
  19762. address;
  19763. constructor(provider, address) {
  19764. super(provider);
  19765. address = getAddress(address);
  19766. defineProperties(this, { address });
  19767. }
  19768. connect(provider) {
  19769. assert(false, "cannot reconnect JsonRpcSigner", "UNSUPPORTED_OPERATION", {
  19770. operation: "signer.connect"
  19771. });
  19772. }
  19773. async getAddress() {
  19774. return this.address;
  19775. }
  19776. // JSON-RPC will automatially fill in nonce, etc. so we just check from
  19777. async populateTransaction(tx) {
  19778. return await this.populateCall(tx);
  19779. }
  19780. // Returns just the hash of the transaction after sent, which is what
  19781. // the bare JSON-RPC API does;
  19782. async sendUncheckedTransaction(_tx) {
  19783. const tx = deepCopy(_tx);
  19784. const promises = [];
  19785. // Make sure the from matches the sender
  19786. if (tx.from) {
  19787. const _from = tx.from;
  19788. promises.push((async () => {
  19789. const from = await resolveAddress(_from, this.provider);
  19790. assertArgument(from != null && from.toLowerCase() === this.address.toLowerCase(), "from address mismatch", "transaction", _tx);
  19791. tx.from = from;
  19792. })());
  19793. }
  19794. else {
  19795. tx.from = this.address;
  19796. }
  19797. // The JSON-RPC for eth_sendTransaction uses 90000 gas; if the user
  19798. // wishes to use this, it is easy to specify explicitly, otherwise
  19799. // we look it up for them.
  19800. if (tx.gasLimit == null) {
  19801. promises.push((async () => {
  19802. tx.gasLimit = await this.provider.estimateGas({ ...tx, from: this.address });
  19803. })());
  19804. }
  19805. // The address may be an ENS name or Addressable
  19806. if (tx.to != null) {
  19807. const _to = tx.to;
  19808. promises.push((async () => {
  19809. tx.to = await resolveAddress(_to, this.provider);
  19810. })());
  19811. }
  19812. // Wait until all of our properties are filled in
  19813. if (promises.length) {
  19814. await Promise.all(promises);
  19815. }
  19816. const hexTx = this.provider.getRpcTransaction(tx);
  19817. return this.provider.send("eth_sendTransaction", [hexTx]);
  19818. }
  19819. async sendTransaction(tx) {
  19820. // This cannot be mined any earlier than any recent block
  19821. const blockNumber = await this.provider.getBlockNumber();
  19822. // Send the transaction
  19823. const hash = await this.sendUncheckedTransaction(tx);
  19824. // Unfortunately, JSON-RPC only provides and opaque transaction hash
  19825. // for a response, and we need the actual transaction, so we poll
  19826. // for it; it should show up very quickly
  19827. return await (new Promise((resolve, reject) => {
  19828. const timeouts = [1000, 100];
  19829. let invalids = 0;
  19830. const checkTx = async () => {
  19831. try {
  19832. // Try getting the transaction
  19833. const tx = await this.provider.getTransaction(hash);
  19834. if (tx != null) {
  19835. resolve(tx.replaceableTransaction(blockNumber));
  19836. return;
  19837. }
  19838. }
  19839. catch (error) {
  19840. // If we were cancelled: stop polling.
  19841. // If the data is bad: the node returns bad transactions
  19842. // If the network changed: calling again will also fail
  19843. // If unsupported: likely destroyed
  19844. if (isError(error, "CANCELLED") || isError(error, "BAD_DATA") ||
  19845. isError(error, "NETWORK_ERROR") || isError(error, "UNSUPPORTED_OPERATION")) {
  19846. if (error.info == null) {
  19847. error.info = {};
  19848. }
  19849. error.info.sendTransactionHash = hash;
  19850. reject(error);
  19851. return;
  19852. }
  19853. // Stop-gap for misbehaving backends; see #4513
  19854. if (isError(error, "INVALID_ARGUMENT")) {
  19855. invalids++;
  19856. if (error.info == null) {
  19857. error.info = {};
  19858. }
  19859. error.info.sendTransactionHash = hash;
  19860. if (invalids > 10) {
  19861. reject(error);
  19862. return;
  19863. }
  19864. }
  19865. // Notify anyone that cares; but we will try again, since
  19866. // it is likely an intermittent service error
  19867. this.provider.emit("error", makeError("failed to fetch transation after sending (will try again)", "UNKNOWN_ERROR", { error }));
  19868. }
  19869. // Wait another 4 seconds
  19870. this.provider._setTimeout(() => { checkTx(); }, timeouts.pop() || 4000);
  19871. };
  19872. checkTx();
  19873. }));
  19874. }
  19875. async signTransaction(_tx) {
  19876. const tx = deepCopy(_tx);
  19877. // Make sure the from matches the sender
  19878. if (tx.from) {
  19879. const from = await resolveAddress(tx.from, this.provider);
  19880. assertArgument(from != null && from.toLowerCase() === this.address.toLowerCase(), "from address mismatch", "transaction", _tx);
  19881. tx.from = from;
  19882. }
  19883. else {
  19884. tx.from = this.address;
  19885. }
  19886. const hexTx = this.provider.getRpcTransaction(tx);
  19887. return await this.provider.send("eth_signTransaction", [hexTx]);
  19888. }
  19889. async signMessage(_message) {
  19890. const message = ((typeof (_message) === "string") ? toUtf8Bytes(_message) : _message);
  19891. return await this.provider.send("personal_sign", [
  19892. hexlify(message), this.address.toLowerCase()
  19893. ]);
  19894. }
  19895. async signTypedData(domain, types, _value) {
  19896. const value = deepCopy(_value);
  19897. // Populate any ENS names (in-place)
  19898. const populated = await TypedDataEncoder.resolveNames(domain, types, value, async (value) => {
  19899. const address = await resolveAddress(value);
  19900. assertArgument(address != null, "TypedData does not support null address", "value", value);
  19901. return address;
  19902. });
  19903. return await this.provider.send("eth_signTypedData_v4", [
  19904. this.address.toLowerCase(),
  19905. JSON.stringify(TypedDataEncoder.getPayload(populated.domain, types, populated.value))
  19906. ]);
  19907. }
  19908. async unlock(password) {
  19909. return this.provider.send("personal_unlockAccount", [
  19910. this.address.toLowerCase(), password, null
  19911. ]);
  19912. }
  19913. // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
  19914. async _legacySignMessage(_message) {
  19915. const message = ((typeof (_message) === "string") ? toUtf8Bytes(_message) : _message);
  19916. return await this.provider.send("eth_sign", [
  19917. this.address.toLowerCase(), hexlify(message)
  19918. ]);
  19919. }
  19920. }
  19921. /**
  19922. * The JsonRpcApiProvider is an abstract class and **MUST** be
  19923. * sub-classed.
  19924. *
  19925. * It provides the base for all JSON-RPC-based Provider interaction.
  19926. *
  19927. * Sub-classing Notes:
  19928. * - a sub-class MUST override _send
  19929. * - a sub-class MUST call the `_start()` method once connected
  19930. */
  19931. class JsonRpcApiProvider extends AbstractProvider {
  19932. #options;
  19933. // The next ID to use for the JSON-RPC ID field
  19934. #nextId;
  19935. // Payloads are queued and triggered in batches using the drainTimer
  19936. #payloads;
  19937. #drainTimer;
  19938. #notReady;
  19939. #network;
  19940. #pendingDetectNetwork;
  19941. #scheduleDrain() {
  19942. if (this.#drainTimer) {
  19943. return;
  19944. }
  19945. // If we aren't using batching, no harm in sending it immediately
  19946. const stallTime = (this._getOption("batchMaxCount") === 1) ? 0 : this._getOption("batchStallTime");
  19947. this.#drainTimer = setTimeout(() => {
  19948. this.#drainTimer = null;
  19949. const payloads = this.#payloads;
  19950. this.#payloads = [];
  19951. while (payloads.length) {
  19952. // Create payload batches that satisfy our batch constraints
  19953. const batch = [(payloads.shift())];
  19954. while (payloads.length) {
  19955. if (batch.length === this.#options.batchMaxCount) {
  19956. break;
  19957. }
  19958. batch.push((payloads.shift()));
  19959. const bytes = JSON.stringify(batch.map((p) => p.payload));
  19960. if (bytes.length > this.#options.batchMaxSize) {
  19961. payloads.unshift((batch.pop()));
  19962. break;
  19963. }
  19964. }
  19965. // Process the result to each payload
  19966. (async () => {
  19967. const payload = ((batch.length === 1) ? batch[0].payload : batch.map((p) => p.payload));
  19968. this.emit("debug", { action: "sendRpcPayload", payload });
  19969. try {
  19970. const result = await this._send(payload);
  19971. this.emit("debug", { action: "receiveRpcResult", result });
  19972. // Process results in batch order
  19973. for (const { resolve, reject, payload } of batch) {
  19974. if (this.destroyed) {
  19975. reject(makeError("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: payload.method }));
  19976. continue;
  19977. }
  19978. // Find the matching result
  19979. const resp = result.filter((r) => (r.id === payload.id))[0];
  19980. // No result; the node failed us in unexpected ways
  19981. if (resp == null) {
  19982. const error = makeError("missing response for request", "BAD_DATA", {
  19983. value: result, info: { payload }
  19984. });
  19985. this.emit("error", error);
  19986. reject(error);
  19987. continue;
  19988. }
  19989. // The response is an error
  19990. if ("error" in resp) {
  19991. reject(this.getRpcError(payload, resp));
  19992. continue;
  19993. }
  19994. // All good; send the result
  19995. resolve(resp.result);
  19996. }
  19997. }
  19998. catch (error) {
  19999. this.emit("debug", { action: "receiveRpcError", error });
  20000. for (const { reject } of batch) {
  20001. // @TODO: augment the error with the payload
  20002. reject(error);
  20003. }
  20004. }
  20005. })();
  20006. }
  20007. }, stallTime);
  20008. }
  20009. constructor(network, options) {
  20010. super(network, options);
  20011. this.#nextId = 1;
  20012. this.#options = Object.assign({}, defaultOptions, options || {});
  20013. this.#payloads = [];
  20014. this.#drainTimer = null;
  20015. this.#network = null;
  20016. this.#pendingDetectNetwork = null;
  20017. {
  20018. let resolve = null;
  20019. const promise = new Promise((_resolve) => {
  20020. resolve = _resolve;
  20021. });
  20022. this.#notReady = { promise, resolve };
  20023. }
  20024. const staticNetwork = this._getOption("staticNetwork");
  20025. if (typeof (staticNetwork) === "boolean") {
  20026. assertArgument(!staticNetwork || network !== "any", "staticNetwork cannot be used on special network 'any'", "options", options);
  20027. if (staticNetwork && network != null) {
  20028. this.#network = Network.from(network);
  20029. }
  20030. }
  20031. else if (staticNetwork) {
  20032. // Make sure any static network is compatbile with the provided netwrok
  20033. assertArgument(network == null || staticNetwork.matches(network), "staticNetwork MUST match network object", "options", options);
  20034. this.#network = staticNetwork;
  20035. }
  20036. }
  20037. /**
  20038. * Returns the value associated with the option %%key%%.
  20039. *
  20040. * Sub-classes can use this to inquire about configuration options.
  20041. */
  20042. _getOption(key) {
  20043. return this.#options[key];
  20044. }
  20045. /**
  20046. * Gets the [[Network]] this provider has committed to. On each call, the network
  20047. * is detected, and if it has changed, the call will reject.
  20048. */
  20049. get _network() {
  20050. assert(this.#network, "network is not available yet", "NETWORK_ERROR");
  20051. return this.#network;
  20052. }
  20053. /**
  20054. * Resolves to the non-normalized value by performing %%req%%.
  20055. *
  20056. * Sub-classes may override this to modify behavior of actions,
  20057. * and should generally call ``super._perform`` as a fallback.
  20058. */
  20059. async _perform(req) {
  20060. // Legacy networks do not like the type field being passed along (which
  20061. // is fair), so we delete type if it is 0 and a non-EIP-1559 network
  20062. if (req.method === "call" || req.method === "estimateGas") {
  20063. let tx = req.transaction;
  20064. if (tx && tx.type != null && getBigInt(tx.type)) {
  20065. // If there are no EIP-1559 or newer properties, it might be pre-EIP-1559
  20066. if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) {
  20067. const feeData = await this.getFeeData();
  20068. if (feeData.maxFeePerGas == null && feeData.maxPriorityFeePerGas == null) {
  20069. // Network doesn't know about EIP-1559 (and hence type)
  20070. req = Object.assign({}, req, {
  20071. transaction: Object.assign({}, tx, { type: undefined })
  20072. });
  20073. }
  20074. }
  20075. }
  20076. }
  20077. const request = this.getRpcRequest(req);
  20078. if (request != null) {
  20079. return await this.send(request.method, request.args);
  20080. }
  20081. return super._perform(req);
  20082. }
  20083. /**
  20084. * Sub-classes may override this; it detects the *actual* network that
  20085. * we are **currently** connected to.
  20086. *
  20087. * Keep in mind that [[send]] may only be used once [[ready]], otherwise the
  20088. * _send primitive must be used instead.
  20089. */
  20090. async _detectNetwork() {
  20091. const network = this._getOption("staticNetwork");
  20092. if (network) {
  20093. if (network === true) {
  20094. if (this.#network) {
  20095. return this.#network;
  20096. }
  20097. }
  20098. else {
  20099. return network;
  20100. }
  20101. }
  20102. if (this.#pendingDetectNetwork) {
  20103. return await this.#pendingDetectNetwork;
  20104. }
  20105. // If we are ready, use ``send``, which enabled requests to be batched
  20106. if (this.ready) {
  20107. this.#pendingDetectNetwork = (async () => {
  20108. try {
  20109. const result = Network.from(getBigInt(await this.send("eth_chainId", [])));
  20110. this.#pendingDetectNetwork = null;
  20111. return result;
  20112. }
  20113. catch (error) {
  20114. this.#pendingDetectNetwork = null;
  20115. throw error;
  20116. }
  20117. })();
  20118. return await this.#pendingDetectNetwork;
  20119. }
  20120. // We are not ready yet; use the primitive _send
  20121. this.#pendingDetectNetwork = (async () => {
  20122. const payload = {
  20123. id: this.#nextId++, method: "eth_chainId", params: [], jsonrpc: "2.0"
  20124. };
  20125. this.emit("debug", { action: "sendRpcPayload", payload });
  20126. let result;
  20127. try {
  20128. result = (await this._send(payload))[0];
  20129. this.#pendingDetectNetwork = null;
  20130. }
  20131. catch (error) {
  20132. this.#pendingDetectNetwork = null;
  20133. this.emit("debug", { action: "receiveRpcError", error });
  20134. throw error;
  20135. }
  20136. this.emit("debug", { action: "receiveRpcResult", result });
  20137. if ("result" in result) {
  20138. return Network.from(getBigInt(result.result));
  20139. }
  20140. throw this.getRpcError(payload, result);
  20141. })();
  20142. return await this.#pendingDetectNetwork;
  20143. }
  20144. /**
  20145. * Sub-classes **MUST** call this. Until [[_start]] has been called, no calls
  20146. * will be passed to [[_send]] from [[send]]. If it is overridden, then
  20147. * ``super._start()`` **MUST** be called.
  20148. *
  20149. * Calling it multiple times is safe and has no effect.
  20150. */
  20151. _start() {
  20152. if (this.#notReady == null || this.#notReady.resolve == null) {
  20153. return;
  20154. }
  20155. this.#notReady.resolve();
  20156. this.#notReady = null;
  20157. (async () => {
  20158. // Bootstrap the network
  20159. while (this.#network == null && !this.destroyed) {
  20160. try {
  20161. this.#network = await this._detectNetwork();
  20162. }
  20163. catch (error) {
  20164. if (this.destroyed) {
  20165. break;
  20166. }
  20167. console.log("JsonRpcProvider failed to detect network and cannot start up; retry in 1s (perhaps the URL is wrong or the node is not started)");
  20168. this.emit("error", makeError("failed to bootstrap network detection", "NETWORK_ERROR", { event: "initial-network-discovery", info: { error } }));
  20169. await stall$3(1000);
  20170. }
  20171. }
  20172. // Start dispatching requests
  20173. this.#scheduleDrain();
  20174. })();
  20175. }
  20176. /**
  20177. * Resolves once the [[_start]] has been called. This can be used in
  20178. * sub-classes to defer sending data until the connection has been
  20179. * established.
  20180. */
  20181. async _waitUntilReady() {
  20182. if (this.#notReady == null) {
  20183. return;
  20184. }
  20185. return await this.#notReady.promise;
  20186. }
  20187. /**
  20188. * Return a Subscriber that will manage the %%sub%%.
  20189. *
  20190. * Sub-classes may override this to modify the behavior of
  20191. * subscription management.
  20192. */
  20193. _getSubscriber(sub) {
  20194. // Pending Filters aren't availble via polling
  20195. if (sub.type === "pending") {
  20196. return new FilterIdPendingSubscriber(this);
  20197. }
  20198. if (sub.type === "event") {
  20199. if (this._getOption("polling")) {
  20200. return new PollingEventSubscriber(this, sub.filter);
  20201. }
  20202. return new FilterIdEventSubscriber(this, sub.filter);
  20203. }
  20204. // Orphaned Logs are handled automatically, by the filter, since
  20205. // logs with removed are emitted by it
  20206. if (sub.type === "orphan" && sub.filter.orphan === "drop-log") {
  20207. return new UnmanagedSubscriber("orphan");
  20208. }
  20209. return super._getSubscriber(sub);
  20210. }
  20211. /**
  20212. * Returns true only if the [[_start]] has been called.
  20213. */
  20214. get ready() { return this.#notReady == null; }
  20215. /**
  20216. * Returns %%tx%% as a normalized JSON-RPC transaction request,
  20217. * which has all values hexlified and any numeric values converted
  20218. * to Quantity values.
  20219. */
  20220. getRpcTransaction(tx) {
  20221. const result = {};
  20222. // JSON-RPC now requires numeric values to be "quantity" values
  20223. ["chainId", "gasLimit", "gasPrice", "type", "maxFeePerGas", "maxPriorityFeePerGas", "nonce", "value"].forEach((key) => {
  20224. if (tx[key] == null) {
  20225. return;
  20226. }
  20227. let dstKey = key;
  20228. if (key === "gasLimit") {
  20229. dstKey = "gas";
  20230. }
  20231. result[dstKey] = toQuantity(getBigInt(tx[key], `tx.${key}`));
  20232. });
  20233. // Make sure addresses and data are lowercase
  20234. ["from", "to", "data"].forEach((key) => {
  20235. if (tx[key] == null) {
  20236. return;
  20237. }
  20238. result[key] = hexlify(tx[key]);
  20239. });
  20240. // Normalize the access list object
  20241. if (tx.accessList) {
  20242. result["accessList"] = accessListify(tx.accessList);
  20243. }
  20244. if (tx.blobVersionedHashes) {
  20245. // @TODO: Remove this <any> case once EIP-4844 added to prepared tx
  20246. result["blobVersionedHashes"] = tx.blobVersionedHashes.map(h => h.toLowerCase());
  20247. }
  20248. // @TODO: blobs should probably also be copied over, optionally
  20249. // accounting for the kzg property to backfill blobVersionedHashes
  20250. // using the commitment. Or should that be left as an exercise to
  20251. // the caller?
  20252. return result;
  20253. }
  20254. /**
  20255. * Returns the request method and arguments required to perform
  20256. * %%req%%.
  20257. */
  20258. getRpcRequest(req) {
  20259. switch (req.method) {
  20260. case "chainId":
  20261. return { method: "eth_chainId", args: [] };
  20262. case "getBlockNumber":
  20263. return { method: "eth_blockNumber", args: [] };
  20264. case "getGasPrice":
  20265. return { method: "eth_gasPrice", args: [] };
  20266. case "getPriorityFee":
  20267. return { method: "eth_maxPriorityFeePerGas", args: [] };
  20268. case "getBalance":
  20269. return {
  20270. method: "eth_getBalance",
  20271. args: [getLowerCase(req.address), req.blockTag]
  20272. };
  20273. case "getTransactionCount":
  20274. return {
  20275. method: "eth_getTransactionCount",
  20276. args: [getLowerCase(req.address), req.blockTag]
  20277. };
  20278. case "getCode":
  20279. return {
  20280. method: "eth_getCode",
  20281. args: [getLowerCase(req.address), req.blockTag]
  20282. };
  20283. case "getStorage":
  20284. return {
  20285. method: "eth_getStorageAt",
  20286. args: [
  20287. getLowerCase(req.address),
  20288. ("0x" + req.position.toString(16)),
  20289. req.blockTag
  20290. ]
  20291. };
  20292. case "broadcastTransaction":
  20293. return {
  20294. method: "eth_sendRawTransaction",
  20295. args: [req.signedTransaction]
  20296. };
  20297. case "getBlock":
  20298. if ("blockTag" in req) {
  20299. return {
  20300. method: "eth_getBlockByNumber",
  20301. args: [req.blockTag, !!req.includeTransactions]
  20302. };
  20303. }
  20304. else if ("blockHash" in req) {
  20305. return {
  20306. method: "eth_getBlockByHash",
  20307. args: [req.blockHash, !!req.includeTransactions]
  20308. };
  20309. }
  20310. break;
  20311. case "getTransaction":
  20312. return {
  20313. method: "eth_getTransactionByHash",
  20314. args: [req.hash]
  20315. };
  20316. case "getTransactionReceipt":
  20317. return {
  20318. method: "eth_getTransactionReceipt",
  20319. args: [req.hash]
  20320. };
  20321. case "call":
  20322. return {
  20323. method: "eth_call",
  20324. args: [this.getRpcTransaction(req.transaction), req.blockTag]
  20325. };
  20326. case "estimateGas": {
  20327. return {
  20328. method: "eth_estimateGas",
  20329. args: [this.getRpcTransaction(req.transaction)]
  20330. };
  20331. }
  20332. case "getLogs":
  20333. if (req.filter && req.filter.address != null) {
  20334. if (Array.isArray(req.filter.address)) {
  20335. req.filter.address = req.filter.address.map(getLowerCase);
  20336. }
  20337. else {
  20338. req.filter.address = getLowerCase(req.filter.address);
  20339. }
  20340. }
  20341. return { method: "eth_getLogs", args: [req.filter] };
  20342. }
  20343. return null;
  20344. }
  20345. /**
  20346. * Returns an ethers-style Error for the given JSON-RPC error
  20347. * %%payload%%, coalescing the various strings and error shapes
  20348. * that different nodes return, coercing them into a machine-readable
  20349. * standardized error.
  20350. */
  20351. getRpcError(payload, _error) {
  20352. const { method } = payload;
  20353. const { error } = _error;
  20354. if (method === "eth_estimateGas" && error.message) {
  20355. const msg = error.message;
  20356. if (!msg.match(/revert/i) && msg.match(/insufficient funds/i)) {
  20357. return makeError("insufficient funds", "INSUFFICIENT_FUNDS", {
  20358. transaction: (payload.params[0]),
  20359. info: { payload, error }
  20360. });
  20361. }
  20362. }
  20363. if (method === "eth_call" || method === "eth_estimateGas") {
  20364. const result = spelunkData(error);
  20365. const e = AbiCoder.getBuiltinCallException((method === "eth_call") ? "call" : "estimateGas", (payload.params[0]), (result ? result.data : null));
  20366. e.info = { error, payload };
  20367. return e;
  20368. }
  20369. // Only estimateGas and call can return arbitrary contract-defined text, so now we
  20370. // we can process text safely.
  20371. const message = JSON.stringify(spelunkMessage(error));
  20372. if (typeof (error.message) === "string" && error.message.match(/user denied|ethers-user-denied/i)) {
  20373. const actionMap = {
  20374. eth_sign: "signMessage",
  20375. personal_sign: "signMessage",
  20376. eth_signTypedData_v4: "signTypedData",
  20377. eth_signTransaction: "signTransaction",
  20378. eth_sendTransaction: "sendTransaction",
  20379. eth_requestAccounts: "requestAccess",
  20380. wallet_requestAccounts: "requestAccess",
  20381. };
  20382. return makeError(`user rejected action`, "ACTION_REJECTED", {
  20383. action: (actionMap[method] || "unknown"),
  20384. reason: "rejected",
  20385. info: { payload, error }
  20386. });
  20387. }
  20388. if (method === "eth_sendRawTransaction" || method === "eth_sendTransaction") {
  20389. const transaction = (payload.params[0]);
  20390. if (message.match(/insufficient funds|base fee exceeds gas limit/i)) {
  20391. return makeError("insufficient funds for intrinsic transaction cost", "INSUFFICIENT_FUNDS", {
  20392. transaction, info: { error }
  20393. });
  20394. }
  20395. if (message.match(/nonce/i) && message.match(/too low/i)) {
  20396. return makeError("nonce has already been used", "NONCE_EXPIRED", { transaction, info: { error } });
  20397. }
  20398. // "replacement transaction underpriced"
  20399. if (message.match(/replacement transaction/i) && message.match(/underpriced/i)) {
  20400. return makeError("replacement fee too low", "REPLACEMENT_UNDERPRICED", { transaction, info: { error } });
  20401. }
  20402. if (message.match(/only replay-protected/i)) {
  20403. return makeError("legacy pre-eip-155 transactions not supported", "UNSUPPORTED_OPERATION", {
  20404. operation: method, info: { transaction, info: { error } }
  20405. });
  20406. }
  20407. }
  20408. let unsupported = !!message.match(/the method .* does not exist/i);
  20409. if (!unsupported) {
  20410. if (error && error.details && error.details.startsWith("Unauthorized method:")) {
  20411. unsupported = true;
  20412. }
  20413. }
  20414. if (unsupported) {
  20415. return makeError("unsupported operation", "UNSUPPORTED_OPERATION", {
  20416. operation: payload.method, info: { error, payload }
  20417. });
  20418. }
  20419. return makeError("could not coalesce error", "UNKNOWN_ERROR", { error, payload });
  20420. }
  20421. /**
  20422. * Requests the %%method%% with %%params%% via the JSON-RPC protocol
  20423. * over the underlying channel. This can be used to call methods
  20424. * on the backend that do not have a high-level API within the Provider
  20425. * API.
  20426. *
  20427. * This method queues requests according to the batch constraints
  20428. * in the options, assigns the request a unique ID.
  20429. *
  20430. * **Do NOT override** this method in sub-classes; instead
  20431. * override [[_send]] or force the options values in the
  20432. * call to the constructor to modify this method's behavior.
  20433. */
  20434. send(method, params) {
  20435. // @TODO: cache chainId?? purge on switch_networks
  20436. // We have been destroyed; no operations are supported anymore
  20437. if (this.destroyed) {
  20438. return Promise.reject(makeError("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: method }));
  20439. }
  20440. const id = this.#nextId++;
  20441. const promise = new Promise((resolve, reject) => {
  20442. this.#payloads.push({
  20443. resolve, reject,
  20444. payload: { method, params, id, jsonrpc: "2.0" }
  20445. });
  20446. });
  20447. // If there is not a pending drainTimer, set one
  20448. this.#scheduleDrain();
  20449. return promise;
  20450. }
  20451. /**
  20452. * Resolves to the [[Signer]] account for %%address%% managed by
  20453. * the client.
  20454. *
  20455. * If the %%address%% is a number, it is used as an index in the
  20456. * the accounts from [[listAccounts]].
  20457. *
  20458. * This can only be used on clients which manage accounts (such as
  20459. * Geth with imported account or MetaMask).
  20460. *
  20461. * Throws if the account doesn't exist.
  20462. */
  20463. async getSigner(address) {
  20464. if (address == null) {
  20465. address = 0;
  20466. }
  20467. const accountsPromise = this.send("eth_accounts", []);
  20468. // Account index
  20469. if (typeof (address) === "number") {
  20470. const accounts = (await accountsPromise);
  20471. if (address >= accounts.length) {
  20472. throw new Error("no such account");
  20473. }
  20474. return new JsonRpcSigner(this, accounts[address]);
  20475. }
  20476. const { accounts } = await resolveProperties({
  20477. network: this.getNetwork(),
  20478. accounts: accountsPromise
  20479. });
  20480. // Account address
  20481. address = getAddress(address);
  20482. for (const account of accounts) {
  20483. if (getAddress(account) === address) {
  20484. return new JsonRpcSigner(this, address);
  20485. }
  20486. }
  20487. throw new Error("invalid account");
  20488. }
  20489. async listAccounts() {
  20490. const accounts = await this.send("eth_accounts", []);
  20491. return accounts.map((a) => new JsonRpcSigner(this, a));
  20492. }
  20493. destroy() {
  20494. // Stop processing requests
  20495. if (this.#drainTimer) {
  20496. clearTimeout(this.#drainTimer);
  20497. this.#drainTimer = null;
  20498. }
  20499. // Cancel all pending requests
  20500. for (const { payload, reject } of this.#payloads) {
  20501. reject(makeError("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: payload.method }));
  20502. }
  20503. this.#payloads = [];
  20504. // Parent clean-up
  20505. super.destroy();
  20506. }
  20507. }
  20508. // @TODO: remove this in v7, it is not exported because this functionality
  20509. // is exposed in the JsonRpcApiProvider by setting polling to true. It should
  20510. // be safe to remove regardless, because it isn't reachable, but just in case.
  20511. /**
  20512. * @_ignore:
  20513. */
  20514. class JsonRpcApiPollingProvider extends JsonRpcApiProvider {
  20515. #pollingInterval;
  20516. constructor(network, options) {
  20517. super(network, options);
  20518. let pollingInterval = this._getOption("pollingInterval");
  20519. if (pollingInterval == null) {
  20520. pollingInterval = defaultOptions.pollingInterval;
  20521. }
  20522. this.#pollingInterval = pollingInterval;
  20523. }
  20524. _getSubscriber(sub) {
  20525. const subscriber = super._getSubscriber(sub);
  20526. if (isPollable(subscriber)) {
  20527. subscriber.pollingInterval = this.#pollingInterval;
  20528. }
  20529. return subscriber;
  20530. }
  20531. /**
  20532. * The polling interval (default: 4000 ms)
  20533. */
  20534. get pollingInterval() { return this.#pollingInterval; }
  20535. set pollingInterval(value) {
  20536. if (!Number.isInteger(value) || value < 0) {
  20537. throw new Error("invalid interval");
  20538. }
  20539. this.#pollingInterval = value;
  20540. this._forEachSubscriber((sub) => {
  20541. if (isPollable(sub)) {
  20542. sub.pollingInterval = this.#pollingInterval;
  20543. }
  20544. });
  20545. }
  20546. }
  20547. /**
  20548. * The JsonRpcProvider is one of the most common Providers,
  20549. * which performs all operations over HTTP (or HTTPS) requests.
  20550. *
  20551. * Events are processed by polling the backend for the current block
  20552. * number; when it advances, all block-base events are then checked
  20553. * for updates.
  20554. */
  20555. class JsonRpcProvider extends JsonRpcApiPollingProvider {
  20556. #connect;
  20557. constructor(url, network, options) {
  20558. if (url == null) {
  20559. url = "http:/\/localhost:8545";
  20560. }
  20561. super(network, options);
  20562. if (typeof (url) === "string") {
  20563. this.#connect = new FetchRequest(url);
  20564. }
  20565. else {
  20566. this.#connect = url.clone();
  20567. }
  20568. }
  20569. _getConnection() {
  20570. return this.#connect.clone();
  20571. }
  20572. async send(method, params) {
  20573. // All requests are over HTTP, so we can just start handling requests
  20574. // We do this here rather than the constructor so that we don't send any
  20575. // requests to the network (i.e. eth_chainId) until we absolutely have to.
  20576. await this._start();
  20577. return await super.send(method, params);
  20578. }
  20579. async _send(payload) {
  20580. // Configure a POST connection for the requested method
  20581. const request = this._getConnection();
  20582. request.body = JSON.stringify(payload);
  20583. request.setHeader("content-type", "application/json");
  20584. const response = await request.send();
  20585. response.assertOk();
  20586. let resp = response.bodyJson;
  20587. if (!Array.isArray(resp)) {
  20588. resp = [resp];
  20589. }
  20590. return resp;
  20591. }
  20592. }
  20593. function spelunkData(value) {
  20594. if (value == null) {
  20595. return null;
  20596. }
  20597. // These *are* the droids we're looking for.
  20598. if (typeof (value.message) === "string" && value.message.match(/revert/i) && isHexString(value.data)) {
  20599. return { message: value.message, data: value.data };
  20600. }
  20601. // Spelunk further...
  20602. if (typeof (value) === "object") {
  20603. for (const key in value) {
  20604. const result = spelunkData(value[key]);
  20605. if (result) {
  20606. return result;
  20607. }
  20608. }
  20609. return null;
  20610. }
  20611. // Might be a JSON string we can further descend...
  20612. if (typeof (value) === "string") {
  20613. try {
  20614. return spelunkData(JSON.parse(value));
  20615. }
  20616. catch (error) { }
  20617. }
  20618. return null;
  20619. }
  20620. function _spelunkMessage(value, result) {
  20621. if (value == null) {
  20622. return;
  20623. }
  20624. // These *are* the droids we're looking for.
  20625. if (typeof (value.message) === "string") {
  20626. result.push(value.message);
  20627. }
  20628. // Spelunk further...
  20629. if (typeof (value) === "object") {
  20630. for (const key in value) {
  20631. _spelunkMessage(value[key], result);
  20632. }
  20633. }
  20634. // Might be a JSON string we can further descend...
  20635. if (typeof (value) === "string") {
  20636. try {
  20637. return _spelunkMessage(JSON.parse(value), result);
  20638. }
  20639. catch (error) { }
  20640. }
  20641. }
  20642. function spelunkMessage(value) {
  20643. const result = [];
  20644. _spelunkMessage(value, result);
  20645. return result;
  20646. }
  20647. /**
  20648. * [[link-ankr]] provides a third-party service for connecting to
  20649. * various blockchains over JSON-RPC.
  20650. *
  20651. * **Supported Networks**
  20652. *
  20653. * - Ethereum Mainnet (``mainnet``)
  20654. * - Goerli Testnet (``goerli``)
  20655. * - Sepolia Testnet (``sepolia``)
  20656. * - Arbitrum (``arbitrum``)
  20657. * - Base (``base``)
  20658. * - Base Goerlia Testnet (``base-goerli``)
  20659. * - Base Sepolia Testnet (``base-sepolia``)
  20660. * - BNB (``bnb``)
  20661. * - BNB Testnet (``bnbt``)
  20662. * - Optimism (``optimism``)
  20663. * - Optimism Goerli Testnet (``optimism-goerli``)
  20664. * - Optimism Sepolia Testnet (``optimism-sepolia``)
  20665. * - Polygon (``matic``)
  20666. * - Polygon Mumbai Testnet (``matic-mumbai``)
  20667. *
  20668. * @_subsection: api/providers/thirdparty:Ankr [providers-ankr]
  20669. */
  20670. const defaultApiKey$1 = "9f7d929b018cdffb338517efa06f58359e86ff1ffd350bc889738523659e7972";
  20671. function getHost$5(name) {
  20672. switch (name) {
  20673. case "mainnet":
  20674. return "rpc.ankr.com/eth";
  20675. case "goerli":
  20676. return "rpc.ankr.com/eth_goerli";
  20677. case "sepolia":
  20678. return "rpc.ankr.com/eth_sepolia";
  20679. case "arbitrum":
  20680. return "rpc.ankr.com/arbitrum";
  20681. case "base":
  20682. return "rpc.ankr.com/base";
  20683. case "base-goerli":
  20684. return "rpc.ankr.com/base_goerli";
  20685. case "base-sepolia":
  20686. return "rpc.ankr.com/base_sepolia";
  20687. case "bnb":
  20688. return "rpc.ankr.com/bsc";
  20689. case "bnbt":
  20690. return "rpc.ankr.com/bsc_testnet_chapel";
  20691. case "matic":
  20692. return "rpc.ankr.com/polygon";
  20693. case "matic-mumbai":
  20694. return "rpc.ankr.com/polygon_mumbai";
  20695. case "optimism":
  20696. return "rpc.ankr.com/optimism";
  20697. case "optimism-goerli":
  20698. return "rpc.ankr.com/optimism_testnet";
  20699. case "optimism-sepolia":
  20700. return "rpc.ankr.com/optimism_sepolia";
  20701. }
  20702. assertArgument(false, "unsupported network", "network", name);
  20703. }
  20704. /**
  20705. * The **AnkrProvider** connects to the [[link-ankr]]
  20706. * JSON-RPC end-points.
  20707. *
  20708. * By default, a highly-throttled API key is used, which is
  20709. * appropriate for quick prototypes and simple scripts. To
  20710. * gain access to an increased rate-limit, it is highly
  20711. * recommended to [sign up here](link-ankr-signup).
  20712. */
  20713. class AnkrProvider extends JsonRpcProvider {
  20714. /**
  20715. * The API key for the Ankr connection.
  20716. */
  20717. apiKey;
  20718. /**
  20719. * Create a new **AnkrProvider**.
  20720. *
  20721. * By default connecting to ``mainnet`` with a highly throttled
  20722. * API key.
  20723. */
  20724. constructor(_network, apiKey) {
  20725. if (_network == null) {
  20726. _network = "mainnet";
  20727. }
  20728. const network = Network.from(_network);
  20729. if (apiKey == null) {
  20730. apiKey = defaultApiKey$1;
  20731. }
  20732. // Ankr does not support filterId, so we force polling
  20733. const options = { polling: true, staticNetwork: network };
  20734. const request = AnkrProvider.getRequest(network, apiKey);
  20735. super(request, network, options);
  20736. defineProperties(this, { apiKey });
  20737. }
  20738. _getProvider(chainId) {
  20739. try {
  20740. return new AnkrProvider(chainId, this.apiKey);
  20741. }
  20742. catch (error) { }
  20743. return super._getProvider(chainId);
  20744. }
  20745. /**
  20746. * Returns a prepared request for connecting to %%network%% with
  20747. * %%apiKey%%.
  20748. */
  20749. static getRequest(network, apiKey) {
  20750. if (apiKey == null) {
  20751. apiKey = defaultApiKey$1;
  20752. }
  20753. const request = new FetchRequest(`https:/\/${getHost$5(network.name)}/${apiKey}`);
  20754. request.allowGzip = true;
  20755. if (apiKey === defaultApiKey$1) {
  20756. request.retryFunc = async (request, response, attempt) => {
  20757. showThrottleMessage("AnkrProvider");
  20758. return true;
  20759. };
  20760. }
  20761. return request;
  20762. }
  20763. getRpcError(payload, error) {
  20764. if (payload.method === "eth_sendRawTransaction") {
  20765. if (error && error.error && error.error.message === "INTERNAL_ERROR: could not replace existing tx") {
  20766. error.error.message = "replacement transaction underpriced";
  20767. }
  20768. }
  20769. return super.getRpcError(payload, error);
  20770. }
  20771. isCommunityResource() {
  20772. return (this.apiKey === defaultApiKey$1);
  20773. }
  20774. }
  20775. /**
  20776. * [[link-alchemy]] provides a third-party service for connecting to
  20777. * various blockchains over JSON-RPC.
  20778. *
  20779. * **Supported Networks**
  20780. *
  20781. * - Ethereum Mainnet (``mainnet``)
  20782. * - Goerli Testnet (``goerli``)
  20783. * - Sepolia Testnet (``sepolia``)
  20784. * - Arbitrum (``arbitrum``)
  20785. * - Arbitrum Goerli Testnet (``arbitrum-goerli``)
  20786. * - Arbitrum Sepolia Testnet (``arbitrum-sepolia``)
  20787. * - Base (``base``)
  20788. * - Base Goerlia Testnet (``base-goerli``)
  20789. * - Base Sepolia Testnet (``base-sepolia``)
  20790. * - Optimism (``optimism``)
  20791. * - Optimism Goerli Testnet (``optimism-goerli``)
  20792. * - Optimism Sepolia Testnet (``optimism-sepolia``)
  20793. * - Polygon (``matic``)
  20794. * - Polygon Amoy Testnet (``matic-amoy``)
  20795. * - Polygon Mumbai Testnet (``matic-mumbai``)
  20796. *
  20797. * @_subsection: api/providers/thirdparty:Alchemy [providers-alchemy]
  20798. */
  20799. const defaultApiKey = "_gg7wSSi0KMBsdKnGVfHDueq6xMB9EkC";
  20800. function getHost$4(name) {
  20801. switch (name) {
  20802. case "mainnet":
  20803. return "eth-mainnet.alchemyapi.io";
  20804. case "goerli":
  20805. return "eth-goerli.g.alchemy.com";
  20806. case "sepolia":
  20807. return "eth-sepolia.g.alchemy.com";
  20808. case "arbitrum":
  20809. return "arb-mainnet.g.alchemy.com";
  20810. case "arbitrum-goerli":
  20811. return "arb-goerli.g.alchemy.com";
  20812. case "arbitrum-sepolia":
  20813. return "arb-sepolia.g.alchemy.com";
  20814. case "base":
  20815. return "base-mainnet.g.alchemy.com";
  20816. case "base-goerli":
  20817. return "base-goerli.g.alchemy.com";
  20818. case "base-sepolia":
  20819. return "base-sepolia.g.alchemy.com";
  20820. case "matic":
  20821. return "polygon-mainnet.g.alchemy.com";
  20822. case "matic-amoy":
  20823. return "polygon-amoy.g.alchemy.com";
  20824. case "matic-mumbai":
  20825. return "polygon-mumbai.g.alchemy.com";
  20826. case "optimism":
  20827. return "opt-mainnet.g.alchemy.com";
  20828. case "optimism-goerli":
  20829. return "opt-goerli.g.alchemy.com";
  20830. case "optimism-sepolia":
  20831. return "opt-sepolia.g.alchemy.com";
  20832. }
  20833. assertArgument(false, "unsupported network", "network", name);
  20834. }
  20835. /**
  20836. * The **AlchemyProvider** connects to the [[link-alchemy]]
  20837. * JSON-RPC end-points.
  20838. *
  20839. * By default, a highly-throttled API key is used, which is
  20840. * appropriate for quick prototypes and simple scripts. To
  20841. * gain access to an increased rate-limit, it is highly
  20842. * recommended to [sign up here](link-alchemy-signup).
  20843. *
  20844. * @_docloc: api/providers/thirdparty
  20845. */
  20846. class AlchemyProvider extends JsonRpcProvider {
  20847. apiKey;
  20848. constructor(_network, apiKey) {
  20849. if (_network == null) {
  20850. _network = "mainnet";
  20851. }
  20852. const network = Network.from(_network);
  20853. if (apiKey == null) {
  20854. apiKey = defaultApiKey;
  20855. }
  20856. const request = AlchemyProvider.getRequest(network, apiKey);
  20857. super(request, network, { staticNetwork: network });
  20858. defineProperties(this, { apiKey });
  20859. }
  20860. _getProvider(chainId) {
  20861. try {
  20862. return new AlchemyProvider(chainId, this.apiKey);
  20863. }
  20864. catch (error) { }
  20865. return super._getProvider(chainId);
  20866. }
  20867. async _perform(req) {
  20868. // https://docs.alchemy.com/reference/trace-transaction
  20869. if (req.method === "getTransactionResult") {
  20870. const { trace, tx } = await resolveProperties({
  20871. trace: this.send("trace_transaction", [req.hash]),
  20872. tx: this.getTransaction(req.hash)
  20873. });
  20874. if (trace == null || tx == null) {
  20875. return null;
  20876. }
  20877. let data;
  20878. let error = false;
  20879. try {
  20880. data = trace[0].result.output;
  20881. error = (trace[0].error === "Reverted");
  20882. }
  20883. catch (error) { }
  20884. if (data) {
  20885. assert(!error, "an error occurred during transaction executions", "CALL_EXCEPTION", {
  20886. action: "getTransactionResult",
  20887. data,
  20888. reason: null,
  20889. transaction: tx,
  20890. invocation: null,
  20891. revert: null // @TODO
  20892. });
  20893. return data;
  20894. }
  20895. assert(false, "could not parse trace result", "BAD_DATA", { value: trace });
  20896. }
  20897. return await super._perform(req);
  20898. }
  20899. isCommunityResource() {
  20900. return (this.apiKey === defaultApiKey);
  20901. }
  20902. static getRequest(network, apiKey) {
  20903. if (apiKey == null) {
  20904. apiKey = defaultApiKey;
  20905. }
  20906. const request = new FetchRequest(`https:/\/${getHost$4(network.name)}/v2/${apiKey}`);
  20907. request.allowGzip = true;
  20908. if (apiKey === defaultApiKey) {
  20909. request.retryFunc = async (request, response, attempt) => {
  20910. showThrottleMessage("alchemy");
  20911. return true;
  20912. };
  20913. }
  20914. return request;
  20915. }
  20916. }
  20917. /**
  20918. * [[link-chainstack]] provides a third-party service for connecting to
  20919. * various blockchains over JSON-RPC.
  20920. *
  20921. * **Supported Networks**
  20922. *
  20923. * - Ethereum Mainnet (``mainnet``)
  20924. * - Arbitrum (``arbitrum``)
  20925. * - BNB Smart Chain Mainnet (``bnb``)
  20926. * - Polygon (``matic``)
  20927. *
  20928. * @_subsection: api/providers/thirdparty:Chainstack [providers-chainstack]
  20929. */
  20930. function getApiKey(name) {
  20931. switch (name) {
  20932. case "mainnet": return "39f1d67cedf8b7831010a665328c9197";
  20933. case "arbitrum": return "0550c209db33c3abf4cc927e1e18cea1";
  20934. case "bnb": return "98b5a77e531614387366f6fc5da097f8";
  20935. case "matic": return "cd9d4d70377471aa7c142ec4a4205249";
  20936. }
  20937. assertArgument(false, "unsupported network", "network", name);
  20938. }
  20939. function getHost$3(name) {
  20940. switch (name) {
  20941. case "mainnet":
  20942. return "ethereum-mainnet.core.chainstack.com";
  20943. case "arbitrum":
  20944. return "arbitrum-mainnet.core.chainstack.com";
  20945. case "bnb":
  20946. return "bsc-mainnet.core.chainstack.com";
  20947. case "matic":
  20948. return "polygon-mainnet.core.chainstack.com";
  20949. }
  20950. assertArgument(false, "unsupported network", "network", name);
  20951. }
  20952. /**
  20953. * The **ChainstackProvider** connects to the [[link-chainstack]]
  20954. * JSON-RPC end-points.
  20955. *
  20956. * By default, a highly-throttled API key is used, which is
  20957. * appropriate for quick prototypes and simple scripts. To
  20958. * gain access to an increased rate-limit, it is highly
  20959. * recommended to [sign up here](link-chainstack).
  20960. */
  20961. class ChainstackProvider extends JsonRpcProvider {
  20962. /**
  20963. * The API key for the Chainstack connection.
  20964. */
  20965. apiKey;
  20966. /**
  20967. * Creates a new **ChainstackProvider**.
  20968. */
  20969. constructor(_network, apiKey) {
  20970. if (_network == null) {
  20971. _network = "mainnet";
  20972. }
  20973. const network = Network.from(_network);
  20974. if (apiKey == null) {
  20975. apiKey = getApiKey(network.name);
  20976. }
  20977. const request = ChainstackProvider.getRequest(network, apiKey);
  20978. super(request, network, { staticNetwork: network });
  20979. defineProperties(this, { apiKey });
  20980. }
  20981. _getProvider(chainId) {
  20982. try {
  20983. return new ChainstackProvider(chainId, this.apiKey);
  20984. }
  20985. catch (error) { }
  20986. return super._getProvider(chainId);
  20987. }
  20988. isCommunityResource() {
  20989. return (this.apiKey === getApiKey(this._network.name));
  20990. }
  20991. /**
  20992. * Returns a prepared request for connecting to %%network%%
  20993. * with %%apiKey%% and %%projectSecret%%.
  20994. */
  20995. static getRequest(network, apiKey) {
  20996. if (apiKey == null) {
  20997. apiKey = getApiKey(network.name);
  20998. }
  20999. const request = new FetchRequest(`https:/\/${getHost$3(network.name)}/${apiKey}`);
  21000. request.allowGzip = true;
  21001. if (apiKey === getApiKey(network.name)) {
  21002. request.retryFunc = async (request, response, attempt) => {
  21003. showThrottleMessage("ChainstackProvider");
  21004. return true;
  21005. };
  21006. }
  21007. return request;
  21008. }
  21009. }
  21010. /**
  21011. * About Cloudflare
  21012. *
  21013. * @_subsection: api/providers/thirdparty:Cloudflare [providers-cloudflare]
  21014. */
  21015. /**
  21016. * About Cloudflare...
  21017. */
  21018. class CloudflareProvider extends JsonRpcProvider {
  21019. constructor(_network) {
  21020. if (_network == null) {
  21021. _network = "mainnet";
  21022. }
  21023. const network = Network.from(_network);
  21024. assertArgument(network.name === "mainnet", "unsupported network", "network", _network);
  21025. super("https:/\/cloudflare-eth.com/", network, { staticNetwork: network });
  21026. }
  21027. }
  21028. /**
  21029. * [[link-etherscan]] provides a third-party service for connecting to
  21030. * various blockchains over a combination of JSON-RPC and custom API
  21031. * endpoints.
  21032. *
  21033. * **Supported Networks**
  21034. *
  21035. * - Ethereum Mainnet (``mainnet``)
  21036. * - Goerli Testnet (``goerli``)
  21037. * - Sepolia Testnet (``sepolia``)
  21038. * - Holesky Testnet (``holesky``)
  21039. * - Arbitrum (``arbitrum``)
  21040. * - Arbitrum Goerli Testnet (``arbitrum-goerli``)
  21041. * - Base (``base``)
  21042. * - Base Sepolia Testnet (``base-sepolia``)
  21043. * - BNB Smart Chain Mainnet (``bnb``)
  21044. * - BNB Smart Chain Testnet (``bnbt``)
  21045. * - Optimism (``optimism``)
  21046. * - Optimism Goerli Testnet (``optimism-goerli``)
  21047. * - Polygon (``matic``)
  21048. * - Polygon Mumbai Testnet (``matic-mumbai``)
  21049. * - Polygon Amoy Testnet (``matic-amoy``)
  21050. *
  21051. * @_subsection api/providers/thirdparty:Etherscan [providers-etherscan]
  21052. */
  21053. const THROTTLE = 2000;
  21054. function isPromise(value) {
  21055. return (value && typeof (value.then) === "function");
  21056. }
  21057. const EtherscanPluginId = "org.ethers.plugins.provider.Etherscan";
  21058. /**
  21059. * A Network can include an **EtherscanPlugin** to provide
  21060. * a custom base URL.
  21061. *
  21062. * @_docloc: api/providers/thirdparty:Etherscan
  21063. */
  21064. class EtherscanPlugin extends NetworkPlugin {
  21065. /**
  21066. * The Etherscan API base URL.
  21067. */
  21068. baseUrl;
  21069. /**
  21070. * Creates a new **EtherscanProvider** which will use
  21071. * %%baseUrl%%.
  21072. */
  21073. constructor(baseUrl) {
  21074. super(EtherscanPluginId);
  21075. defineProperties(this, { baseUrl });
  21076. }
  21077. clone() {
  21078. return new EtherscanPlugin(this.baseUrl);
  21079. }
  21080. }
  21081. const skipKeys = ["enableCcipRead"];
  21082. let nextId = 1;
  21083. /**
  21084. * The **EtherscanBaseProvider** is the super-class of
  21085. * [[EtherscanProvider]], which should generally be used instead.
  21086. *
  21087. * Since the **EtherscanProvider** includes additional code for
  21088. * [[Contract]] access, in //rare cases// that contracts are not
  21089. * used, this class can reduce code size.
  21090. *
  21091. * @_docloc: api/providers/thirdparty:Etherscan
  21092. */
  21093. class EtherscanProvider extends AbstractProvider {
  21094. /**
  21095. * The connected network.
  21096. */
  21097. network;
  21098. /**
  21099. * The API key or null if using the community provided bandwidth.
  21100. */
  21101. apiKey;
  21102. #plugin;
  21103. /**
  21104. * Creates a new **EtherscanBaseProvider**.
  21105. */
  21106. constructor(_network, _apiKey) {
  21107. const apiKey = (_apiKey != null) ? _apiKey : null;
  21108. super();
  21109. const network = Network.from(_network);
  21110. this.#plugin = network.getPlugin(EtherscanPluginId);
  21111. defineProperties(this, { apiKey, network });
  21112. // Test that the network is supported by Etherscan
  21113. this.getBaseUrl();
  21114. }
  21115. /**
  21116. * Returns the base URL.
  21117. *
  21118. * If an [[EtherscanPlugin]] is configured on the
  21119. * [[EtherscanBaseProvider_network]], returns the plugin's
  21120. * baseUrl.
  21121. */
  21122. getBaseUrl() {
  21123. if (this.#plugin) {
  21124. return this.#plugin.baseUrl;
  21125. }
  21126. switch (this.network.name) {
  21127. case "mainnet":
  21128. return "https:/\/api.etherscan.io";
  21129. case "goerli":
  21130. return "https:/\/api-goerli.etherscan.io";
  21131. case "sepolia":
  21132. return "https:/\/api-sepolia.etherscan.io";
  21133. case "holesky":
  21134. return "https:/\/api-holesky.etherscan.io";
  21135. case "arbitrum":
  21136. return "https:/\/api.arbiscan.io";
  21137. case "arbitrum-goerli":
  21138. return "https:/\/api-goerli.arbiscan.io";
  21139. case "base":
  21140. return "https:/\/api.basescan.org";
  21141. case "base-sepolia":
  21142. return "https:/\/api-sepolia.basescan.org";
  21143. case "bnb":
  21144. return "https:/\/api.bscscan.com";
  21145. case "bnbt":
  21146. return "https:/\/api-testnet.bscscan.com";
  21147. case "matic":
  21148. return "https:/\/api.polygonscan.com";
  21149. case "matic-amoy":
  21150. return "https:/\/api-amoy.polygonscan.com";
  21151. case "matic-mumbai":
  21152. return "https:/\/api-testnet.polygonscan.com";
  21153. case "optimism":
  21154. return "https:/\/api-optimistic.etherscan.io";
  21155. case "optimism-goerli":
  21156. return "https:/\/api-goerli-optimistic.etherscan.io";
  21157. }
  21158. assertArgument(false, "unsupported network", "network", this.network);
  21159. }
  21160. /**
  21161. * Returns the URL for the %%module%% and %%params%%.
  21162. */
  21163. getUrl(module, params) {
  21164. const query = Object.keys(params).reduce((accum, key) => {
  21165. const value = params[key];
  21166. if (value != null) {
  21167. accum += `&${key}=${value}`;
  21168. }
  21169. return accum;
  21170. }, "");
  21171. const apiKey = ((this.apiKey) ? `&apikey=${this.apiKey}` : "");
  21172. return `${this.getBaseUrl()}/api?module=${module}${query}${apiKey}`;
  21173. }
  21174. /**
  21175. * Returns the URL for using POST requests.
  21176. */
  21177. getPostUrl() {
  21178. return `${this.getBaseUrl()}/api`;
  21179. }
  21180. /**
  21181. * Returns the parameters for using POST requests.
  21182. */
  21183. getPostData(module, params) {
  21184. params.module = module;
  21185. params.apikey = this.apiKey;
  21186. return params;
  21187. }
  21188. async detectNetwork() {
  21189. return this.network;
  21190. }
  21191. /**
  21192. * Resolves to the result of calling %%module%% with %%params%%.
  21193. *
  21194. * If %%post%%, the request is made as a POST request.
  21195. */
  21196. async fetch(module, params, post) {
  21197. const id = nextId++;
  21198. const url = (post ? this.getPostUrl() : this.getUrl(module, params));
  21199. const payload = (post ? this.getPostData(module, params) : null);
  21200. this.emit("debug", { action: "sendRequest", id, url, payload: payload });
  21201. const request = new FetchRequest(url);
  21202. request.setThrottleParams({ slotInterval: 1000 });
  21203. request.retryFunc = (req, resp, attempt) => {
  21204. if (this.isCommunityResource()) {
  21205. showThrottleMessage("Etherscan");
  21206. }
  21207. return Promise.resolve(true);
  21208. };
  21209. request.processFunc = async (request, response) => {
  21210. const result = response.hasBody() ? JSON.parse(toUtf8String(response.body)) : {};
  21211. const throttle = ((typeof (result.result) === "string") ? result.result : "").toLowerCase().indexOf("rate limit") >= 0;
  21212. if (module === "proxy") {
  21213. // This JSON response indicates we are being throttled
  21214. if (result && result.status == 0 && result.message == "NOTOK" && throttle) {
  21215. this.emit("debug", { action: "receiveError", id, reason: "proxy-NOTOK", error: result });
  21216. response.throwThrottleError(result.result, THROTTLE);
  21217. }
  21218. }
  21219. else {
  21220. if (throttle) {
  21221. this.emit("debug", { action: "receiveError", id, reason: "null result", error: result.result });
  21222. response.throwThrottleError(result.result, THROTTLE);
  21223. }
  21224. }
  21225. return response;
  21226. };
  21227. if (payload) {
  21228. request.setHeader("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
  21229. request.body = Object.keys(payload).map((k) => `${k}=${payload[k]}`).join("&");
  21230. }
  21231. const response = await request.send();
  21232. try {
  21233. response.assertOk();
  21234. }
  21235. catch (error) {
  21236. this.emit("debug", { action: "receiveError", id, error, reason: "assertOk" });
  21237. assert(false, "response error", "SERVER_ERROR", { request, response });
  21238. }
  21239. if (!response.hasBody()) {
  21240. this.emit("debug", { action: "receiveError", id, error: "missing body", reason: "null body" });
  21241. assert(false, "missing response", "SERVER_ERROR", { request, response });
  21242. }
  21243. const result = JSON.parse(toUtf8String(response.body));
  21244. if (module === "proxy") {
  21245. if (result.jsonrpc != "2.0") {
  21246. this.emit("debug", { action: "receiveError", id, result, reason: "invalid JSON-RPC" });
  21247. assert(false, "invalid JSON-RPC response (missing jsonrpc='2.0')", "SERVER_ERROR", { request, response, info: { result } });
  21248. }
  21249. if (result.error) {
  21250. this.emit("debug", { action: "receiveError", id, result, reason: "JSON-RPC error" });
  21251. assert(false, "error response", "SERVER_ERROR", { request, response, info: { result } });
  21252. }
  21253. this.emit("debug", { action: "receiveRequest", id, result });
  21254. return result.result;
  21255. }
  21256. else {
  21257. // getLogs, getHistory have weird success responses
  21258. if (result.status == 0 && (result.message === "No records found" || result.message === "No transactions found")) {
  21259. this.emit("debug", { action: "receiveRequest", id, result });
  21260. return result.result;
  21261. }
  21262. if (result.status != 1 || (typeof (result.message) === "string" && !result.message.match(/^OK/))) {
  21263. this.emit("debug", { action: "receiveError", id, result });
  21264. assert(false, "error response", "SERVER_ERROR", { request, response, info: { result } });
  21265. }
  21266. this.emit("debug", { action: "receiveRequest", id, result });
  21267. return result.result;
  21268. }
  21269. }
  21270. /**
  21271. * Returns %%transaction%% normalized for the Etherscan API.
  21272. */
  21273. _getTransactionPostData(transaction) {
  21274. const result = {};
  21275. for (let key in transaction) {
  21276. if (skipKeys.indexOf(key) >= 0) {
  21277. continue;
  21278. }
  21279. if (transaction[key] == null) {
  21280. continue;
  21281. }
  21282. let value = transaction[key];
  21283. if (key === "type" && value === 0) {
  21284. continue;
  21285. }
  21286. if (key === "blockTag" && value === "latest") {
  21287. continue;
  21288. }
  21289. // Quantity-types require no leading zero, unless 0
  21290. if ({ type: true, gasLimit: true, gasPrice: true, maxFeePerGs: true, maxPriorityFeePerGas: true, nonce: true, value: true }[key]) {
  21291. value = toQuantity(value);
  21292. }
  21293. else if (key === "accessList") {
  21294. value = "[" + accessListify(value).map((set) => {
  21295. return `{address:"${set.address}",storageKeys:["${set.storageKeys.join('","')}"]}`;
  21296. }).join(",") + "]";
  21297. }
  21298. else if (key === "blobVersionedHashes") {
  21299. if (value.length === 0) {
  21300. continue;
  21301. }
  21302. // @TODO: update this once the API supports blobs
  21303. assert(false, "Etherscan API does not support blobVersionedHashes", "UNSUPPORTED_OPERATION", {
  21304. operation: "_getTransactionPostData",
  21305. info: { transaction }
  21306. });
  21307. }
  21308. else {
  21309. value = hexlify(value);
  21310. }
  21311. result[key] = value;
  21312. }
  21313. return result;
  21314. }
  21315. /**
  21316. * Throws the normalized Etherscan error.
  21317. */
  21318. _checkError(req, error, transaction) {
  21319. // Pull any message out if, possible
  21320. let message = "";
  21321. if (isError(error, "SERVER_ERROR")) {
  21322. // Check for an error emitted by a proxy call
  21323. try {
  21324. message = error.info.result.error.message;
  21325. }
  21326. catch (e) { }
  21327. if (!message) {
  21328. try {
  21329. message = error.info.message;
  21330. }
  21331. catch (e) { }
  21332. }
  21333. }
  21334. if (req.method === "estimateGas") {
  21335. if (!message.match(/revert/i) && message.match(/insufficient funds/i)) {
  21336. assert(false, "insufficient funds", "INSUFFICIENT_FUNDS", {
  21337. transaction: req.transaction
  21338. });
  21339. }
  21340. }
  21341. if (req.method === "call" || req.method === "estimateGas") {
  21342. if (message.match(/execution reverted/i)) {
  21343. let data = "";
  21344. try {
  21345. data = error.info.result.error.data;
  21346. }
  21347. catch (error) { }
  21348. const e = AbiCoder.getBuiltinCallException(req.method, req.transaction, data);
  21349. e.info = { request: req, error };
  21350. throw e;
  21351. }
  21352. }
  21353. if (message) {
  21354. if (req.method === "broadcastTransaction") {
  21355. const transaction = Transaction.from(req.signedTransaction);
  21356. if (message.match(/replacement/i) && message.match(/underpriced/i)) {
  21357. assert(false, "replacement fee too low", "REPLACEMENT_UNDERPRICED", {
  21358. transaction
  21359. });
  21360. }
  21361. if (message.match(/insufficient funds/)) {
  21362. assert(false, "insufficient funds for intrinsic transaction cost", "INSUFFICIENT_FUNDS", {
  21363. transaction
  21364. });
  21365. }
  21366. if (message.match(/same hash was already imported|transaction nonce is too low|nonce too low/)) {
  21367. assert(false, "nonce has already been used", "NONCE_EXPIRED", {
  21368. transaction
  21369. });
  21370. }
  21371. }
  21372. }
  21373. // Something we could not process
  21374. throw error;
  21375. }
  21376. async _detectNetwork() {
  21377. return this.network;
  21378. }
  21379. async _perform(req) {
  21380. switch (req.method) {
  21381. case "chainId":
  21382. return this.network.chainId;
  21383. case "getBlockNumber":
  21384. return this.fetch("proxy", { action: "eth_blockNumber" });
  21385. case "getGasPrice":
  21386. return this.fetch("proxy", { action: "eth_gasPrice" });
  21387. case "getPriorityFee":
  21388. // This is temporary until Etherscan completes support
  21389. if (this.network.name === "mainnet") {
  21390. return "1000000000";
  21391. }
  21392. else if (this.network.name === "optimism") {
  21393. return "1000000";
  21394. }
  21395. else {
  21396. throw new Error("fallback onto the AbstractProvider default");
  21397. }
  21398. /* Working with Etherscan to get this added:
  21399. try {
  21400. const test = await this.fetch("proxy", {
  21401. action: "eth_maxPriorityFeePerGas"
  21402. });
  21403. console.log(test);
  21404. return test;
  21405. } catch (e) {
  21406. console.log("DEBUG", e);
  21407. throw e;
  21408. }
  21409. */
  21410. /* This might be safe; but due to rounding neither myself
  21411. or Etherscan are necessarily comfortable with this. :)
  21412. try {
  21413. const result = await this.fetch("gastracker", { action: "gasoracle" });
  21414. console.log(result);
  21415. const gasPrice = parseUnits(result.SafeGasPrice, "gwei");
  21416. const baseFee = parseUnits(result.suggestBaseFee, "gwei");
  21417. const priorityFee = gasPrice - baseFee;
  21418. if (priorityFee < 0) { throw new Error("negative priority fee; defer to abstract provider default"); }
  21419. return priorityFee;
  21420. } catch (error) {
  21421. console.log("DEBUG", error);
  21422. throw error;
  21423. }
  21424. */
  21425. case "getBalance":
  21426. // Returns base-10 result
  21427. return this.fetch("account", {
  21428. action: "balance",
  21429. address: req.address,
  21430. tag: req.blockTag
  21431. });
  21432. case "getTransactionCount":
  21433. return this.fetch("proxy", {
  21434. action: "eth_getTransactionCount",
  21435. address: req.address,
  21436. tag: req.blockTag
  21437. });
  21438. case "getCode":
  21439. return this.fetch("proxy", {
  21440. action: "eth_getCode",
  21441. address: req.address,
  21442. tag: req.blockTag
  21443. });
  21444. case "getStorage":
  21445. return this.fetch("proxy", {
  21446. action: "eth_getStorageAt",
  21447. address: req.address,
  21448. position: req.position,
  21449. tag: req.blockTag
  21450. });
  21451. case "broadcastTransaction":
  21452. return this.fetch("proxy", {
  21453. action: "eth_sendRawTransaction",
  21454. hex: req.signedTransaction
  21455. }, true).catch((error) => {
  21456. return this._checkError(req, error, req.signedTransaction);
  21457. });
  21458. case "getBlock":
  21459. if ("blockTag" in req) {
  21460. return this.fetch("proxy", {
  21461. action: "eth_getBlockByNumber",
  21462. tag: req.blockTag,
  21463. boolean: (req.includeTransactions ? "true" : "false")
  21464. });
  21465. }
  21466. assert(false, "getBlock by blockHash not supported by Etherscan", "UNSUPPORTED_OPERATION", {
  21467. operation: "getBlock(blockHash)"
  21468. });
  21469. case "getTransaction":
  21470. return this.fetch("proxy", {
  21471. action: "eth_getTransactionByHash",
  21472. txhash: req.hash
  21473. });
  21474. case "getTransactionReceipt":
  21475. return this.fetch("proxy", {
  21476. action: "eth_getTransactionReceipt",
  21477. txhash: req.hash
  21478. });
  21479. case "call": {
  21480. if (req.blockTag !== "latest") {
  21481. throw new Error("EtherscanProvider does not support blockTag for call");
  21482. }
  21483. const postData = this._getTransactionPostData(req.transaction);
  21484. postData.module = "proxy";
  21485. postData.action = "eth_call";
  21486. try {
  21487. return await this.fetch("proxy", postData, true);
  21488. }
  21489. catch (error) {
  21490. return this._checkError(req, error, req.transaction);
  21491. }
  21492. }
  21493. case "estimateGas": {
  21494. const postData = this._getTransactionPostData(req.transaction);
  21495. postData.module = "proxy";
  21496. postData.action = "eth_estimateGas";
  21497. try {
  21498. return await this.fetch("proxy", postData, true);
  21499. }
  21500. catch (error) {
  21501. return this._checkError(req, error, req.transaction);
  21502. }
  21503. }
  21504. }
  21505. return super._perform(req);
  21506. }
  21507. async getNetwork() {
  21508. return this.network;
  21509. }
  21510. /**
  21511. * Resolves to the current price of ether.
  21512. *
  21513. * This returns ``0`` on any network other than ``mainnet``.
  21514. */
  21515. async getEtherPrice() {
  21516. if (this.network.name !== "mainnet") {
  21517. return 0.0;
  21518. }
  21519. return parseFloat((await this.fetch("stats", { action: "ethprice" })).ethusd);
  21520. }
  21521. /**
  21522. * Resolves to a [Contract]] for %%address%%, using the
  21523. * Etherscan API to retreive the Contract ABI.
  21524. */
  21525. async getContract(_address) {
  21526. let address = this._getAddress(_address);
  21527. if (isPromise(address)) {
  21528. address = await address;
  21529. }
  21530. try {
  21531. const resp = await this.fetch("contract", {
  21532. action: "getabi", address
  21533. });
  21534. const abi = JSON.parse(resp);
  21535. return new Contract(address, abi, this);
  21536. }
  21537. catch (error) {
  21538. return null;
  21539. }
  21540. }
  21541. isCommunityResource() {
  21542. return (this.apiKey == null);
  21543. }
  21544. }
  21545. function getGlobal() {
  21546. if (typeof self !== 'undefined') {
  21547. return self;
  21548. }
  21549. if (typeof window !== 'undefined') {
  21550. return window;
  21551. }
  21552. if (typeof global !== 'undefined') {
  21553. return global;
  21554. }
  21555. throw new Error('unable to locate global object');
  21556. }
  21557. const _WebSocket = getGlobal().WebSocket;
  21558. /**
  21559. * Generic long-lived socket provider.
  21560. *
  21561. * Sub-classing notes
  21562. * - a sub-class MUST call the `_start()` method once connected
  21563. * - a sub-class MUST override the `_write(string)` method
  21564. * - a sub-class MUST call `_processMessage(string)` for each message
  21565. *
  21566. * @_subsection: api/providers/abstract-provider:Socket Providers [about-socketProvider]
  21567. */
  21568. /**
  21569. * A **SocketSubscriber** uses a socket transport to handle events and
  21570. * should use [[_emit]] to manage the events.
  21571. */
  21572. class SocketSubscriber {
  21573. #provider;
  21574. #filter;
  21575. /**
  21576. * The filter.
  21577. */
  21578. get filter() { return JSON.parse(this.#filter); }
  21579. #filterId;
  21580. #paused;
  21581. #emitPromise;
  21582. /**
  21583. * Creates a new **SocketSubscriber** attached to %%provider%% listening
  21584. * to %%filter%%.
  21585. */
  21586. constructor(provider, filter) {
  21587. this.#provider = provider;
  21588. this.#filter = JSON.stringify(filter);
  21589. this.#filterId = null;
  21590. this.#paused = null;
  21591. this.#emitPromise = null;
  21592. }
  21593. start() {
  21594. this.#filterId = this.#provider.send("eth_subscribe", this.filter).then((filterId) => {
  21595. this.#provider._register(filterId, this);
  21596. return filterId;
  21597. });
  21598. }
  21599. stop() {
  21600. (this.#filterId).then((filterId) => {
  21601. if (this.#provider.destroyed) {
  21602. return;
  21603. }
  21604. this.#provider.send("eth_unsubscribe", [filterId]);
  21605. });
  21606. this.#filterId = null;
  21607. }
  21608. // @TODO: pause should trap the current blockNumber, unsub, and on resume use getLogs
  21609. // and resume
  21610. pause(dropWhilePaused) {
  21611. assert(dropWhilePaused, "preserve logs while paused not supported by SocketSubscriber yet", "UNSUPPORTED_OPERATION", { operation: "pause(false)" });
  21612. this.#paused = !!dropWhilePaused;
  21613. }
  21614. resume() {
  21615. this.#paused = null;
  21616. }
  21617. /**
  21618. * @_ignore:
  21619. */
  21620. _handleMessage(message) {
  21621. if (this.#filterId == null) {
  21622. return;
  21623. }
  21624. if (this.#paused === null) {
  21625. let emitPromise = this.#emitPromise;
  21626. if (emitPromise == null) {
  21627. emitPromise = this._emit(this.#provider, message);
  21628. }
  21629. else {
  21630. emitPromise = emitPromise.then(async () => {
  21631. await this._emit(this.#provider, message);
  21632. });
  21633. }
  21634. this.#emitPromise = emitPromise.then(() => {
  21635. if (this.#emitPromise === emitPromise) {
  21636. this.#emitPromise = null;
  21637. }
  21638. });
  21639. }
  21640. }
  21641. /**
  21642. * Sub-classes **must** override this to emit the events on the
  21643. * provider.
  21644. */
  21645. async _emit(provider, message) {
  21646. throw new Error("sub-classes must implemente this; _emit");
  21647. }
  21648. }
  21649. /**
  21650. * A **SocketBlockSubscriber** listens for ``newHeads`` events and emits
  21651. * ``"block"`` events.
  21652. */
  21653. class SocketBlockSubscriber extends SocketSubscriber {
  21654. /**
  21655. * @_ignore:
  21656. */
  21657. constructor(provider) {
  21658. super(provider, ["newHeads"]);
  21659. }
  21660. async _emit(provider, message) {
  21661. provider.emit("block", parseInt(message.number));
  21662. }
  21663. }
  21664. /**
  21665. * A **SocketPendingSubscriber** listens for pending transacitons and emits
  21666. * ``"pending"`` events.
  21667. */
  21668. class SocketPendingSubscriber extends SocketSubscriber {
  21669. /**
  21670. * @_ignore:
  21671. */
  21672. constructor(provider) {
  21673. super(provider, ["newPendingTransactions"]);
  21674. }
  21675. async _emit(provider, message) {
  21676. provider.emit("pending", message);
  21677. }
  21678. }
  21679. /**
  21680. * A **SocketEventSubscriber** listens for event logs.
  21681. */
  21682. class SocketEventSubscriber extends SocketSubscriber {
  21683. #logFilter;
  21684. /**
  21685. * The filter.
  21686. */
  21687. get logFilter() { return JSON.parse(this.#logFilter); }
  21688. /**
  21689. * @_ignore:
  21690. */
  21691. constructor(provider, filter) {
  21692. super(provider, ["logs", filter]);
  21693. this.#logFilter = JSON.stringify(filter);
  21694. }
  21695. async _emit(provider, message) {
  21696. provider.emit(this.logFilter, provider._wrapLog(message, provider._network));
  21697. }
  21698. }
  21699. /**
  21700. * A **SocketProvider** is backed by a long-lived connection over a
  21701. * socket, which can subscribe and receive real-time messages over
  21702. * its communication channel.
  21703. */
  21704. class SocketProvider extends JsonRpcApiProvider {
  21705. #callbacks;
  21706. // Maps each filterId to its subscriber
  21707. #subs;
  21708. // If any events come in before a subscriber has finished
  21709. // registering, queue them
  21710. #pending;
  21711. /**
  21712. * Creates a new **SocketProvider** connected to %%network%%.
  21713. *
  21714. * If unspecified, the network will be discovered.
  21715. */
  21716. constructor(network, _options) {
  21717. // Copy the options
  21718. const options = Object.assign({}, (_options != null) ? _options : {});
  21719. // Support for batches is generally not supported for
  21720. // connection-base providers; if this changes in the future
  21721. // the _send should be updated to reflect this
  21722. assertArgument(options.batchMaxCount == null || options.batchMaxCount === 1, "sockets-based providers do not support batches", "options.batchMaxCount", _options);
  21723. options.batchMaxCount = 1;
  21724. // Socket-based Providers (generally) cannot change their network,
  21725. // since they have a long-lived connection; but let people override
  21726. // this if they have just cause.
  21727. if (options.staticNetwork == null) {
  21728. options.staticNetwork = true;
  21729. }
  21730. super(network, options);
  21731. this.#callbacks = new Map();
  21732. this.#subs = new Map();
  21733. this.#pending = new Map();
  21734. }
  21735. // This value is only valid after _start has been called
  21736. /*
  21737. get _network(): Network {
  21738. if (this.#network == null) {
  21739. throw new Error("this shouldn't happen");
  21740. }
  21741. return this.#network.clone();
  21742. }
  21743. */
  21744. _getSubscriber(sub) {
  21745. switch (sub.type) {
  21746. case "close":
  21747. return new UnmanagedSubscriber("close");
  21748. case "block":
  21749. return new SocketBlockSubscriber(this);
  21750. case "pending":
  21751. return new SocketPendingSubscriber(this);
  21752. case "event":
  21753. return new SocketEventSubscriber(this, sub.filter);
  21754. case "orphan":
  21755. // Handled auto-matically within AbstractProvider
  21756. // when the log.removed = true
  21757. if (sub.filter.orphan === "drop-log") {
  21758. return new UnmanagedSubscriber("drop-log");
  21759. }
  21760. }
  21761. return super._getSubscriber(sub);
  21762. }
  21763. /**
  21764. * Register a new subscriber. This is used internalled by Subscribers
  21765. * and generally is unecessary unless extending capabilities.
  21766. */
  21767. _register(filterId, subscriber) {
  21768. this.#subs.set(filterId, subscriber);
  21769. const pending = this.#pending.get(filterId);
  21770. if (pending) {
  21771. for (const message of pending) {
  21772. subscriber._handleMessage(message);
  21773. }
  21774. this.#pending.delete(filterId);
  21775. }
  21776. }
  21777. async _send(payload) {
  21778. // WebSocket provider doesn't accept batches
  21779. assertArgument(!Array.isArray(payload), "WebSocket does not support batch send", "payload", payload);
  21780. // @TODO: stringify payloads here and store to prevent mutations
  21781. // Prepare a promise to respond to
  21782. const promise = new Promise((resolve, reject) => {
  21783. this.#callbacks.set(payload.id, { payload, resolve, reject });
  21784. });
  21785. // Wait until the socket is connected before writing to it
  21786. await this._waitUntilReady();
  21787. // Write the request to the socket
  21788. await this._write(JSON.stringify(payload));
  21789. return [await promise];
  21790. }
  21791. // Sub-classes must call this once they are connected
  21792. /*
  21793. async _start(): Promise<void> {
  21794. if (this.#ready) { return; }
  21795. for (const { payload } of this.#callbacks.values()) {
  21796. await this._write(JSON.stringify(payload));
  21797. }
  21798. this.#ready = (async function() {
  21799. await super._start();
  21800. })();
  21801. }
  21802. */
  21803. /**
  21804. * Sub-classes **must** call this with messages received over their
  21805. * transport to be processed and dispatched.
  21806. */
  21807. async _processMessage(message) {
  21808. const result = (JSON.parse(message));
  21809. if (result && typeof (result) === "object" && "id" in result) {
  21810. const callback = this.#callbacks.get(result.id);
  21811. if (callback == null) {
  21812. this.emit("error", makeError("received result for unknown id", "UNKNOWN_ERROR", {
  21813. reasonCode: "UNKNOWN_ID",
  21814. result
  21815. }));
  21816. return;
  21817. }
  21818. this.#callbacks.delete(result.id);
  21819. callback.resolve(result);
  21820. }
  21821. else if (result && result.method === "eth_subscription") {
  21822. const filterId = result.params.subscription;
  21823. const subscriber = this.#subs.get(filterId);
  21824. if (subscriber) {
  21825. subscriber._handleMessage(result.params.result);
  21826. }
  21827. else {
  21828. let pending = this.#pending.get(filterId);
  21829. if (pending == null) {
  21830. pending = [];
  21831. this.#pending.set(filterId, pending);
  21832. }
  21833. pending.push(result.params.result);
  21834. }
  21835. }
  21836. else {
  21837. this.emit("error", makeError("received unexpected message", "UNKNOWN_ERROR", {
  21838. reasonCode: "UNEXPECTED_MESSAGE",
  21839. result
  21840. }));
  21841. return;
  21842. }
  21843. }
  21844. /**
  21845. * Sub-classes **must** override this to send %%message%% over their
  21846. * transport.
  21847. */
  21848. async _write(message) {
  21849. throw new Error("sub-classes must override this");
  21850. }
  21851. }
  21852. /**
  21853. * A JSON-RPC provider which is backed by a WebSocket.
  21854. *
  21855. * WebSockets are often preferred because they retain a live connection
  21856. * to a server, which permits more instant access to events.
  21857. *
  21858. * However, this incurs higher server infrasturture costs, so additional
  21859. * resources may be required to host your own WebSocket nodes and many
  21860. * third-party services charge additional fees for WebSocket endpoints.
  21861. */
  21862. class WebSocketProvider extends SocketProvider {
  21863. #connect;
  21864. #websocket;
  21865. get websocket() {
  21866. if (this.#websocket == null) {
  21867. throw new Error("websocket closed");
  21868. }
  21869. return this.#websocket;
  21870. }
  21871. constructor(url, network, options) {
  21872. super(network, options);
  21873. if (typeof (url) === "string") {
  21874. this.#connect = () => { return new _WebSocket(url); };
  21875. this.#websocket = this.#connect();
  21876. }
  21877. else if (typeof (url) === "function") {
  21878. this.#connect = url;
  21879. this.#websocket = url();
  21880. }
  21881. else {
  21882. this.#connect = null;
  21883. this.#websocket = url;
  21884. }
  21885. this.websocket.onopen = async () => {
  21886. try {
  21887. await this._start();
  21888. this.resume();
  21889. }
  21890. catch (error) {
  21891. console.log("failed to start WebsocketProvider", error);
  21892. // @TODO: now what? Attempt reconnect?
  21893. }
  21894. };
  21895. this.websocket.onmessage = (message) => {
  21896. this._processMessage(message.data);
  21897. };
  21898. /*
  21899. this.websocket.onclose = (event) => {
  21900. // @TODO: What event.code should we reconnect on?
  21901. const reconnect = false;
  21902. if (reconnect) {
  21903. this.pause(true);
  21904. if (this.#connect) {
  21905. this.#websocket = this.#connect();
  21906. this.#websocket.onopen = ...
  21907. // @TODO: this requires the super class to rebroadcast; move it there
  21908. }
  21909. this._reconnect();
  21910. }
  21911. };
  21912. */
  21913. }
  21914. async _write(message) {
  21915. this.websocket.send(message);
  21916. }
  21917. async destroy() {
  21918. if (this.#websocket != null) {
  21919. this.#websocket.close();
  21920. this.#websocket = null;
  21921. }
  21922. super.destroy();
  21923. }
  21924. }
  21925. /**
  21926. * [[link-infura]] provides a third-party service for connecting to
  21927. * various blockchains over JSON-RPC.
  21928. *
  21929. * **Supported Networks**
  21930. *
  21931. * - Ethereum Mainnet (``mainnet``)
  21932. * - Goerli Testnet (``goerli``)
  21933. * - Sepolia Testnet (``sepolia``)
  21934. * - Arbitrum (``arbitrum``)
  21935. * - Arbitrum Goerli Testnet (``arbitrum-goerli``)
  21936. * - Arbitrum Sepolia Testnet (``arbitrum-sepolia``)
  21937. * - Base (``base``)
  21938. * - Base Goerlia Testnet (``base-goerli``)
  21939. * - Base Sepolia Testnet (``base-sepolia``)
  21940. * - BNB Smart Chain Mainnet (``bnb``)
  21941. * - BNB Smart Chain Testnet (``bnbt``)
  21942. * - Linea (``linea``)
  21943. * - Linea Goerli Testnet (``linea-goerli``)
  21944. * - Linea Sepolia Testnet (``linea-sepolia``)
  21945. * - Optimism (``optimism``)
  21946. * - Optimism Goerli Testnet (``optimism-goerli``)
  21947. * - Optimism Sepolia Testnet (``optimism-sepolia``)
  21948. * - Polygon (``matic``)
  21949. * - Polygon Amoy Testnet (``matic-amoy``)
  21950. * - Polygon Mumbai Testnet (``matic-mumbai``)
  21951. *
  21952. * @_subsection: api/providers/thirdparty:INFURA [providers-infura]
  21953. */
  21954. const defaultProjectId = "84842078b09946638c03157f83405213";
  21955. function getHost$2(name) {
  21956. switch (name) {
  21957. case "mainnet":
  21958. return "mainnet.infura.io";
  21959. case "goerli":
  21960. return "goerli.infura.io";
  21961. case "sepolia":
  21962. return "sepolia.infura.io";
  21963. case "arbitrum":
  21964. return "arbitrum-mainnet.infura.io";
  21965. case "arbitrum-goerli":
  21966. return "arbitrum-goerli.infura.io";
  21967. case "arbitrum-sepolia":
  21968. return "arbitrum-sepolia.infura.io";
  21969. case "base":
  21970. return "base-mainnet.infura.io";
  21971. case "base-goerlia":
  21972. return "base-goerli.infura.io";
  21973. case "base-sepolia":
  21974. return "base-sepolia.infura.io";
  21975. case "bnb":
  21976. return "bnbsmartchain-mainnet.infura.io";
  21977. case "bnbt":
  21978. return "bnbsmartchain-testnet.infura.io";
  21979. case "linea":
  21980. return "linea-mainnet.infura.io";
  21981. case "linea-goerli":
  21982. return "linea-goerli.infura.io";
  21983. case "linea-sepolia":
  21984. return "linea-sepolia.infura.io";
  21985. case "matic":
  21986. return "polygon-mainnet.infura.io";
  21987. case "matic-amoy":
  21988. return "polygon-amoy.infura.io";
  21989. case "matic-mumbai":
  21990. return "polygon-mumbai.infura.io";
  21991. case "optimism":
  21992. return "optimism-mainnet.infura.io";
  21993. case "optimism-goerli":
  21994. return "optimism-goerli.infura.io";
  21995. case "optimism-sepolia":
  21996. return "optimism-sepolia.infura.io";
  21997. }
  21998. assertArgument(false, "unsupported network", "network", name);
  21999. }
  22000. /**
  22001. * The **InfuraWebSocketProvider** connects to the [[link-infura]]
  22002. * WebSocket end-points.
  22003. *
  22004. * By default, a highly-throttled API key is used, which is
  22005. * appropriate for quick prototypes and simple scripts. To
  22006. * gain access to an increased rate-limit, it is highly
  22007. * recommended to [sign up here](link-infura-signup).
  22008. */
  22009. class InfuraWebSocketProvider extends WebSocketProvider {
  22010. /**
  22011. * The Project ID for the INFURA connection.
  22012. */
  22013. projectId;
  22014. /**
  22015. * The Project Secret.
  22016. *
  22017. * If null, no authenticated requests are made. This should not
  22018. * be used outside of private contexts.
  22019. */
  22020. projectSecret;
  22021. /**
  22022. * Creates a new **InfuraWebSocketProvider**.
  22023. */
  22024. constructor(network, projectId) {
  22025. const provider = new InfuraProvider(network, projectId);
  22026. const req = provider._getConnection();
  22027. assert(!req.credentials, "INFURA WebSocket project secrets unsupported", "UNSUPPORTED_OPERATION", { operation: "InfuraProvider.getWebSocketProvider()" });
  22028. const url = req.url.replace(/^http/i, "ws").replace("/v3/", "/ws/v3/");
  22029. super(url, provider._network);
  22030. defineProperties(this, {
  22031. projectId: provider.projectId,
  22032. projectSecret: provider.projectSecret
  22033. });
  22034. }
  22035. isCommunityResource() {
  22036. return (this.projectId === defaultProjectId);
  22037. }
  22038. }
  22039. /**
  22040. * The **InfuraProvider** connects to the [[link-infura]]
  22041. * JSON-RPC end-points.
  22042. *
  22043. * By default, a highly-throttled API key is used, which is
  22044. * appropriate for quick prototypes and simple scripts. To
  22045. * gain access to an increased rate-limit, it is highly
  22046. * recommended to [sign up here](link-infura-signup).
  22047. */
  22048. class InfuraProvider extends JsonRpcProvider {
  22049. /**
  22050. * The Project ID for the INFURA connection.
  22051. */
  22052. projectId;
  22053. /**
  22054. * The Project Secret.
  22055. *
  22056. * If null, no authenticated requests are made. This should not
  22057. * be used outside of private contexts.
  22058. */
  22059. projectSecret;
  22060. /**
  22061. * Creates a new **InfuraProvider**.
  22062. */
  22063. constructor(_network, projectId, projectSecret) {
  22064. if (_network == null) {
  22065. _network = "mainnet";
  22066. }
  22067. const network = Network.from(_network);
  22068. if (projectId == null) {
  22069. projectId = defaultProjectId;
  22070. }
  22071. if (projectSecret == null) {
  22072. projectSecret = null;
  22073. }
  22074. const request = InfuraProvider.getRequest(network, projectId, projectSecret);
  22075. super(request, network, { staticNetwork: network });
  22076. defineProperties(this, { projectId, projectSecret });
  22077. }
  22078. _getProvider(chainId) {
  22079. try {
  22080. return new InfuraProvider(chainId, this.projectId, this.projectSecret);
  22081. }
  22082. catch (error) { }
  22083. return super._getProvider(chainId);
  22084. }
  22085. isCommunityResource() {
  22086. return (this.projectId === defaultProjectId);
  22087. }
  22088. /**
  22089. * Creates a new **InfuraWebSocketProvider**.
  22090. */
  22091. static getWebSocketProvider(network, projectId) {
  22092. return new InfuraWebSocketProvider(network, projectId);
  22093. }
  22094. /**
  22095. * Returns a prepared request for connecting to %%network%%
  22096. * with %%projectId%% and %%projectSecret%%.
  22097. */
  22098. static getRequest(network, projectId, projectSecret) {
  22099. if (projectId == null) {
  22100. projectId = defaultProjectId;
  22101. }
  22102. if (projectSecret == null) {
  22103. projectSecret = null;
  22104. }
  22105. const request = new FetchRequest(`https:/\/${getHost$2(network.name)}/v3/${projectId}`);
  22106. request.allowGzip = true;
  22107. if (projectSecret) {
  22108. request.setCredentials("", projectSecret);
  22109. }
  22110. if (projectId === defaultProjectId) {
  22111. request.retryFunc = async (request, response, attempt) => {
  22112. showThrottleMessage("InfuraProvider");
  22113. return true;
  22114. };
  22115. }
  22116. return request;
  22117. }
  22118. }
  22119. /**
  22120. * [[link-quicknode]] provides a third-party service for connecting to
  22121. * various blockchains over JSON-RPC.
  22122. *
  22123. * **Supported Networks**
  22124. *
  22125. * - Ethereum Mainnet (``mainnet``)
  22126. * - Goerli Testnet (``goerli``)
  22127. * - Sepolia Testnet (``sepolia``)
  22128. * - Holesky Testnet (``holesky``)
  22129. * - Arbitrum (``arbitrum``)
  22130. * - Arbitrum Goerli Testnet (``arbitrum-goerli``)
  22131. * - Arbitrum Sepolia Testnet (``arbitrum-sepolia``)
  22132. * - Base Mainnet (``base``);
  22133. * - Base Goerli Testnet (``base-goerli``);
  22134. * - Base Sepolia Testnet (``base-sepolia``);
  22135. * - BNB Smart Chain Mainnet (``bnb``)
  22136. * - BNB Smart Chain Testnet (``bnbt``)
  22137. * - Optimism (``optimism``)
  22138. * - Optimism Goerli Testnet (``optimism-goerli``)
  22139. * - Optimism Sepolia Testnet (``optimism-sepolia``)
  22140. * - Polygon (``matic``)
  22141. * - Polygon Mumbai Testnet (``matic-mumbai``)
  22142. *
  22143. * @_subsection: api/providers/thirdparty:QuickNode [providers-quicknode]
  22144. */
  22145. const defaultToken = "919b412a057b5e9c9b6dce193c5a60242d6efadb";
  22146. function getHost$1(name) {
  22147. switch (name) {
  22148. case "mainnet":
  22149. return "ethers.quiknode.pro";
  22150. case "goerli":
  22151. return "ethers.ethereum-goerli.quiknode.pro";
  22152. case "sepolia":
  22153. return "ethers.ethereum-sepolia.quiknode.pro";
  22154. case "holesky":
  22155. return "ethers.ethereum-holesky.quiknode.pro";
  22156. case "arbitrum":
  22157. return "ethers.arbitrum-mainnet.quiknode.pro";
  22158. case "arbitrum-goerli":
  22159. return "ethers.arbitrum-goerli.quiknode.pro";
  22160. case "arbitrum-sepolia":
  22161. return "ethers.arbitrum-sepolia.quiknode.pro";
  22162. case "base":
  22163. return "ethers.base-mainnet.quiknode.pro";
  22164. case "base-goerli":
  22165. return "ethers.base-goerli.quiknode.pro";
  22166. case "base-spolia":
  22167. return "ethers.base-sepolia.quiknode.pro";
  22168. case "bnb":
  22169. return "ethers.bsc.quiknode.pro";
  22170. case "bnbt":
  22171. return "ethers.bsc-testnet.quiknode.pro";
  22172. case "matic":
  22173. return "ethers.matic.quiknode.pro";
  22174. case "matic-mumbai":
  22175. return "ethers.matic-testnet.quiknode.pro";
  22176. case "optimism":
  22177. return "ethers.optimism.quiknode.pro";
  22178. case "optimism-goerli":
  22179. return "ethers.optimism-goerli.quiknode.pro";
  22180. case "optimism-sepolia":
  22181. return "ethers.optimism-sepolia.quiknode.pro";
  22182. case "xdai":
  22183. return "ethers.xdai.quiknode.pro";
  22184. }
  22185. assertArgument(false, "unsupported network", "network", name);
  22186. }
  22187. /*
  22188. @TODO:
  22189. These networks are not currently present in the Network
  22190. default included networks. Research them and ensure they
  22191. are EVM compatible and work with ethers
  22192. http://ethers.matic-amoy.quiknode.pro
  22193. http://ethers.avalanche-mainnet.quiknode.pro
  22194. http://ethers.avalanche-testnet.quiknode.pro
  22195. http://ethers.blast-sepolia.quiknode.pro
  22196. http://ethers.celo-mainnet.quiknode.pro
  22197. http://ethers.fantom.quiknode.pro
  22198. http://ethers.imx-demo.quiknode.pro
  22199. http://ethers.imx-mainnet.quiknode.pro
  22200. http://ethers.imx-testnet.quiknode.pro
  22201. http://ethers.near-mainnet.quiknode.pro
  22202. http://ethers.near-testnet.quiknode.pro
  22203. http://ethers.nova-mainnet.quiknode.pro
  22204. http://ethers.scroll-mainnet.quiknode.pro
  22205. http://ethers.scroll-testnet.quiknode.pro
  22206. http://ethers.tron-mainnet.quiknode.pro
  22207. http://ethers.zkevm-mainnet.quiknode.pro
  22208. http://ethers.zkevm-testnet.quiknode.pro
  22209. http://ethers.zksync-mainnet.quiknode.pro
  22210. http://ethers.zksync-testnet.quiknode.pro
  22211. */
  22212. /**
  22213. * The **QuickNodeProvider** connects to the [[link-quicknode]]
  22214. * JSON-RPC end-points.
  22215. *
  22216. * By default, a highly-throttled API token is used, which is
  22217. * appropriate for quick prototypes and simple scripts. To
  22218. * gain access to an increased rate-limit, it is highly
  22219. * recommended to [sign up here](link-quicknode).
  22220. */
  22221. class QuickNodeProvider extends JsonRpcProvider {
  22222. /**
  22223. * The API token.
  22224. */
  22225. token;
  22226. /**
  22227. * Creates a new **QuickNodeProvider**.
  22228. */
  22229. constructor(_network, token) {
  22230. if (_network == null) {
  22231. _network = "mainnet";
  22232. }
  22233. const network = Network.from(_network);
  22234. if (token == null) {
  22235. token = defaultToken;
  22236. }
  22237. const request = QuickNodeProvider.getRequest(network, token);
  22238. super(request, network, { staticNetwork: network });
  22239. defineProperties(this, { token });
  22240. }
  22241. _getProvider(chainId) {
  22242. try {
  22243. return new QuickNodeProvider(chainId, this.token);
  22244. }
  22245. catch (error) { }
  22246. return super._getProvider(chainId);
  22247. }
  22248. isCommunityResource() {
  22249. return (this.token === defaultToken);
  22250. }
  22251. /**
  22252. * Returns a new request prepared for %%network%% and the
  22253. * %%token%%.
  22254. */
  22255. static getRequest(network, token) {
  22256. if (token == null) {
  22257. token = defaultToken;
  22258. }
  22259. const request = new FetchRequest(`https:/\/${getHost$1(network.name)}/${token}`);
  22260. request.allowGzip = true;
  22261. //if (projectSecret) { request.setCredentials("", projectSecret); }
  22262. if (token === defaultToken) {
  22263. request.retryFunc = async (request, response, attempt) => {
  22264. showThrottleMessage("QuickNodeProvider");
  22265. return true;
  22266. };
  22267. }
  22268. return request;
  22269. }
  22270. }
  22271. /**
  22272. * A **FallbackProvider** provides resilience, security and performance
  22273. * in a way that is customizable and configurable.
  22274. *
  22275. * @_section: api/providers/fallback-provider:Fallback Provider [about-fallback-provider]
  22276. */
  22277. const BN_1 = BigInt("1");
  22278. const BN_2 = BigInt("2");
  22279. function shuffle(array) {
  22280. for (let i = array.length - 1; i > 0; i--) {
  22281. const j = Math.floor(Math.random() * (i + 1));
  22282. const tmp = array[i];
  22283. array[i] = array[j];
  22284. array[j] = tmp;
  22285. }
  22286. }
  22287. function stall$2(duration) {
  22288. return new Promise((resolve) => { setTimeout(resolve, duration); });
  22289. }
  22290. function getTime() { return (new Date()).getTime(); }
  22291. function stringify(value) {
  22292. return JSON.stringify(value, (key, value) => {
  22293. if (typeof (value) === "bigint") {
  22294. return { type: "bigint", value: value.toString() };
  22295. }
  22296. return value;
  22297. });
  22298. }
  22299. const defaultConfig = { stallTimeout: 400, priority: 1, weight: 1 };
  22300. const defaultState = {
  22301. blockNumber: -2, requests: 0, lateResponses: 0, errorResponses: 0,
  22302. outOfSync: -1, unsupportedEvents: 0, rollingDuration: 0, score: 0,
  22303. _network: null, _updateNumber: null, _totalTime: 0,
  22304. _lastFatalError: null, _lastFatalErrorTimestamp: 0
  22305. };
  22306. async function waitForSync(config, blockNumber) {
  22307. while (config.blockNumber < 0 || config.blockNumber < blockNumber) {
  22308. if (!config._updateNumber) {
  22309. config._updateNumber = (async () => {
  22310. try {
  22311. const blockNumber = await config.provider.getBlockNumber();
  22312. if (blockNumber > config.blockNumber) {
  22313. config.blockNumber = blockNumber;
  22314. }
  22315. }
  22316. catch (error) {
  22317. config.blockNumber = -2;
  22318. config._lastFatalError = error;
  22319. config._lastFatalErrorTimestamp = getTime();
  22320. }
  22321. config._updateNumber = null;
  22322. })();
  22323. }
  22324. await config._updateNumber;
  22325. config.outOfSync++;
  22326. if (config._lastFatalError) {
  22327. break;
  22328. }
  22329. }
  22330. }
  22331. function _normalize(value) {
  22332. if (value == null) {
  22333. return "null";
  22334. }
  22335. if (Array.isArray(value)) {
  22336. return "[" + (value.map(_normalize)).join(",") + "]";
  22337. }
  22338. if (typeof (value) === "object" && typeof (value.toJSON) === "function") {
  22339. return _normalize(value.toJSON());
  22340. }
  22341. switch (typeof (value)) {
  22342. case "boolean":
  22343. case "symbol":
  22344. return value.toString();
  22345. case "bigint":
  22346. case "number":
  22347. return BigInt(value).toString();
  22348. case "string":
  22349. return JSON.stringify(value);
  22350. case "object": {
  22351. const keys = Object.keys(value);
  22352. keys.sort();
  22353. return "{" + keys.map((k) => `${JSON.stringify(k)}:${_normalize(value[k])}`).join(",") + "}";
  22354. }
  22355. }
  22356. console.log("Could not serialize", value);
  22357. throw new Error("Hmm...");
  22358. }
  22359. function normalizeResult(value) {
  22360. if ("error" in value) {
  22361. const error = value.error;
  22362. return { tag: _normalize(error), value: error };
  22363. }
  22364. const result = value.result;
  22365. return { tag: _normalize(result), value: result };
  22366. }
  22367. // This strategy picks the highest weight result, as long as the weight is
  22368. // equal to or greater than quorum
  22369. function checkQuorum(quorum, results) {
  22370. const tally = new Map();
  22371. for (const { value, tag, weight } of results) {
  22372. const t = tally.get(tag) || { value, weight: 0 };
  22373. t.weight += weight;
  22374. tally.set(tag, t);
  22375. }
  22376. let best = null;
  22377. for (const r of tally.values()) {
  22378. if (r.weight >= quorum && (!best || r.weight > best.weight)) {
  22379. best = r;
  22380. }
  22381. }
  22382. if (best) {
  22383. return best.value;
  22384. }
  22385. return undefined;
  22386. }
  22387. function getMedian(quorum, results) {
  22388. let resultWeight = 0;
  22389. const errorMap = new Map();
  22390. let bestError = null;
  22391. const values = [];
  22392. for (const { value, tag, weight } of results) {
  22393. if (value instanceof Error) {
  22394. const e = errorMap.get(tag) || { value, weight: 0 };
  22395. e.weight += weight;
  22396. errorMap.set(tag, e);
  22397. if (bestError == null || e.weight > bestError.weight) {
  22398. bestError = e;
  22399. }
  22400. }
  22401. else {
  22402. values.push(BigInt(value));
  22403. resultWeight += weight;
  22404. }
  22405. }
  22406. if (resultWeight < quorum) {
  22407. // We have quorum for an error
  22408. if (bestError && bestError.weight >= quorum) {
  22409. return bestError.value;
  22410. }
  22411. // We do not have quorum for a result
  22412. return undefined;
  22413. }
  22414. // Get the sorted values
  22415. values.sort((a, b) => ((a < b) ? -1 : (b > a) ? 1 : 0));
  22416. const mid = Math.floor(values.length / 2);
  22417. // Odd-length; take the middle value
  22418. if (values.length % 2) {
  22419. return values[mid];
  22420. }
  22421. // Even length; take the ceiling of the mean of the center two values
  22422. return (values[mid - 1] + values[mid] + BN_1) / BN_2;
  22423. }
  22424. function getAnyResult(quorum, results) {
  22425. // If any value or error meets quorum, that is our preferred result
  22426. const result = checkQuorum(quorum, results);
  22427. if (result !== undefined) {
  22428. return result;
  22429. }
  22430. // Otherwise, do we have any result?
  22431. for (const r of results) {
  22432. if (r.value) {
  22433. return r.value;
  22434. }
  22435. }
  22436. // Nope!
  22437. return undefined;
  22438. }
  22439. function getFuzzyMode(quorum, results) {
  22440. if (quorum === 1) {
  22441. return getNumber(getMedian(quorum, results), "%internal");
  22442. }
  22443. const tally = new Map();
  22444. const add = (result, weight) => {
  22445. const t = tally.get(result) || { result, weight: 0 };
  22446. t.weight += weight;
  22447. tally.set(result, t);
  22448. };
  22449. for (const { weight, value } of results) {
  22450. const r = getNumber(value);
  22451. add(r - 1, weight);
  22452. add(r, weight);
  22453. add(r + 1, weight);
  22454. }
  22455. let bestWeight = 0;
  22456. let bestResult = undefined;
  22457. for (const { weight, result } of tally.values()) {
  22458. // Use this result, if this result meets quorum and has either:
  22459. // - a better weight
  22460. // - or equal weight, but the result is larger
  22461. if (weight >= quorum && (weight > bestWeight || (bestResult != null && weight === bestWeight && result > bestResult))) {
  22462. bestWeight = weight;
  22463. bestResult = result;
  22464. }
  22465. }
  22466. return bestResult;
  22467. }
  22468. /**
  22469. * A **FallbackProvider** manages several [[Providers]] providing
  22470. * resilience by switching between slow or misbehaving nodes, security
  22471. * by requiring multiple backends to aggree and performance by allowing
  22472. * faster backends to respond earlier.
  22473. *
  22474. */
  22475. class FallbackProvider extends AbstractProvider {
  22476. /**
  22477. * The number of backends that must agree on a value before it is
  22478. * accpeted.
  22479. */
  22480. quorum;
  22481. /**
  22482. * @_ignore:
  22483. */
  22484. eventQuorum;
  22485. /**
  22486. * @_ignore:
  22487. */
  22488. eventWorkers;
  22489. #configs;
  22490. #height;
  22491. #initialSyncPromise;
  22492. /**
  22493. * Creates a new **FallbackProvider** with %%providers%% connected to
  22494. * %%network%%.
  22495. *
  22496. * If a [[Provider]] is included in %%providers%%, defaults are used
  22497. * for the configuration.
  22498. */
  22499. constructor(providers, network, options) {
  22500. super(network, options);
  22501. this.#configs = providers.map((p) => {
  22502. if (p instanceof AbstractProvider) {
  22503. return Object.assign({ provider: p }, defaultConfig, defaultState);
  22504. }
  22505. else {
  22506. return Object.assign({}, defaultConfig, p, defaultState);
  22507. }
  22508. });
  22509. this.#height = -2;
  22510. this.#initialSyncPromise = null;
  22511. if (options && options.quorum != null) {
  22512. this.quorum = options.quorum;
  22513. }
  22514. else {
  22515. this.quorum = Math.ceil(this.#configs.reduce((accum, config) => {
  22516. accum += config.weight;
  22517. return accum;
  22518. }, 0) / 2);
  22519. }
  22520. this.eventQuorum = 1;
  22521. this.eventWorkers = 1;
  22522. assertArgument(this.quorum <= this.#configs.reduce((a, c) => (a + c.weight), 0), "quorum exceed provider weight", "quorum", this.quorum);
  22523. }
  22524. get providerConfigs() {
  22525. return this.#configs.map((c) => {
  22526. const result = Object.assign({}, c);
  22527. for (const key in result) {
  22528. if (key[0] === "_") {
  22529. delete result[key];
  22530. }
  22531. }
  22532. return result;
  22533. });
  22534. }
  22535. async _detectNetwork() {
  22536. return Network.from(getBigInt(await this._perform({ method: "chainId" })));
  22537. }
  22538. // @TODO: Add support to select providers to be the event subscriber
  22539. //_getSubscriber(sub: Subscription): Subscriber {
  22540. // throw new Error("@TODO");
  22541. //}
  22542. /**
  22543. * Transforms a %%req%% into the correct method call on %%provider%%.
  22544. */
  22545. async _translatePerform(provider, req) {
  22546. switch (req.method) {
  22547. case "broadcastTransaction":
  22548. return await provider.broadcastTransaction(req.signedTransaction);
  22549. case "call":
  22550. return await provider.call(Object.assign({}, req.transaction, { blockTag: req.blockTag }));
  22551. case "chainId":
  22552. return (await provider.getNetwork()).chainId;
  22553. case "estimateGas":
  22554. return await provider.estimateGas(req.transaction);
  22555. case "getBalance":
  22556. return await provider.getBalance(req.address, req.blockTag);
  22557. case "getBlock": {
  22558. const block = ("blockHash" in req) ? req.blockHash : req.blockTag;
  22559. return await provider.getBlock(block, req.includeTransactions);
  22560. }
  22561. case "getBlockNumber":
  22562. return await provider.getBlockNumber();
  22563. case "getCode":
  22564. return await provider.getCode(req.address, req.blockTag);
  22565. case "getGasPrice":
  22566. return (await provider.getFeeData()).gasPrice;
  22567. case "getPriorityFee":
  22568. return (await provider.getFeeData()).maxPriorityFeePerGas;
  22569. case "getLogs":
  22570. return await provider.getLogs(req.filter);
  22571. case "getStorage":
  22572. return await provider.getStorage(req.address, req.position, req.blockTag);
  22573. case "getTransaction":
  22574. return await provider.getTransaction(req.hash);
  22575. case "getTransactionCount":
  22576. return await provider.getTransactionCount(req.address, req.blockTag);
  22577. case "getTransactionReceipt":
  22578. return await provider.getTransactionReceipt(req.hash);
  22579. case "getTransactionResult":
  22580. return await provider.getTransactionResult(req.hash);
  22581. }
  22582. }
  22583. // Grab the next (random) config that is not already part of
  22584. // the running set
  22585. #getNextConfig(running) {
  22586. // @TODO: Maybe do a check here to favour (heavily) providers that
  22587. // do not require waitForSync and disfavour providers that
  22588. // seem down-ish or are behaving slowly
  22589. const configs = Array.from(running).map((r) => r.config);
  22590. // Shuffle the states, sorted by priority
  22591. const allConfigs = this.#configs.slice();
  22592. shuffle(allConfigs);
  22593. allConfigs.sort((a, b) => (a.priority - b.priority));
  22594. for (const config of allConfigs) {
  22595. if (config._lastFatalError) {
  22596. continue;
  22597. }
  22598. if (configs.indexOf(config) === -1) {
  22599. return config;
  22600. }
  22601. }
  22602. return null;
  22603. }
  22604. // Adds a new runner (if available) to running.
  22605. #addRunner(running, req) {
  22606. const config = this.#getNextConfig(running);
  22607. // No runners available
  22608. if (config == null) {
  22609. return null;
  22610. }
  22611. // Create a new runner
  22612. const runner = {
  22613. config, result: null, didBump: false,
  22614. perform: null, staller: null
  22615. };
  22616. const now = getTime();
  22617. // Start performing this operation
  22618. runner.perform = (async () => {
  22619. try {
  22620. config.requests++;
  22621. const result = await this._translatePerform(config.provider, req);
  22622. runner.result = { result };
  22623. }
  22624. catch (error) {
  22625. config.errorResponses++;
  22626. runner.result = { error };
  22627. }
  22628. const dt = (getTime() - now);
  22629. config._totalTime += dt;
  22630. config.rollingDuration = 0.95 * config.rollingDuration + 0.05 * dt;
  22631. runner.perform = null;
  22632. })();
  22633. // Start a staller; when this times out, it's time to force
  22634. // kicking off another runner because we are taking too long
  22635. runner.staller = (async () => {
  22636. await stall$2(config.stallTimeout);
  22637. runner.staller = null;
  22638. })();
  22639. running.add(runner);
  22640. return runner;
  22641. }
  22642. // Initializes the blockNumber and network for each runner and
  22643. // blocks until initialized
  22644. async #initialSync() {
  22645. let initialSync = this.#initialSyncPromise;
  22646. if (!initialSync) {
  22647. const promises = [];
  22648. this.#configs.forEach((config) => {
  22649. promises.push((async () => {
  22650. await waitForSync(config, 0);
  22651. if (!config._lastFatalError) {
  22652. config._network = await config.provider.getNetwork();
  22653. }
  22654. })());
  22655. });
  22656. this.#initialSyncPromise = initialSync = (async () => {
  22657. // Wait for all providers to have a block number and network
  22658. await Promise.all(promises);
  22659. // Check all the networks match
  22660. let chainId = null;
  22661. for (const config of this.#configs) {
  22662. if (config._lastFatalError) {
  22663. continue;
  22664. }
  22665. const network = (config._network);
  22666. if (chainId == null) {
  22667. chainId = network.chainId;
  22668. }
  22669. else if (network.chainId !== chainId) {
  22670. assert(false, "cannot mix providers on different networks", "UNSUPPORTED_OPERATION", {
  22671. operation: "new FallbackProvider"
  22672. });
  22673. }
  22674. }
  22675. })();
  22676. }
  22677. await initialSync;
  22678. }
  22679. async #checkQuorum(running, req) {
  22680. // Get all the result objects
  22681. const results = [];
  22682. for (const runner of running) {
  22683. if (runner.result != null) {
  22684. const { tag, value } = normalizeResult(runner.result);
  22685. results.push({ tag, value, weight: runner.config.weight });
  22686. }
  22687. }
  22688. // Are there enough results to event meet quorum?
  22689. if (results.reduce((a, r) => (a + r.weight), 0) < this.quorum) {
  22690. return undefined;
  22691. }
  22692. switch (req.method) {
  22693. case "getBlockNumber": {
  22694. // We need to get the bootstrap block height
  22695. if (this.#height === -2) {
  22696. this.#height = Math.ceil(getNumber(getMedian(this.quorum, this.#configs.filter((c) => (!c._lastFatalError)).map((c) => ({
  22697. value: c.blockNumber,
  22698. tag: getNumber(c.blockNumber).toString(),
  22699. weight: c.weight
  22700. })))));
  22701. }
  22702. // Find the mode across all the providers, allowing for
  22703. // a little drift between block heights
  22704. const mode = getFuzzyMode(this.quorum, results);
  22705. if (mode === undefined) {
  22706. return undefined;
  22707. }
  22708. if (mode > this.#height) {
  22709. this.#height = mode;
  22710. }
  22711. return this.#height;
  22712. }
  22713. case "getGasPrice":
  22714. case "getPriorityFee":
  22715. case "estimateGas":
  22716. return getMedian(this.quorum, results);
  22717. case "getBlock":
  22718. // Pending blocks are in the mempool and already
  22719. // quite untrustworthy; just grab anything
  22720. if ("blockTag" in req && req.blockTag === "pending") {
  22721. return getAnyResult(this.quorum, results);
  22722. }
  22723. return checkQuorum(this.quorum, results);
  22724. case "call":
  22725. case "chainId":
  22726. case "getBalance":
  22727. case "getTransactionCount":
  22728. case "getCode":
  22729. case "getStorage":
  22730. case "getTransaction":
  22731. case "getTransactionReceipt":
  22732. case "getLogs":
  22733. return checkQuorum(this.quorum, results);
  22734. case "broadcastTransaction":
  22735. return getAnyResult(this.quorum, results);
  22736. }
  22737. assert(false, "unsupported method", "UNSUPPORTED_OPERATION", {
  22738. operation: `_perform(${stringify(req.method)})`
  22739. });
  22740. }
  22741. async #waitForQuorum(running, req) {
  22742. if (running.size === 0) {
  22743. throw new Error("no runners?!");
  22744. }
  22745. // Any promises that are interesting to watch for; an expired stall
  22746. // or a successful perform
  22747. const interesting = [];
  22748. let newRunners = 0;
  22749. for (const runner of running) {
  22750. // No responses, yet; keep an eye on it
  22751. if (runner.perform) {
  22752. interesting.push(runner.perform);
  22753. }
  22754. // Still stalling...
  22755. if (runner.staller) {
  22756. interesting.push(runner.staller);
  22757. continue;
  22758. }
  22759. // This runner has already triggered another runner
  22760. if (runner.didBump) {
  22761. continue;
  22762. }
  22763. // Got a response (result or error) or stalled; kick off another runner
  22764. runner.didBump = true;
  22765. newRunners++;
  22766. }
  22767. // Check if we have reached quorum on a result (or error)
  22768. const value = await this.#checkQuorum(running, req);
  22769. if (value !== undefined) {
  22770. if (value instanceof Error) {
  22771. throw value;
  22772. }
  22773. return value;
  22774. }
  22775. // Add any new runners, because a staller timed out or a result
  22776. // or error response came in.
  22777. for (let i = 0; i < newRunners; i++) {
  22778. this.#addRunner(running, req);
  22779. }
  22780. // All providers have returned, and we have no result
  22781. assert(interesting.length > 0, "quorum not met", "SERVER_ERROR", {
  22782. request: "%sub-requests",
  22783. info: { request: req, results: Array.from(running).map((r) => stringify(r.result)) }
  22784. });
  22785. // Wait for someone to either complete its perform or stall out
  22786. await Promise.race(interesting);
  22787. // This is recursive, but at worst case the depth is 2x the
  22788. // number of providers (each has a perform and a staller)
  22789. return await this.#waitForQuorum(running, req);
  22790. }
  22791. async _perform(req) {
  22792. // Broadcasting a transaction is rare (ish) and already incurs
  22793. // a cost on the user, so spamming is safe-ish. Just send it to
  22794. // every backend.
  22795. if (req.method === "broadcastTransaction") {
  22796. // Once any broadcast provides a positive result, use it. No
  22797. // need to wait for anyone else
  22798. const results = this.#configs.map((c) => null);
  22799. const broadcasts = this.#configs.map(async ({ provider, weight }, index) => {
  22800. try {
  22801. const result = await provider._perform(req);
  22802. results[index] = Object.assign(normalizeResult({ result }), { weight });
  22803. }
  22804. catch (error) {
  22805. results[index] = Object.assign(normalizeResult({ error }), { weight });
  22806. }
  22807. });
  22808. // As each promise finishes...
  22809. while (true) {
  22810. // Check for a valid broadcast result
  22811. const done = results.filter((r) => (r != null));
  22812. for (const { value } of done) {
  22813. if (!(value instanceof Error)) {
  22814. return value;
  22815. }
  22816. }
  22817. // Check for a legit broadcast error (one which we cannot
  22818. // recover from; some nodes may return the following red
  22819. // herring events:
  22820. // - alredy seend (UNKNOWN_ERROR)
  22821. // - NONCE_EXPIRED
  22822. // - REPLACEMENT_UNDERPRICED
  22823. const result = checkQuorum(this.quorum, results.filter((r) => (r != null)));
  22824. if (isError(result, "INSUFFICIENT_FUNDS")) {
  22825. throw result;
  22826. }
  22827. // Kick off the next provider (if any)
  22828. const waiting = broadcasts.filter((b, i) => (results[i] == null));
  22829. if (waiting.length === 0) {
  22830. break;
  22831. }
  22832. await Promise.race(waiting);
  22833. }
  22834. // Use standard quorum results; any result was returned above,
  22835. // so this will find any error that met quorum if any
  22836. const result = getAnyResult(this.quorum, results);
  22837. assert(result !== undefined, "problem multi-broadcasting", "SERVER_ERROR", {
  22838. request: "%sub-requests",
  22839. info: { request: req, results: results.map(stringify) }
  22840. });
  22841. if (result instanceof Error) {
  22842. throw result;
  22843. }
  22844. return result;
  22845. }
  22846. await this.#initialSync();
  22847. // Bootstrap enough runners to meet quorum
  22848. const running = new Set();
  22849. let inflightQuorum = 0;
  22850. while (true) {
  22851. const runner = this.#addRunner(running, req);
  22852. if (runner == null) {
  22853. break;
  22854. }
  22855. inflightQuorum += runner.config.weight;
  22856. if (inflightQuorum >= this.quorum) {
  22857. break;
  22858. }
  22859. }
  22860. const result = await this.#waitForQuorum(running, req);
  22861. // Track requests sent to a provider that are still
  22862. // outstanding after quorum has been otherwise found
  22863. for (const runner of running) {
  22864. if (runner.perform && runner.result == null) {
  22865. runner.config.lateResponses++;
  22866. }
  22867. }
  22868. return result;
  22869. }
  22870. async destroy() {
  22871. for (const { provider } of this.#configs) {
  22872. provider.destroy();
  22873. }
  22874. super.destroy();
  22875. }
  22876. }
  22877. function isWebSocketLike(value) {
  22878. return (value && typeof (value.send) === "function" &&
  22879. typeof (value.close) === "function");
  22880. }
  22881. const Testnets = "goerli kovan sepolia classicKotti optimism-goerli arbitrum-goerli matic-mumbai bnbt".split(" ");
  22882. /**
  22883. * Returns a default provider for %%network%%.
  22884. *
  22885. * If %%network%% is a [[WebSocketLike]] or string that begins with
  22886. * ``"ws:"`` or ``"wss:"``, a [[WebSocketProvider]] is returned backed
  22887. * by that WebSocket or URL.
  22888. *
  22889. * If %%network%% is a string that begins with ``"HTTP:"`` or ``"HTTPS:"``,
  22890. * a [[JsonRpcProvider]] is returned connected to that URL.
  22891. *
  22892. * Otherwise, a default provider is created backed by well-known public
  22893. * Web3 backends (such as [[link-infura]]) using community-provided API
  22894. * keys.
  22895. *
  22896. * The %%options%% allows specifying custom API keys per backend (setting
  22897. * an API key to ``"-"`` will omit that provider) and ``options.exclusive``
  22898. * can be set to either a backend name or and array of backend names, which
  22899. * will whitelist **only** those backends.
  22900. *
  22901. * Current backend strings supported are:
  22902. * - ``"alchemy"``
  22903. * - ``"ankr"``
  22904. * - ``"cloudflare"``
  22905. * - ``"chainstack"``
  22906. * - ``"etherscan"``
  22907. * - ``"infura"``
  22908. * - ``"publicPolygon"``
  22909. * - ``"quicknode"``
  22910. *
  22911. * @example:
  22912. * // Connect to a local Geth node
  22913. * provider = getDefaultProvider("http://localhost:8545/");
  22914. *
  22915. * // Connect to Ethereum mainnet with any current and future
  22916. * // third-party services available
  22917. * provider = getDefaultProvider("mainnet");
  22918. *
  22919. * // Connect to Polygon, but only allow Etherscan and
  22920. * // INFURA and use "MY_API_KEY" in calls to Etherscan.
  22921. * provider = getDefaultProvider("matic", {
  22922. * etherscan: "MY_API_KEY",
  22923. * exclusive: [ "etherscan", "infura" ]
  22924. * });
  22925. */
  22926. function getDefaultProvider(network, options) {
  22927. if (options == null) {
  22928. options = {};
  22929. }
  22930. const allowService = (name) => {
  22931. if (options[name] === "-") {
  22932. return false;
  22933. }
  22934. if (typeof (options.exclusive) === "string") {
  22935. return (name === options.exclusive);
  22936. }
  22937. if (Array.isArray(options.exclusive)) {
  22938. return (options.exclusive.indexOf(name) !== -1);
  22939. }
  22940. return true;
  22941. };
  22942. if (typeof (network) === "string" && network.match(/^https?:/)) {
  22943. return new JsonRpcProvider(network);
  22944. }
  22945. if (typeof (network) === "string" && network.match(/^wss?:/) || isWebSocketLike(network)) {
  22946. return new WebSocketProvider(network);
  22947. }
  22948. // Get the network and name, if possible
  22949. let staticNetwork = null;
  22950. try {
  22951. staticNetwork = Network.from(network);
  22952. }
  22953. catch (error) { }
  22954. const providers = [];
  22955. if (allowService("publicPolygon") && staticNetwork) {
  22956. if (staticNetwork.name === "matic") {
  22957. providers.push(new JsonRpcProvider("https:/\/polygon-rpc.com/", staticNetwork, { staticNetwork }));
  22958. }
  22959. else if (staticNetwork.name === "matic-amoy") {
  22960. providers.push(new JsonRpcProvider("https:/\/rpc-amoy.polygon.technology/", staticNetwork, { staticNetwork }));
  22961. }
  22962. }
  22963. if (allowService("alchemy")) {
  22964. try {
  22965. providers.push(new AlchemyProvider(network, options.alchemy));
  22966. }
  22967. catch (error) { }
  22968. }
  22969. if (allowService("ankr") && options.ankr != null) {
  22970. try {
  22971. providers.push(new AnkrProvider(network, options.ankr));
  22972. }
  22973. catch (error) { }
  22974. }
  22975. if (allowService("chainstack")) {
  22976. try {
  22977. providers.push(new ChainstackProvider(network, options.chainstack));
  22978. }
  22979. catch (error) { }
  22980. }
  22981. if (allowService("cloudflare")) {
  22982. try {
  22983. providers.push(new CloudflareProvider(network));
  22984. }
  22985. catch (error) { }
  22986. }
  22987. if (allowService("etherscan")) {
  22988. try {
  22989. providers.push(new EtherscanProvider(network, options.etherscan));
  22990. }
  22991. catch (error) { }
  22992. }
  22993. if (allowService("infura")) {
  22994. try {
  22995. let projectId = options.infura;
  22996. let projectSecret = undefined;
  22997. if (typeof (projectId) === "object") {
  22998. projectSecret = projectId.projectSecret;
  22999. projectId = projectId.projectId;
  23000. }
  23001. providers.push(new InfuraProvider(network, projectId, projectSecret));
  23002. }
  23003. catch (error) { }
  23004. }
  23005. /*
  23006. if (options.pocket !== "-") {
  23007. try {
  23008. let appId = options.pocket;
  23009. let secretKey: undefined | string = undefined;
  23010. let loadBalancer: undefined | boolean = undefined;
  23011. if (typeof(appId) === "object") {
  23012. loadBalancer = !!appId.loadBalancer;
  23013. secretKey = appId.secretKey;
  23014. appId = appId.appId;
  23015. }
  23016. providers.push(new PocketProvider(network, appId, secretKey, loadBalancer));
  23017. } catch (error) { console.log(error); }
  23018. }
  23019. */
  23020. if (allowService("quicknode")) {
  23021. try {
  23022. let token = options.quicknode;
  23023. providers.push(new QuickNodeProvider(network, token));
  23024. }
  23025. catch (error) { }
  23026. }
  23027. assert(providers.length, "unsupported default network", "UNSUPPORTED_OPERATION", {
  23028. operation: "getDefaultProvider"
  23029. });
  23030. // No need for a FallbackProvider
  23031. if (providers.length === 1) {
  23032. return providers[0];
  23033. }
  23034. // We use the floor because public third-party providers can be unreliable,
  23035. // so a low number of providers with a large quorum will fail too often
  23036. let quorum = Math.floor(providers.length / 2);
  23037. if (quorum > 2) {
  23038. quorum = 2;
  23039. }
  23040. // Testnets don't need as strong a security gaurantee and speed is
  23041. // more useful during testing
  23042. if (staticNetwork && Testnets.indexOf(staticNetwork.name) !== -1) {
  23043. quorum = 1;
  23044. }
  23045. // Provided override qorum takes priority
  23046. if (options && options.quorum) {
  23047. quorum = options.quorum;
  23048. }
  23049. return new FallbackProvider(providers, undefined, { quorum });
  23050. }
  23051. /**
  23052. * A **NonceManager** wraps another [[Signer]] and automatically manages
  23053. * the nonce, ensuring serialized and sequential nonces are used during
  23054. * transaction.
  23055. */
  23056. class NonceManager extends AbstractSigner {
  23057. /**
  23058. * The Signer being managed.
  23059. */
  23060. signer;
  23061. #noncePromise;
  23062. #delta;
  23063. /**
  23064. * Creates a new **NonceManager** to manage %%signer%%.
  23065. */
  23066. constructor(signer) {
  23067. super(signer.provider);
  23068. defineProperties(this, { signer });
  23069. this.#noncePromise = null;
  23070. this.#delta = 0;
  23071. }
  23072. async getAddress() {
  23073. return this.signer.getAddress();
  23074. }
  23075. connect(provider) {
  23076. return new NonceManager(this.signer.connect(provider));
  23077. }
  23078. async getNonce(blockTag) {
  23079. if (blockTag === "pending") {
  23080. if (this.#noncePromise == null) {
  23081. this.#noncePromise = super.getNonce("pending");
  23082. }
  23083. const delta = this.#delta;
  23084. return (await this.#noncePromise) + delta;
  23085. }
  23086. return super.getNonce(blockTag);
  23087. }
  23088. /**
  23089. * Manually increment the nonce. This may be useful when managng
  23090. * offline transactions.
  23091. */
  23092. increment() {
  23093. this.#delta++;
  23094. }
  23095. /**
  23096. * Resets the nonce, causing the **NonceManager** to reload the current
  23097. * nonce from the blockchain on the next transaction.
  23098. */
  23099. reset() {
  23100. this.#delta = 0;
  23101. this.#noncePromise = null;
  23102. }
  23103. async sendTransaction(tx) {
  23104. const noncePromise = this.getNonce("pending");
  23105. this.increment();
  23106. tx = await this.signer.populateTransaction(tx);
  23107. tx.nonce = await noncePromise;
  23108. // @TODO: Maybe handle interesting/recoverable errors?
  23109. // Like don't increment if the tx was certainly not sent
  23110. return await this.signer.sendTransaction(tx);
  23111. }
  23112. signTransaction(tx) {
  23113. return this.signer.signTransaction(tx);
  23114. }
  23115. signMessage(message) {
  23116. return this.signer.signMessage(message);
  23117. }
  23118. signTypedData(domain, types, value) {
  23119. return this.signer.signTypedData(domain, types, value);
  23120. }
  23121. }
  23122. /**
  23123. * A **BrowserProvider** is intended to wrap an injected provider which
  23124. * adheres to the [[link-eip-1193]] standard, which most (if not all)
  23125. * currently do.
  23126. */
  23127. class BrowserProvider extends JsonRpcApiPollingProvider {
  23128. #request;
  23129. /**
  23130. * Connect to the %%ethereum%% provider, optionally forcing the
  23131. * %%network%%.
  23132. */
  23133. constructor(ethereum, network, _options) {
  23134. // Copy the options
  23135. const options = Object.assign({}, ((_options != null) ? _options : {}), { batchMaxCount: 1 });
  23136. assertArgument(ethereum && ethereum.request, "invalid EIP-1193 provider", "ethereum", ethereum);
  23137. super(network, options);
  23138. this.#request = async (method, params) => {
  23139. const payload = { method, params };
  23140. this.emit("debug", { action: "sendEip1193Request", payload });
  23141. try {
  23142. const result = await ethereum.request(payload);
  23143. this.emit("debug", { action: "receiveEip1193Result", result });
  23144. return result;
  23145. }
  23146. catch (e) {
  23147. const error = new Error(e.message);
  23148. error.code = e.code;
  23149. error.data = e.data;
  23150. error.payload = payload;
  23151. this.emit("debug", { action: "receiveEip1193Error", error });
  23152. throw error;
  23153. }
  23154. };
  23155. }
  23156. async send(method, params) {
  23157. await this._start();
  23158. return await super.send(method, params);
  23159. }
  23160. async _send(payload) {
  23161. assertArgument(!Array.isArray(payload), "EIP-1193 does not support batch request", "payload", payload);
  23162. try {
  23163. const result = await this.#request(payload.method, payload.params || []);
  23164. return [{ id: payload.id, result }];
  23165. }
  23166. catch (e) {
  23167. return [{
  23168. id: payload.id,
  23169. error: { code: e.code, data: e.data, message: e.message }
  23170. }];
  23171. }
  23172. }
  23173. getRpcError(payload, error) {
  23174. error = JSON.parse(JSON.stringify(error));
  23175. // EIP-1193 gives us some machine-readable error codes, so rewrite
  23176. // them into
  23177. switch (error.error.code || -1) {
  23178. case 4001:
  23179. error.error.message = `ethers-user-denied: ${error.error.message}`;
  23180. break;
  23181. case 4200:
  23182. error.error.message = `ethers-unsupported: ${error.error.message}`;
  23183. break;
  23184. }
  23185. return super.getRpcError(payload, error);
  23186. }
  23187. /**
  23188. * Resolves to ``true`` if the provider manages the %%address%%.
  23189. */
  23190. async hasSigner(address) {
  23191. if (address == null) {
  23192. address = 0;
  23193. }
  23194. const accounts = await this.send("eth_accounts", []);
  23195. if (typeof (address) === "number") {
  23196. return (accounts.length > address);
  23197. }
  23198. address = address.toLowerCase();
  23199. return accounts.filter((a) => (a.toLowerCase() === address)).length !== 0;
  23200. }
  23201. async getSigner(address) {
  23202. if (address == null) {
  23203. address = 0;
  23204. }
  23205. if (!(await this.hasSigner(address))) {
  23206. try {
  23207. //const resp =
  23208. await this.#request("eth_requestAccounts", []);
  23209. //console.log("RESP", resp);
  23210. }
  23211. catch (error) {
  23212. const payload = error.payload;
  23213. throw this.getRpcError(payload, { id: payload.id, error });
  23214. }
  23215. }
  23216. return await super.getSigner(address);
  23217. }
  23218. }
  23219. /**
  23220. * [[link-pocket]] provides a third-party service for connecting to
  23221. * various blockchains over JSON-RPC.
  23222. *
  23223. * **Supported Networks**
  23224. *
  23225. * - Ethereum Mainnet (``mainnet``)
  23226. * - Goerli Testnet (``goerli``)
  23227. * - Polygon (``matic``)
  23228. * - Arbitrum (``arbitrum``)
  23229. *
  23230. * @_subsection: api/providers/thirdparty:Pocket [providers-pocket]
  23231. */
  23232. const defaultApplicationId = "62e1ad51b37b8e00394bda3b";
  23233. function getHost(name) {
  23234. switch (name) {
  23235. case "mainnet":
  23236. return "eth-mainnet.gateway.pokt.network";
  23237. case "goerli":
  23238. return "eth-goerli.gateway.pokt.network";
  23239. case "matic":
  23240. return "poly-mainnet.gateway.pokt.network";
  23241. case "matic-mumbai":
  23242. return "polygon-mumbai-rpc.gateway.pokt.network";
  23243. }
  23244. assertArgument(false, "unsupported network", "network", name);
  23245. }
  23246. /**
  23247. * The **PocketProvider** connects to the [[link-pocket]]
  23248. * JSON-RPC end-points.
  23249. *
  23250. * By default, a highly-throttled API key is used, which is
  23251. * appropriate for quick prototypes and simple scripts. To
  23252. * gain access to an increased rate-limit, it is highly
  23253. * recommended to [sign up here](link-pocket-signup).
  23254. */
  23255. class PocketProvider extends JsonRpcProvider {
  23256. /**
  23257. * The Application ID for the Pocket connection.
  23258. */
  23259. applicationId;
  23260. /**
  23261. * The Application Secret for making authenticated requests
  23262. * to the Pocket connection.
  23263. */
  23264. applicationSecret;
  23265. /**
  23266. * Create a new **PocketProvider**.
  23267. *
  23268. * By default connecting to ``mainnet`` with a highly throttled
  23269. * API key.
  23270. */
  23271. constructor(_network, applicationId, applicationSecret) {
  23272. if (_network == null) {
  23273. _network = "mainnet";
  23274. }
  23275. const network = Network.from(_network);
  23276. if (applicationId == null) {
  23277. applicationId = defaultApplicationId;
  23278. }
  23279. if (applicationSecret == null) {
  23280. applicationSecret = null;
  23281. }
  23282. const options = { staticNetwork: network };
  23283. const request = PocketProvider.getRequest(network, applicationId, applicationSecret);
  23284. super(request, network, options);
  23285. defineProperties(this, { applicationId, applicationSecret });
  23286. }
  23287. _getProvider(chainId) {
  23288. try {
  23289. return new PocketProvider(chainId, this.applicationId, this.applicationSecret);
  23290. }
  23291. catch (error) { }
  23292. return super._getProvider(chainId);
  23293. }
  23294. /**
  23295. * Returns a prepared request for connecting to %%network%% with
  23296. * %%applicationId%%.
  23297. */
  23298. static getRequest(network, applicationId, applicationSecret) {
  23299. if (applicationId == null) {
  23300. applicationId = defaultApplicationId;
  23301. }
  23302. const request = new FetchRequest(`https:/\/${getHost(network.name)}/v1/lb/${applicationId}`);
  23303. request.allowGzip = true;
  23304. if (applicationSecret) {
  23305. request.setCredentials("", applicationSecret);
  23306. }
  23307. if (applicationId === defaultApplicationId) {
  23308. request.retryFunc = async (request, response, attempt) => {
  23309. showThrottleMessage("PocketProvider");
  23310. return true;
  23311. };
  23312. }
  23313. return request;
  23314. }
  23315. isCommunityResource() {
  23316. return (this.applicationId === defaultApplicationId);
  23317. }
  23318. }
  23319. const IpcSocketProvider = undefined;
  23320. /**
  23321. * The **BaseWallet** is a stream-lined implementation of a
  23322. * [[Signer]] that operates with a private key.
  23323. *
  23324. * It is preferred to use the [[Wallet]] class, as it offers
  23325. * additional functionality and simplifies loading a variety
  23326. * of JSON formats, Mnemonic Phrases, etc.
  23327. *
  23328. * This class may be of use for those attempting to implement
  23329. * a minimal Signer.
  23330. */
  23331. class BaseWallet extends AbstractSigner {
  23332. /**
  23333. * The wallet address.
  23334. */
  23335. address;
  23336. #signingKey;
  23337. /**
  23338. * Creates a new BaseWallet for %%privateKey%%, optionally
  23339. * connected to %%provider%%.
  23340. *
  23341. * If %%provider%% is not specified, only offline methods can
  23342. * be used.
  23343. */
  23344. constructor(privateKey, provider) {
  23345. super(provider);
  23346. assertArgument(privateKey && typeof (privateKey.sign) === "function", "invalid private key", "privateKey", "[ REDACTED ]");
  23347. this.#signingKey = privateKey;
  23348. const address = computeAddress(this.signingKey.publicKey);
  23349. defineProperties(this, { address });
  23350. }
  23351. // Store private values behind getters to reduce visibility
  23352. // in console.log
  23353. /**
  23354. * The [[SigningKey]] used for signing payloads.
  23355. */
  23356. get signingKey() { return this.#signingKey; }
  23357. /**
  23358. * The private key for this wallet.
  23359. */
  23360. get privateKey() { return this.signingKey.privateKey; }
  23361. async getAddress() { return this.address; }
  23362. connect(provider) {
  23363. return new BaseWallet(this.#signingKey, provider);
  23364. }
  23365. async signTransaction(tx) {
  23366. tx = copyRequest(tx);
  23367. // Replace any Addressable or ENS name with an address
  23368. const { to, from } = await resolveProperties({
  23369. to: (tx.to ? resolveAddress(tx.to, this.provider) : undefined),
  23370. from: (tx.from ? resolveAddress(tx.from, this.provider) : undefined)
  23371. });
  23372. if (to != null) {
  23373. tx.to = to;
  23374. }
  23375. if (from != null) {
  23376. tx.from = from;
  23377. }
  23378. if (tx.from != null) {
  23379. assertArgument(getAddress((tx.from)) === this.address, "transaction from address mismatch", "tx.from", tx.from);
  23380. delete tx.from;
  23381. }
  23382. // Build the transaction
  23383. const btx = Transaction.from(tx);
  23384. btx.signature = this.signingKey.sign(btx.unsignedHash);
  23385. return btx.serialized;
  23386. }
  23387. async signMessage(message) {
  23388. return this.signMessageSync(message);
  23389. }
  23390. // @TODO: Add a secialized signTx and signTyped sync that enforces
  23391. // all parameters are known?
  23392. /**
  23393. * Returns the signature for %%message%% signed with this wallet.
  23394. */
  23395. signMessageSync(message) {
  23396. return this.signingKey.sign(hashMessage(message)).serialized;
  23397. }
  23398. async signTypedData(domain, types, value) {
  23399. // Populate any ENS names
  23400. const populated = await TypedDataEncoder.resolveNames(domain, types, value, async (name) => {
  23401. // @TODO: this should use resolveName; addresses don't
  23402. // need a provider
  23403. assert(this.provider != null, "cannot resolve ENS names without a provider", "UNSUPPORTED_OPERATION", {
  23404. operation: "resolveName",
  23405. info: { name }
  23406. });
  23407. const address = await this.provider.resolveName(name);
  23408. assert(address != null, "unconfigured ENS name", "UNCONFIGURED_NAME", {
  23409. value: name
  23410. });
  23411. return address;
  23412. });
  23413. return this.signingKey.sign(TypedDataEncoder.hash(populated.domain, types, populated.value)).serialized;
  23414. }
  23415. }
  23416. const subsChrs = " !#$%&'()*+,-./<=>?@[]^_`{|}~";
  23417. const Word = /^[a-z]*$/i;
  23418. function unfold(words, sep) {
  23419. let initial = 97;
  23420. return words.reduce((accum, word) => {
  23421. if (word === sep) {
  23422. initial++;
  23423. }
  23424. else if (word.match(Word)) {
  23425. accum.push(String.fromCharCode(initial) + word);
  23426. }
  23427. else {
  23428. initial = 97;
  23429. accum.push(word);
  23430. }
  23431. return accum;
  23432. }, []);
  23433. }
  23434. /**
  23435. * @_ignore
  23436. */
  23437. function decode(data, subs) {
  23438. // Replace all the substitutions with their expanded form
  23439. for (let i = subsChrs.length - 1; i >= 0; i--) {
  23440. data = data.split(subsChrs[i]).join(subs.substring(2 * i, 2 * i + 2));
  23441. }
  23442. // Get all tle clumps; each suffix, first-increment and second-increment
  23443. const clumps = [];
  23444. const leftover = data.replace(/(:|([0-9])|([A-Z][a-z]*))/g, (all, item, semi, word) => {
  23445. if (semi) {
  23446. for (let i = parseInt(semi); i >= 0; i--) {
  23447. clumps.push(";");
  23448. }
  23449. }
  23450. else {
  23451. clumps.push(item.toLowerCase());
  23452. }
  23453. return "";
  23454. });
  23455. /* c8 ignore start */
  23456. if (leftover) {
  23457. throw new Error(`leftovers: ${JSON.stringify(leftover)}`);
  23458. }
  23459. /* c8 ignore stop */
  23460. return unfold(unfold(clumps, ";"), ":");
  23461. }
  23462. /**
  23463. * @_ignore
  23464. */
  23465. function decodeOwl(data) {
  23466. assertArgument(data[0] === "0", "unsupported auwl data", "data", data);
  23467. return decode(data.substring(1 + 2 * subsChrs.length), data.substring(1, 1 + 2 * subsChrs.length));
  23468. }
  23469. /**
  23470. * A Wordlist represents a collection of language-specific
  23471. * words used to encode and devoce [[link-bip-39]] encoded data
  23472. * by mapping words to 11-bit values and vice versa.
  23473. */
  23474. class Wordlist {
  23475. locale;
  23476. /**
  23477. * Creates a new Wordlist instance.
  23478. *
  23479. * Sub-classes MUST call this if they provide their own constructor,
  23480. * passing in the locale string of the language.
  23481. *
  23482. * Generally there is no need to create instances of a Wordlist,
  23483. * since each language-specific Wordlist creates an instance and
  23484. * there is no state kept internally, so they are safe to share.
  23485. */
  23486. constructor(locale) {
  23487. defineProperties(this, { locale });
  23488. }
  23489. /**
  23490. * Sub-classes may override this to provide a language-specific
  23491. * method for spliting %%phrase%% into individual words.
  23492. *
  23493. * By default, %%phrase%% is split using any sequences of
  23494. * white-space as defined by regular expressions (i.e. ``/\s+/``).
  23495. */
  23496. split(phrase) {
  23497. return phrase.toLowerCase().split(/\s+/g);
  23498. }
  23499. /**
  23500. * Sub-classes may override this to provider a language-specific
  23501. * method for joining %%words%% into a phrase.
  23502. *
  23503. * By default, %%words%% are joined by a single space.
  23504. */
  23505. join(words) {
  23506. return words.join(" ");
  23507. }
  23508. }
  23509. // Use the encode-latin.js script to create the necessary
  23510. // data files to be consumed by this class
  23511. /**
  23512. * An OWL format Wordlist is an encoding method that exploits
  23513. * the general locality of alphabetically sorted words to
  23514. * achieve a simple but effective means of compression.
  23515. *
  23516. * This class is generally not useful to most developers as
  23517. * it is used mainly internally to keep Wordlists for languages
  23518. * based on ASCII-7 small.
  23519. *
  23520. * If necessary, there are tools within the ``generation/`` folder
  23521. * to create the necessary data.
  23522. */
  23523. class WordlistOwl extends Wordlist {
  23524. #data;
  23525. #checksum;
  23526. /**
  23527. * Creates a new Wordlist for %%locale%% using the OWL %%data%%
  23528. * and validated against the %%checksum%%.
  23529. */
  23530. constructor(locale, data, checksum) {
  23531. super(locale);
  23532. this.#data = data;
  23533. this.#checksum = checksum;
  23534. this.#words = null;
  23535. }
  23536. /**
  23537. * The OWL-encoded data.
  23538. */
  23539. get _data() { return this.#data; }
  23540. /**
  23541. * Decode all the words for the wordlist.
  23542. */
  23543. _decodeWords() {
  23544. return decodeOwl(this.#data);
  23545. }
  23546. #words;
  23547. #loadWords() {
  23548. if (this.#words == null) {
  23549. const words = this._decodeWords();
  23550. // Verify the computed list matches the official list
  23551. const checksum = id(words.join("\n") + "\n");
  23552. /* c8 ignore start */
  23553. if (checksum !== this.#checksum) {
  23554. throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`);
  23555. }
  23556. /* c8 ignore stop */
  23557. this.#words = words;
  23558. }
  23559. return this.#words;
  23560. }
  23561. getWord(index) {
  23562. const words = this.#loadWords();
  23563. assertArgument(index >= 0 && index < words.length, `invalid word index: ${index}`, "index", index);
  23564. return words[index];
  23565. }
  23566. getWordIndex(word) {
  23567. return this.#loadWords().indexOf(word);
  23568. }
  23569. }
  23570. const words = "0erleonalorenseinceregesticitStanvetearctssi#ch2Athck&tneLl0And#Il.yLeOutO=S|S%b/ra@SurdU'0Ce[Cid|CountCu'Hie=IdOu,-Qui*Ro[TT]T%T*[Tu$0AptDD-tD*[Ju,M.UltV<)Vi)0Rob-0FairF%dRaid0A(EEntRee0Ead0MRRp%tS!_rmBumCoholErtI&LLeyLowMo,O}PhaReadySoT Ways0A>urAz(gOngOuntU'd0Aly,Ch%Ci|G G!GryIm$K!Noun)Nu$O` Sw T&naTiqueXietyY1ArtOlogyPe?P!Pro=Ril1ChCt-EaEnaGueMMedM%MyOundR<+Re,Ri=RowTTefa@Ti,Tw%k0KPe@SaultSetSi,SumeThma0H!>OmTa{T&dT.udeTra@0Ct]D.Gu,NtTh%ToTumn0Era+OcadoOid0AkeA*AyEsomeFulKw?d0Is:ByChel%C#D+GL<)Lc#y~MbooN<aNn RRelyRga(R*lSeS-SketTt!3A^AnAutyCau'ComeEfF%eG(Ha=H(dLie=LowLtN^Nef./TrayTt Twe&Y#d3Cyc!DKeNdOlogyRdR`Tt _{AdeAmeAnketA,EakE[IndOodO[omOu'UeUrUsh_rdAtDyIlMbNeNusOkO,Rd R(gRrowSsTtomUn)XY_{etA(AndA[A=EadEezeI{Id+IefIghtIngIskOccoliOk&OnzeOomO` OwnUsh2Bb!DdyD+tFf$oIldLbLkL!tNd!Nk Rd&Rg R,SS(e[SyTt Y Zz:Bba+B(B!CtusGeKe~LmM aMpNN$N)lNdyNn#NoeNvasNy#Pab!P.$Pta(RRb#RdRgoRpetRryRtSeShS(o/!Su$TT$ogT^Teg%yTt!UghtU'Ut]Ve3Il(gL yM|NsusNturyRe$Rta(_irAlkAmp]An+AosApt Ar+A'AtEapE{Ee'EfErryE,I{&IefIldIm}yOi)Oo'R#-U{!UnkUrn0G?Nnam#Rc!Tiz&TyVil_imApArifyAwAyE<ErkEv I{I|IffImbIn-IpO{OgO'O`OudOwnUbUmpU, Ut^_^A,C#utDeFfeeIlInL!@L%LumnMb(eMeMf%tM-Mm#Mp<yNc tNdu@NfirmNg*[N}@Nsid NtrolNv()OkOlPp PyR$ReRnR*@/Tt#U^UntryUp!Ur'Us(V Yo>_{Ad!AftAmA}AshAt AwlAzyEamEd.EekEwI{etImeIspIt-OpO[Ou^OwdUci$UelUi'Umb!Un^UshYY,$2BeLtu*PPbo?dRiousRr|Rta(R=Sh]/omTe3C!:DMa+MpN)Ng R(gShUght WnY3AlBa>BrisCadeCemb CideCl(eC%a>C*a'ErF&'F(eFyG*eLayLiv M<dMi'Ni$Nti,NyP?tP&dPos.P`PutyRi=ScribeS tSignSkSpair/royTailTe@VelopVi)Vo>3AgramAlAm#dAryCeE'lEtFf G.$Gn.yLemmaNn NosaurRe@RtSag*eScov Sea'ShSmi[S%d Splay/<)V tVideV%)Zzy5Ct%Cum|G~Lph(Ma(Na>NkeyN%OrSeUb!Ve_ftAg#AmaA,-AwEamE[IftIllInkIpI=OpUmY2CkMbNeR(g/T^Ty1Arf1Nam-:G G!RlyRnR`Sily/Sy1HoOlogyOnomy0GeItUca>1F%t0G1GhtTh 2BowD E@r-Eg<tEm|Eph<tEvat%I>Se0B?kBodyBra)Er+Ot]PloyPow Pty0Ab!A@DD![D%'EmyErgyF%)Ga+G(eH<)JoyLi,OughR-hRollSu*T Ti*TryVelope1Isode0U$Uip0AA'OdeOs]R%Upt0CapeSayS&)Ta>0Ern$H-s1Id&)IlOkeOl=1A@Amp!Ce[Ch<+C.eCludeCu'Ecu>Erci'Hau,Hib.I!I,ItOt-P<dPe@Pi*Pla(Po'P*[T&dTra0EEbrow:Br-CeCultyDeIntI`~L'MeMilyMousNNcyNtasyRmSh]TT$Th TigueUltV%.e3Atu*Bru?yD $EEdElMa!N)/iv$T^V W3B Ct]EldGu*LeLmLt N$NdNeNg NishReRmR,Sc$ShTT}[X_gAmeAshAtAv%EeIghtIpOatO{O%Ow UidUshY_mCusGIlLd~owOdOtR)Re,R+tRkRtu}RumRw?dSsil/ UndX_gi!AmeEqu|EshI&dIn+OgOntO,OwnOz&U.2ElNNnyRna)RyTu*:D+tInLaxy~ yMePRa+Rba+Rd&Rl-Rm|SSpTeTh U+Ze3N $NiusN*Nt!Nu(e/u*2O,0AntFtGg!Ng RaffeRlVe_dAn)A*A[IdeImp'ObeOomOryO=OwUe_tDde[LdOdO'RillaSpelSsipV nWn_bA)A(AntApeA[Av.yEatE&IdIefItOc yOupOwUnt_rdE[IdeIltIt?N3M:B.IrLfMm M, NdPpyRb%RdRshR=,TVeWkZ?d3AdAl`ArtAvyD+hogIght~oLmetLpNRo3Dd&Gh~NtPRe/%y5BbyCkeyLdLeLiday~owMeNeyOdPeRnRr%R'Sp.$/TelUrV 5BGeM<Mb!M%Nd*dNgryNtRd!RryRtSb<d3Brid:1EOn0EaEntifyLe2N%e4LLeg$L}[0A+Ita>M&'Mu}Pa@Po'Pro=Pul'0ChCludeComeC*a'DexD-a>Do%Du,ryF<tFl-tF%mHa!H .Iti$Je@JuryMa>N Noc|PutQuiryS<eSe@SideSpi*/$lTa@T e,ToVe,V.eVol=3On0L<dOla>Sue0Em1Ory:CketGu?RZz3AlousAns~yWel9BInKeUr}yY5D+I)MpNg!Ni%Nk/:Ng?oo3EnEpT^upY3CkDD}yNdNgdomSsTT^&TeTt&Wi4EeIfeO{Ow:BBelB%Dd DyKeMpNgua+PtopR+T T(UghUndryVaWWnWsu.Y Zy3Ad AfArnA=Ctu*FtGG$G&dIsu*M#NdNg`NsOp?dSs#Tt Vel3ArB tyBr?yC&'FeFtGhtKeMbM.NkOnQuid/Tt!VeZ?d5AdAnB, C$CkG-NelyNgOpTt yUdUn+VeY$5CkyGga+Mb N?N^Xury3R-s:Ch(eDG-G}tIdIlInJ%KeMm$NNa+Nda>NgoNs]Nu$P!Rb!R^Rg(R(eRketRria+SkSs/ T^T i$ThTrixTt XimumZe3AdowAnAsu*AtCh<-D$DiaLodyLtMb M%yNt]NuRcyR+R.RryShSsa+T$Thod3Dd!DnightLk~]M-NdNimumN%Nu>Rac!Rr%S ySs/akeXXedXtu*5Bi!DelDifyMM|N.%NkeyN, N`OnR$ReRn(gSqu.oTh T]T%Unta(U'VeVie5ChFf(LeLtiplySc!SeumShroomS-/Tu$3Self/ yTh:I=MePk(Rrow/yT]Tu*3ArCkEdGati=G!@I` PhewR=/TTw%kUtr$V WsXt3CeGht5B!I'M(eeOd!Rm$R`SeTab!TeTh(gTi)VelW5C!?Mb R'T:K0EyJe@Li+Scu*S =Ta(Vious0CurE<Tob 0Or1FF Fi)T&2L1Ay0DI=Ymp-0It0CeEI#L(eLy1EnEraIn]Po'T]1An+B.Ch?dD D(?yG<I|Ig($Ph<0Tr-h0H 0Tdo%T TputTside0AlEnEr0NN 0Yg&0/ 0O}:CtDd!GeIrLa)LmNdaNelN-N` P RadeR|RkRrotRtySsT^ThTi|TrolTt nU'VeYm|3A)AnutArAs<tL-<NN$tyNcilOp!Pp Rfe@Rm.Rs#T2O}OtoRa'Ys-$0AnoCn-Ctu*E)GGe#~LotNkO} Pe/olT^Zza_)A}tA,-A>AyEa'Ed+U{UgUn+2EmEtIntL?LeLi)NdNyOlPul?Rt]S.]Ssib!/TatoTt yV tyWd W _@i)Ai'Ed-tEf Epa*Es|EttyEv|I)IdeIm?yIntI%.yIs#Iva>IzeOb!mO)[Odu)Of.OgramOje@Omo>OofOp tyOsp O>@OudOvide2Bl-Dd(g~LpL'Mpk(N^PilPpyR^a'R.yRpo'R'ShTZz!3Ramid:99Al.yAntumArt E,]I{ItIzO>:Bb.Cco#CeCkD?DioIlInI'~yMpN^NdomN+PidReTeTh V&WZ%3AdyAlAs#BelBuildC$lCei=CipeC%dCyc!Du)F!@F%mFu'G]G*tGul?Je@LaxLea'LiefLyMa(Memb M(dMo=Nd NewNtOp&PairPeatPla)P%tQui*ScueSemb!Si,Sour)Sp#'SultTi*T*atTurnUn]Ve$ViewW?d2Y`m0BBb#CeChDeD+F!GhtGidNgOtPp!SkTu$V$V 5AdA,BotBu,CketM<)OfOkieOmSeTa>UghUndU>Y$5Bb DeGLeNNwayR$:DDd!D}[FeIlLadLm#L#LtLu>MeMp!NdTisfyToshiU)Usa+VeY1A!AnA*Att E}HemeHoolI&)I[%sOrp]OutRapRe&RiptRub1AAr^As#AtC#dC*tCt]Cur.yEdEkGm|Le@~M(?Ni%N'Nt&)RiesRvi)Ss]Tt!TupV&_dowAftAllowA*EdEllEriffIeldIftI}IpIv O{OeOotOpOrtOuld O=RimpRugUff!Y0Bl(gCkDeE+GhtGnL|Lk~yLv Mil?Mp!N)NgR&/ Tua>XZe1A>Et^IIllInIrtUll0AbAmEepEnd I)IdeIghtImOg<OtOwUsh0AllArtI!OkeOo`0A{AkeApIffOw0ApCc Ci$CkDaFtL?Ldi LidLut]L=Me#eNgOnRryRtUlUndUpUr)U`0A)A*Ati$AwnEakEci$EedEllEndH eI)Id IkeInIr.L.OilOns%O#OrtOtRayReadR(gY0Ua*UeezeUir*l_b!AdiumAffA+AirsAmpAndArtA>AyEakEelEmEpE*oI{IllIngO{Oma^O}OolOryO=Ra>gyReetRikeR#gRugg!Ud|UffUmb!Y!0Bje@Bm.BwayC)[ChDd&Ff G?G+,ItMm NNnyN'tP PplyP*meReRfa)R+Rpri'RroundR=ySpe@/a(1AllowAmpApArmE?EetIftImIngIt^Ord1MbolMptomRup/em:B!Ck!GIlL|LkNkPeR+tSk/eTtooXi3A^Am~NN<tNnisNtRm/Xt_nkAtEmeEnE%yE*EyIngIsOughtReeRi=RowUmbUnd 0CketDeG LtMb MeNyPRedSsueT!5A,BaccoDayDdl EGe` I!tK&MatoM%rowNeNgueNightOlO`PP-Pp!R^RnadoRtoi'SsT$Uri,W?dW WnY_{AdeAff-Ag-A(Ansf ApAshA=lAyEatEeEndI$IbeI{Igg ImIpOphyOub!U{UeUlyUmpetU,U`Y2BeIt]Mb!NaN}lRkeyRnRt!1El=EntyI)InI,O1PeP-$:5Ly5B*lla0Ab!Awa*C!Cov D DoFairFoldHappyIf%mIqueItIv 'KnownLo{TilUsu$Veil1Da>GradeHoldOnP Set1B<Ge0A+EEdEfulE![U$0Il.y:C<tCuumGueLidL!yL=NNishP%Rious/Ult3H-!L=tNd%Ntu*NueRbRifyRs]RyS'lT <3Ab!Br<tCiousCt%yDeoEw~a+Nta+Ol(Rtu$RusSaS.Su$T$Vid5C$I)IdLc<oLumeTeYa+:GeG#ItLk~LnutNtRfa*RmRri%ShSp/eT VeY3Al`Ap#ArA'lA` BDd(gEk&dIrdLcome/T_!AtEatEelEnE*IpIsp 0DeD`FeLd~NNdowNeNgNkNn Nt ReSdomSeShT}[5LfM<Nd OdOlRdRkRldRryR`_pE{E,!I,I>Ong::Rd3Ar~ow9UUngU`:3BraRo9NeO";
  23571. const checksum = "0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60";
  23572. let wordlist = null;
  23573. /**
  23574. * The [[link-bip39-en]] for [mnemonic phrases](link-bip-39).
  23575. *
  23576. * @_docloc: api/wordlists
  23577. */
  23578. class LangEn extends WordlistOwl {
  23579. /**
  23580. * Creates a new instance of the English language Wordlist.
  23581. *
  23582. * This should be unnecessary most of the time as the exported
  23583. * [[langEn]] should suffice.
  23584. *
  23585. * @_ignore:
  23586. */
  23587. constructor() { super("en", words, checksum); }
  23588. /**
  23589. * Returns a singleton instance of a ``LangEn``, creating it
  23590. * if this is the first time being called.
  23591. */
  23592. static wordlist() {
  23593. if (wordlist == null) {
  23594. wordlist = new LangEn();
  23595. }
  23596. return wordlist;
  23597. }
  23598. }
  23599. // Returns a byte with the MSB bits set
  23600. function getUpperMask(bits) {
  23601. return ((1 << bits) - 1) << (8 - bits) & 0xff;
  23602. }
  23603. // Returns a byte with the LSB bits set
  23604. function getLowerMask(bits) {
  23605. return ((1 << bits) - 1) & 0xff;
  23606. }
  23607. function mnemonicToEntropy(mnemonic, wordlist) {
  23608. assertNormalize("NFKD");
  23609. if (wordlist == null) {
  23610. wordlist = LangEn.wordlist();
  23611. }
  23612. const words = wordlist.split(mnemonic);
  23613. assertArgument((words.length % 3) === 0 && words.length >= 12 && words.length <= 24, "invalid mnemonic length", "mnemonic", "[ REDACTED ]");
  23614. const entropy = new Uint8Array(Math.ceil(11 * words.length / 8));
  23615. let offset = 0;
  23616. for (let i = 0; i < words.length; i++) {
  23617. let index = wordlist.getWordIndex(words[i].normalize("NFKD"));
  23618. assertArgument(index >= 0, `invalid mnemonic word at index ${i}`, "mnemonic", "[ REDACTED ]");
  23619. for (let bit = 0; bit < 11; bit++) {
  23620. if (index & (1 << (10 - bit))) {
  23621. entropy[offset >> 3] |= (1 << (7 - (offset % 8)));
  23622. }
  23623. offset++;
  23624. }
  23625. }
  23626. const entropyBits = 32 * words.length / 3;
  23627. const checksumBits = words.length / 3;
  23628. const checksumMask = getUpperMask(checksumBits);
  23629. const checksum = getBytes(sha256(entropy.slice(0, entropyBits / 8)))[0] & checksumMask;
  23630. assertArgument(checksum === (entropy[entropy.length - 1] & checksumMask), "invalid mnemonic checksum", "mnemonic", "[ REDACTED ]");
  23631. return hexlify(entropy.slice(0, entropyBits / 8));
  23632. }
  23633. function entropyToMnemonic(entropy, wordlist) {
  23634. assertArgument((entropy.length % 4) === 0 && entropy.length >= 16 && entropy.length <= 32, "invalid entropy size", "entropy", "[ REDACTED ]");
  23635. if (wordlist == null) {
  23636. wordlist = LangEn.wordlist();
  23637. }
  23638. const indices = [0];
  23639. let remainingBits = 11;
  23640. for (let i = 0; i < entropy.length; i++) {
  23641. // Consume the whole byte (with still more to go)
  23642. if (remainingBits > 8) {
  23643. indices[indices.length - 1] <<= 8;
  23644. indices[indices.length - 1] |= entropy[i];
  23645. remainingBits -= 8;
  23646. // This byte will complete an 11-bit index
  23647. }
  23648. else {
  23649. indices[indices.length - 1] <<= remainingBits;
  23650. indices[indices.length - 1] |= entropy[i] >> (8 - remainingBits);
  23651. // Start the next word
  23652. indices.push(entropy[i] & getLowerMask(8 - remainingBits));
  23653. remainingBits += 3;
  23654. }
  23655. }
  23656. // Compute the checksum bits
  23657. const checksumBits = entropy.length / 4;
  23658. const checksum = parseInt(sha256(entropy).substring(2, 4), 16) & getUpperMask(checksumBits);
  23659. // Shift the checksum into the word indices
  23660. indices[indices.length - 1] <<= checksumBits;
  23661. indices[indices.length - 1] |= (checksum >> (8 - checksumBits));
  23662. return wordlist.join(indices.map((index) => wordlist.getWord(index)));
  23663. }
  23664. const _guard$1 = {};
  23665. /**
  23666. * A **Mnemonic** wraps all properties required to compute [[link-bip-39]]
  23667. * seeds and convert between phrases and entropy.
  23668. */
  23669. class Mnemonic {
  23670. /**
  23671. * The mnemonic phrase of 12, 15, 18, 21 or 24 words.
  23672. *
  23673. * Use the [[wordlist]] ``split`` method to get the individual words.
  23674. */
  23675. phrase;
  23676. /**
  23677. * The password used for this mnemonic. If no password is used this
  23678. * is the empty string (i.e. ``""``) as per the specification.
  23679. */
  23680. password;
  23681. /**
  23682. * The wordlist for this mnemonic.
  23683. */
  23684. wordlist;
  23685. /**
  23686. * The underlying entropy which the mnemonic encodes.
  23687. */
  23688. entropy;
  23689. /**
  23690. * @private
  23691. */
  23692. constructor(guard, entropy, phrase, password, wordlist) {
  23693. if (password == null) {
  23694. password = "";
  23695. }
  23696. if (wordlist == null) {
  23697. wordlist = LangEn.wordlist();
  23698. }
  23699. assertPrivate(guard, _guard$1, "Mnemonic");
  23700. defineProperties(this, { phrase, password, wordlist, entropy });
  23701. }
  23702. /**
  23703. * Returns the seed for the mnemonic.
  23704. */
  23705. computeSeed() {
  23706. const salt = toUtf8Bytes("mnemonic" + this.password, "NFKD");
  23707. return pbkdf2(toUtf8Bytes(this.phrase, "NFKD"), salt, 2048, 64, "sha512");
  23708. }
  23709. /**
  23710. * Creates a new Mnemonic for the %%phrase%%.
  23711. *
  23712. * The default %%password%% is the empty string and the default
  23713. * wordlist is the [English wordlists](LangEn).
  23714. */
  23715. static fromPhrase(phrase, password, wordlist) {
  23716. // Normalize the case and space; throws if invalid
  23717. const entropy = mnemonicToEntropy(phrase, wordlist);
  23718. phrase = entropyToMnemonic(getBytes(entropy), wordlist);
  23719. return new Mnemonic(_guard$1, entropy, phrase, password, wordlist);
  23720. }
  23721. /**
  23722. * Create a new **Mnemonic** from the %%entropy%%.
  23723. *
  23724. * The default %%password%% is the empty string and the default
  23725. * wordlist is the [English wordlists](LangEn).
  23726. */
  23727. static fromEntropy(_entropy, password, wordlist) {
  23728. const entropy = getBytes(_entropy, "entropy");
  23729. const phrase = entropyToMnemonic(entropy, wordlist);
  23730. return new Mnemonic(_guard$1, hexlify(entropy), phrase, password, wordlist);
  23731. }
  23732. /**
  23733. * Returns the phrase for %%mnemonic%%.
  23734. */
  23735. static entropyToPhrase(_entropy, wordlist) {
  23736. const entropy = getBytes(_entropy, "entropy");
  23737. return entropyToMnemonic(entropy, wordlist);
  23738. }
  23739. /**
  23740. * Returns the entropy for %%phrase%%.
  23741. */
  23742. static phraseToEntropy(phrase, wordlist) {
  23743. return mnemonicToEntropy(phrase, wordlist);
  23744. }
  23745. /**
  23746. * Returns true if %%phrase%% is a valid [[link-bip-39]] phrase.
  23747. *
  23748. * This checks all the provided words belong to the %%wordlist%%,
  23749. * that the length is valid and the checksum is correct.
  23750. */
  23751. static isValidMnemonic(phrase, wordlist) {
  23752. try {
  23753. mnemonicToEntropy(phrase, wordlist);
  23754. return true;
  23755. }
  23756. catch (error) { }
  23757. return false;
  23758. }
  23759. }
  23760. /*! MIT License. Copyright 2015-2022 Richard Moore <me@ricmoo.com>. See LICENSE.txt. */
  23761. var __classPrivateFieldGet$2 = (__$G && __$G.__classPrivateFieldGet) || function (receiver, state, kind, f) {
  23762. if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
  23763. if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  23764. return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
  23765. };
  23766. var __classPrivateFieldSet$2 = (__$G && __$G.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
  23767. if (kind === "m") throw new TypeError("Private method is not writable");
  23768. if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
  23769. if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  23770. return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
  23771. };
  23772. var _AES_key, _AES_Kd, _AES_Ke;
  23773. // Number of rounds by keysize
  23774. const numberOfRounds = { 16: 10, 24: 12, 32: 14 };
  23775. // Round constant words
  23776. const rcon = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91];
  23777. // S-box and Inverse S-box (S is for Substitution)
  23778. const S = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16];
  23779. const Si = [0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d];
  23780. // Transformations for encryption
  23781. const T1 = [0xc66363a5, 0xf87c7c84, 0xee777799, 0xf67b7b8d, 0xfff2f20d, 0xd66b6bbd, 0xde6f6fb1, 0x91c5c554, 0x60303050, 0x02010103, 0xce6767a9, 0x562b2b7d, 0xe7fefe19, 0xb5d7d762, 0x4dababe6, 0xec76769a, 0x8fcaca45, 0x1f82829d, 0x89c9c940, 0xfa7d7d87, 0xeffafa15, 0xb25959eb, 0x8e4747c9, 0xfbf0f00b, 0x41adadec, 0xb3d4d467, 0x5fa2a2fd, 0x45afafea, 0x239c9cbf, 0x53a4a4f7, 0xe4727296, 0x9bc0c05b, 0x75b7b7c2, 0xe1fdfd1c, 0x3d9393ae, 0x4c26266a, 0x6c36365a, 0x7e3f3f41, 0xf5f7f702, 0x83cccc4f, 0x6834345c, 0x51a5a5f4, 0xd1e5e534, 0xf9f1f108, 0xe2717193, 0xabd8d873, 0x62313153, 0x2a15153f, 0x0804040c, 0x95c7c752, 0x46232365, 0x9dc3c35e, 0x30181828, 0x379696a1, 0x0a05050f, 0x2f9a9ab5, 0x0e070709, 0x24121236, 0x1b80809b, 0xdfe2e23d, 0xcdebeb26, 0x4e272769, 0x7fb2b2cd, 0xea75759f, 0x1209091b, 0x1d83839e, 0x582c2c74, 0x341a1a2e, 0x361b1b2d, 0xdc6e6eb2, 0xb45a5aee, 0x5ba0a0fb, 0xa45252f6, 0x763b3b4d, 0xb7d6d661, 0x7db3b3ce, 0x5229297b, 0xdde3e33e, 0x5e2f2f71, 0x13848497, 0xa65353f5, 0xb9d1d168, 0x00000000, 0xc1eded2c, 0x40202060, 0xe3fcfc1f, 0x79b1b1c8, 0xb65b5bed, 0xd46a6abe, 0x8dcbcb46, 0x67bebed9, 0x7239394b, 0x944a4ade, 0x984c4cd4, 0xb05858e8, 0x85cfcf4a, 0xbbd0d06b, 0xc5efef2a, 0x4faaaae5, 0xedfbfb16, 0x864343c5, 0x9a4d4dd7, 0x66333355, 0x11858594, 0x8a4545cf, 0xe9f9f910, 0x04020206, 0xfe7f7f81, 0xa05050f0, 0x783c3c44, 0x259f9fba, 0x4ba8a8e3, 0xa25151f3, 0x5da3a3fe, 0x804040c0, 0x058f8f8a, 0x3f9292ad, 0x219d9dbc, 0x70383848, 0xf1f5f504, 0x63bcbcdf, 0x77b6b6c1, 0xafdada75, 0x42212163, 0x20101030, 0xe5ffff1a, 0xfdf3f30e, 0xbfd2d26d, 0x81cdcd4c, 0x180c0c14, 0x26131335, 0xc3ecec2f, 0xbe5f5fe1, 0x359797a2, 0x884444cc, 0x2e171739, 0x93c4c457, 0x55a7a7f2, 0xfc7e7e82, 0x7a3d3d47, 0xc86464ac, 0xba5d5de7, 0x3219192b, 0xe6737395, 0xc06060a0, 0x19818198, 0x9e4f4fd1, 0xa3dcdc7f, 0x44222266, 0x542a2a7e, 0x3b9090ab, 0x0b888883, 0x8c4646ca, 0xc7eeee29, 0x6bb8b8d3, 0x2814143c, 0xa7dede79, 0xbc5e5ee2, 0x160b0b1d, 0xaddbdb76, 0xdbe0e03b, 0x64323256, 0x743a3a4e, 0x140a0a1e, 0x924949db, 0x0c06060a, 0x4824246c, 0xb85c5ce4, 0x9fc2c25d, 0xbdd3d36e, 0x43acacef, 0xc46262a6, 0x399191a8, 0x319595a4, 0xd3e4e437, 0xf279798b, 0xd5e7e732, 0x8bc8c843, 0x6e373759, 0xda6d6db7, 0x018d8d8c, 0xb1d5d564, 0x9c4e4ed2, 0x49a9a9e0, 0xd86c6cb4, 0xac5656fa, 0xf3f4f407, 0xcfeaea25, 0xca6565af, 0xf47a7a8e, 0x47aeaee9, 0x10080818, 0x6fbabad5, 0xf0787888, 0x4a25256f, 0x5c2e2e72, 0x381c1c24, 0x57a6a6f1, 0x73b4b4c7, 0x97c6c651, 0xcbe8e823, 0xa1dddd7c, 0xe874749c, 0x3e1f1f21, 0x964b4bdd, 0x61bdbddc, 0x0d8b8b86, 0x0f8a8a85, 0xe0707090, 0x7c3e3e42, 0x71b5b5c4, 0xcc6666aa, 0x904848d8, 0x06030305, 0xf7f6f601, 0x1c0e0e12, 0xc26161a3, 0x6a35355f, 0xae5757f9, 0x69b9b9d0, 0x17868691, 0x99c1c158, 0x3a1d1d27, 0x279e9eb9, 0xd9e1e138, 0xebf8f813, 0x2b9898b3, 0x22111133, 0xd26969bb, 0xa9d9d970, 0x078e8e89, 0x339494a7, 0x2d9b9bb6, 0x3c1e1e22, 0x15878792, 0xc9e9e920, 0x87cece49, 0xaa5555ff, 0x50282878, 0xa5dfdf7a, 0x038c8c8f, 0x59a1a1f8, 0x09898980, 0x1a0d0d17, 0x65bfbfda, 0xd7e6e631, 0x844242c6, 0xd06868b8, 0x824141c3, 0x299999b0, 0x5a2d2d77, 0x1e0f0f11, 0x7bb0b0cb, 0xa85454fc, 0x6dbbbbd6, 0x2c16163a];
  23782. const T2 = [0xa5c66363, 0x84f87c7c, 0x99ee7777, 0x8df67b7b, 0x0dfff2f2, 0xbdd66b6b, 0xb1de6f6f, 0x5491c5c5, 0x50603030, 0x03020101, 0xa9ce6767, 0x7d562b2b, 0x19e7fefe, 0x62b5d7d7, 0xe64dabab, 0x9aec7676, 0x458fcaca, 0x9d1f8282, 0x4089c9c9, 0x87fa7d7d, 0x15effafa, 0xebb25959, 0xc98e4747, 0x0bfbf0f0, 0xec41adad, 0x67b3d4d4, 0xfd5fa2a2, 0xea45afaf, 0xbf239c9c, 0xf753a4a4, 0x96e47272, 0x5b9bc0c0, 0xc275b7b7, 0x1ce1fdfd, 0xae3d9393, 0x6a4c2626, 0x5a6c3636, 0x417e3f3f, 0x02f5f7f7, 0x4f83cccc, 0x5c683434, 0xf451a5a5, 0x34d1e5e5, 0x08f9f1f1, 0x93e27171, 0x73abd8d8, 0x53623131, 0x3f2a1515, 0x0c080404, 0x5295c7c7, 0x65462323, 0x5e9dc3c3, 0x28301818, 0xa1379696, 0x0f0a0505, 0xb52f9a9a, 0x090e0707, 0x36241212, 0x9b1b8080, 0x3ddfe2e2, 0x26cdebeb, 0x694e2727, 0xcd7fb2b2, 0x9fea7575, 0x1b120909, 0x9e1d8383, 0x74582c2c, 0x2e341a1a, 0x2d361b1b, 0xb2dc6e6e, 0xeeb45a5a, 0xfb5ba0a0, 0xf6a45252, 0x4d763b3b, 0x61b7d6d6, 0xce7db3b3, 0x7b522929, 0x3edde3e3, 0x715e2f2f, 0x97138484, 0xf5a65353, 0x68b9d1d1, 0x00000000, 0x2cc1eded, 0x60402020, 0x1fe3fcfc, 0xc879b1b1, 0xedb65b5b, 0xbed46a6a, 0x468dcbcb, 0xd967bebe, 0x4b723939, 0xde944a4a, 0xd4984c4c, 0xe8b05858, 0x4a85cfcf, 0x6bbbd0d0, 0x2ac5efef, 0xe54faaaa, 0x16edfbfb, 0xc5864343, 0xd79a4d4d, 0x55663333, 0x94118585, 0xcf8a4545, 0x10e9f9f9, 0x06040202, 0x81fe7f7f, 0xf0a05050, 0x44783c3c, 0xba259f9f, 0xe34ba8a8, 0xf3a25151, 0xfe5da3a3, 0xc0804040, 0x8a058f8f, 0xad3f9292, 0xbc219d9d, 0x48703838, 0x04f1f5f5, 0xdf63bcbc, 0xc177b6b6, 0x75afdada, 0x63422121, 0x30201010, 0x1ae5ffff, 0x0efdf3f3, 0x6dbfd2d2, 0x4c81cdcd, 0x14180c0c, 0x35261313, 0x2fc3ecec, 0xe1be5f5f, 0xa2359797, 0xcc884444, 0x392e1717, 0x5793c4c4, 0xf255a7a7, 0x82fc7e7e, 0x477a3d3d, 0xacc86464, 0xe7ba5d5d, 0x2b321919, 0x95e67373, 0xa0c06060, 0x98198181, 0xd19e4f4f, 0x7fa3dcdc, 0x66442222, 0x7e542a2a, 0xab3b9090, 0x830b8888, 0xca8c4646, 0x29c7eeee, 0xd36bb8b8, 0x3c281414, 0x79a7dede, 0xe2bc5e5e, 0x1d160b0b, 0x76addbdb, 0x3bdbe0e0, 0x56643232, 0x4e743a3a, 0x1e140a0a, 0xdb924949, 0x0a0c0606, 0x6c482424, 0xe4b85c5c, 0x5d9fc2c2, 0x6ebdd3d3, 0xef43acac, 0xa6c46262, 0xa8399191, 0xa4319595, 0x37d3e4e4, 0x8bf27979, 0x32d5e7e7, 0x438bc8c8, 0x596e3737, 0xb7da6d6d, 0x8c018d8d, 0x64b1d5d5, 0xd29c4e4e, 0xe049a9a9, 0xb4d86c6c, 0xfaac5656, 0x07f3f4f4, 0x25cfeaea, 0xafca6565, 0x8ef47a7a, 0xe947aeae, 0x18100808, 0xd56fbaba, 0x88f07878, 0x6f4a2525, 0x725c2e2e, 0x24381c1c, 0xf157a6a6, 0xc773b4b4, 0x5197c6c6, 0x23cbe8e8, 0x7ca1dddd, 0x9ce87474, 0x213e1f1f, 0xdd964b4b, 0xdc61bdbd, 0x860d8b8b, 0x850f8a8a, 0x90e07070, 0x427c3e3e, 0xc471b5b5, 0xaacc6666, 0xd8904848, 0x05060303, 0x01f7f6f6, 0x121c0e0e, 0xa3c26161, 0x5f6a3535, 0xf9ae5757, 0xd069b9b9, 0x91178686, 0x5899c1c1, 0x273a1d1d, 0xb9279e9e, 0x38d9e1e1, 0x13ebf8f8, 0xb32b9898, 0x33221111, 0xbbd26969, 0x70a9d9d9, 0x89078e8e, 0xa7339494, 0xb62d9b9b, 0x223c1e1e, 0x92158787, 0x20c9e9e9, 0x4987cece, 0xffaa5555, 0x78502828, 0x7aa5dfdf, 0x8f038c8c, 0xf859a1a1, 0x80098989, 0x171a0d0d, 0xda65bfbf, 0x31d7e6e6, 0xc6844242, 0xb8d06868, 0xc3824141, 0xb0299999, 0x775a2d2d, 0x111e0f0f, 0xcb7bb0b0, 0xfca85454, 0xd66dbbbb, 0x3a2c1616];
  23783. const T3 = [0x63a5c663, 0x7c84f87c, 0x7799ee77, 0x7b8df67b, 0xf20dfff2, 0x6bbdd66b, 0x6fb1de6f, 0xc55491c5, 0x30506030, 0x01030201, 0x67a9ce67, 0x2b7d562b, 0xfe19e7fe, 0xd762b5d7, 0xabe64dab, 0x769aec76, 0xca458fca, 0x829d1f82, 0xc94089c9, 0x7d87fa7d, 0xfa15effa, 0x59ebb259, 0x47c98e47, 0xf00bfbf0, 0xadec41ad, 0xd467b3d4, 0xa2fd5fa2, 0xafea45af, 0x9cbf239c, 0xa4f753a4, 0x7296e472, 0xc05b9bc0, 0xb7c275b7, 0xfd1ce1fd, 0x93ae3d93, 0x266a4c26, 0x365a6c36, 0x3f417e3f, 0xf702f5f7, 0xcc4f83cc, 0x345c6834, 0xa5f451a5, 0xe534d1e5, 0xf108f9f1, 0x7193e271, 0xd873abd8, 0x31536231, 0x153f2a15, 0x040c0804, 0xc75295c7, 0x23654623, 0xc35e9dc3, 0x18283018, 0x96a13796, 0x050f0a05, 0x9ab52f9a, 0x07090e07, 0x12362412, 0x809b1b80, 0xe23ddfe2, 0xeb26cdeb, 0x27694e27, 0xb2cd7fb2, 0x759fea75, 0x091b1209, 0x839e1d83, 0x2c74582c, 0x1a2e341a, 0x1b2d361b, 0x6eb2dc6e, 0x5aeeb45a, 0xa0fb5ba0, 0x52f6a452, 0x3b4d763b, 0xd661b7d6, 0xb3ce7db3, 0x297b5229, 0xe33edde3, 0x2f715e2f, 0x84971384, 0x53f5a653, 0xd168b9d1, 0x00000000, 0xed2cc1ed, 0x20604020, 0xfc1fe3fc, 0xb1c879b1, 0x5bedb65b, 0x6abed46a, 0xcb468dcb, 0xbed967be, 0x394b7239, 0x4ade944a, 0x4cd4984c, 0x58e8b058, 0xcf4a85cf, 0xd06bbbd0, 0xef2ac5ef, 0xaae54faa, 0xfb16edfb, 0x43c58643, 0x4dd79a4d, 0x33556633, 0x85941185, 0x45cf8a45, 0xf910e9f9, 0x02060402, 0x7f81fe7f, 0x50f0a050, 0x3c44783c, 0x9fba259f, 0xa8e34ba8, 0x51f3a251, 0xa3fe5da3, 0x40c08040, 0x8f8a058f, 0x92ad3f92, 0x9dbc219d, 0x38487038, 0xf504f1f5, 0xbcdf63bc, 0xb6c177b6, 0xda75afda, 0x21634221, 0x10302010, 0xff1ae5ff, 0xf30efdf3, 0xd26dbfd2, 0xcd4c81cd, 0x0c14180c, 0x13352613, 0xec2fc3ec, 0x5fe1be5f, 0x97a23597, 0x44cc8844, 0x17392e17, 0xc45793c4, 0xa7f255a7, 0x7e82fc7e, 0x3d477a3d, 0x64acc864, 0x5de7ba5d, 0x192b3219, 0x7395e673, 0x60a0c060, 0x81981981, 0x4fd19e4f, 0xdc7fa3dc, 0x22664422, 0x2a7e542a, 0x90ab3b90, 0x88830b88, 0x46ca8c46, 0xee29c7ee, 0xb8d36bb8, 0x143c2814, 0xde79a7de, 0x5ee2bc5e, 0x0b1d160b, 0xdb76addb, 0xe03bdbe0, 0x32566432, 0x3a4e743a, 0x0a1e140a, 0x49db9249, 0x060a0c06, 0x246c4824, 0x5ce4b85c, 0xc25d9fc2, 0xd36ebdd3, 0xacef43ac, 0x62a6c462, 0x91a83991, 0x95a43195, 0xe437d3e4, 0x798bf279, 0xe732d5e7, 0xc8438bc8, 0x37596e37, 0x6db7da6d, 0x8d8c018d, 0xd564b1d5, 0x4ed29c4e, 0xa9e049a9, 0x6cb4d86c, 0x56faac56, 0xf407f3f4, 0xea25cfea, 0x65afca65, 0x7a8ef47a, 0xaee947ae, 0x08181008, 0xbad56fba, 0x7888f078, 0x256f4a25, 0x2e725c2e, 0x1c24381c, 0xa6f157a6, 0xb4c773b4, 0xc65197c6, 0xe823cbe8, 0xdd7ca1dd, 0x749ce874, 0x1f213e1f, 0x4bdd964b, 0xbddc61bd, 0x8b860d8b, 0x8a850f8a, 0x7090e070, 0x3e427c3e, 0xb5c471b5, 0x66aacc66, 0x48d89048, 0x03050603, 0xf601f7f6, 0x0e121c0e, 0x61a3c261, 0x355f6a35, 0x57f9ae57, 0xb9d069b9, 0x86911786, 0xc15899c1, 0x1d273a1d, 0x9eb9279e, 0xe138d9e1, 0xf813ebf8, 0x98b32b98, 0x11332211, 0x69bbd269, 0xd970a9d9, 0x8e89078e, 0x94a73394, 0x9bb62d9b, 0x1e223c1e, 0x87921587, 0xe920c9e9, 0xce4987ce, 0x55ffaa55, 0x28785028, 0xdf7aa5df, 0x8c8f038c, 0xa1f859a1, 0x89800989, 0x0d171a0d, 0xbfda65bf, 0xe631d7e6, 0x42c68442, 0x68b8d068, 0x41c38241, 0x99b02999, 0x2d775a2d, 0x0f111e0f, 0xb0cb7bb0, 0x54fca854, 0xbbd66dbb, 0x163a2c16];
  23784. const T4 = [0x6363a5c6, 0x7c7c84f8, 0x777799ee, 0x7b7b8df6, 0xf2f20dff, 0x6b6bbdd6, 0x6f6fb1de, 0xc5c55491, 0x30305060, 0x01010302, 0x6767a9ce, 0x2b2b7d56, 0xfefe19e7, 0xd7d762b5, 0xababe64d, 0x76769aec, 0xcaca458f, 0x82829d1f, 0xc9c94089, 0x7d7d87fa, 0xfafa15ef, 0x5959ebb2, 0x4747c98e, 0xf0f00bfb, 0xadadec41, 0xd4d467b3, 0xa2a2fd5f, 0xafafea45, 0x9c9cbf23, 0xa4a4f753, 0x727296e4, 0xc0c05b9b, 0xb7b7c275, 0xfdfd1ce1, 0x9393ae3d, 0x26266a4c, 0x36365a6c, 0x3f3f417e, 0xf7f702f5, 0xcccc4f83, 0x34345c68, 0xa5a5f451, 0xe5e534d1, 0xf1f108f9, 0x717193e2, 0xd8d873ab, 0x31315362, 0x15153f2a, 0x04040c08, 0xc7c75295, 0x23236546, 0xc3c35e9d, 0x18182830, 0x9696a137, 0x05050f0a, 0x9a9ab52f, 0x0707090e, 0x12123624, 0x80809b1b, 0xe2e23ddf, 0xebeb26cd, 0x2727694e, 0xb2b2cd7f, 0x75759fea, 0x09091b12, 0x83839e1d, 0x2c2c7458, 0x1a1a2e34, 0x1b1b2d36, 0x6e6eb2dc, 0x5a5aeeb4, 0xa0a0fb5b, 0x5252f6a4, 0x3b3b4d76, 0xd6d661b7, 0xb3b3ce7d, 0x29297b52, 0xe3e33edd, 0x2f2f715e, 0x84849713, 0x5353f5a6, 0xd1d168b9, 0x00000000, 0xeded2cc1, 0x20206040, 0xfcfc1fe3, 0xb1b1c879, 0x5b5bedb6, 0x6a6abed4, 0xcbcb468d, 0xbebed967, 0x39394b72, 0x4a4ade94, 0x4c4cd498, 0x5858e8b0, 0xcfcf4a85, 0xd0d06bbb, 0xefef2ac5, 0xaaaae54f, 0xfbfb16ed, 0x4343c586, 0x4d4dd79a, 0x33335566, 0x85859411, 0x4545cf8a, 0xf9f910e9, 0x02020604, 0x7f7f81fe, 0x5050f0a0, 0x3c3c4478, 0x9f9fba25, 0xa8a8e34b, 0x5151f3a2, 0xa3a3fe5d, 0x4040c080, 0x8f8f8a05, 0x9292ad3f, 0x9d9dbc21, 0x38384870, 0xf5f504f1, 0xbcbcdf63, 0xb6b6c177, 0xdada75af, 0x21216342, 0x10103020, 0xffff1ae5, 0xf3f30efd, 0xd2d26dbf, 0xcdcd4c81, 0x0c0c1418, 0x13133526, 0xecec2fc3, 0x5f5fe1be, 0x9797a235, 0x4444cc88, 0x1717392e, 0xc4c45793, 0xa7a7f255, 0x7e7e82fc, 0x3d3d477a, 0x6464acc8, 0x5d5de7ba, 0x19192b32, 0x737395e6, 0x6060a0c0, 0x81819819, 0x4f4fd19e, 0xdcdc7fa3, 0x22226644, 0x2a2a7e54, 0x9090ab3b, 0x8888830b, 0x4646ca8c, 0xeeee29c7, 0xb8b8d36b, 0x14143c28, 0xdede79a7, 0x5e5ee2bc, 0x0b0b1d16, 0xdbdb76ad, 0xe0e03bdb, 0x32325664, 0x3a3a4e74, 0x0a0a1e14, 0x4949db92, 0x06060a0c, 0x24246c48, 0x5c5ce4b8, 0xc2c25d9f, 0xd3d36ebd, 0xacacef43, 0x6262a6c4, 0x9191a839, 0x9595a431, 0xe4e437d3, 0x79798bf2, 0xe7e732d5, 0xc8c8438b, 0x3737596e, 0x6d6db7da, 0x8d8d8c01, 0xd5d564b1, 0x4e4ed29c, 0xa9a9e049, 0x6c6cb4d8, 0x5656faac, 0xf4f407f3, 0xeaea25cf, 0x6565afca, 0x7a7a8ef4, 0xaeaee947, 0x08081810, 0xbabad56f, 0x787888f0, 0x25256f4a, 0x2e2e725c, 0x1c1c2438, 0xa6a6f157, 0xb4b4c773, 0xc6c65197, 0xe8e823cb, 0xdddd7ca1, 0x74749ce8, 0x1f1f213e, 0x4b4bdd96, 0xbdbddc61, 0x8b8b860d, 0x8a8a850f, 0x707090e0, 0x3e3e427c, 0xb5b5c471, 0x6666aacc, 0x4848d890, 0x03030506, 0xf6f601f7, 0x0e0e121c, 0x6161a3c2, 0x35355f6a, 0x5757f9ae, 0xb9b9d069, 0x86869117, 0xc1c15899, 0x1d1d273a, 0x9e9eb927, 0xe1e138d9, 0xf8f813eb, 0x9898b32b, 0x11113322, 0x6969bbd2, 0xd9d970a9, 0x8e8e8907, 0x9494a733, 0x9b9bb62d, 0x1e1e223c, 0x87879215, 0xe9e920c9, 0xcece4987, 0x5555ffaa, 0x28287850, 0xdfdf7aa5, 0x8c8c8f03, 0xa1a1f859, 0x89898009, 0x0d0d171a, 0xbfbfda65, 0xe6e631d7, 0x4242c684, 0x6868b8d0, 0x4141c382, 0x9999b029, 0x2d2d775a, 0x0f0f111e, 0xb0b0cb7b, 0x5454fca8, 0xbbbbd66d, 0x16163a2c];
  23785. // Transformations for decryption
  23786. const T5 = [0x51f4a750, 0x7e416553, 0x1a17a4c3, 0x3a275e96, 0x3bab6bcb, 0x1f9d45f1, 0xacfa58ab, 0x4be30393, 0x2030fa55, 0xad766df6, 0x88cc7691, 0xf5024c25, 0x4fe5d7fc, 0xc52acbd7, 0x26354480, 0xb562a38f, 0xdeb15a49, 0x25ba1b67, 0x45ea0e98, 0x5dfec0e1, 0xc32f7502, 0x814cf012, 0x8d4697a3, 0x6bd3f9c6, 0x038f5fe7, 0x15929c95, 0xbf6d7aeb, 0x955259da, 0xd4be832d, 0x587421d3, 0x49e06929, 0x8ec9c844, 0x75c2896a, 0xf48e7978, 0x99583e6b, 0x27b971dd, 0xbee14fb6, 0xf088ad17, 0xc920ac66, 0x7dce3ab4, 0x63df4a18, 0xe51a3182, 0x97513360, 0x62537f45, 0xb16477e0, 0xbb6bae84, 0xfe81a01c, 0xf9082b94, 0x70486858, 0x8f45fd19, 0x94de6c87, 0x527bf8b7, 0xab73d323, 0x724b02e2, 0xe31f8f57, 0x6655ab2a, 0xb2eb2807, 0x2fb5c203, 0x86c57b9a, 0xd33708a5, 0x302887f2, 0x23bfa5b2, 0x02036aba, 0xed16825c, 0x8acf1c2b, 0xa779b492, 0xf307f2f0, 0x4e69e2a1, 0x65daf4cd, 0x0605bed5, 0xd134621f, 0xc4a6fe8a, 0x342e539d, 0xa2f355a0, 0x058ae132, 0xa4f6eb75, 0x0b83ec39, 0x4060efaa, 0x5e719f06, 0xbd6e1051, 0x3e218af9, 0x96dd063d, 0xdd3e05ae, 0x4de6bd46, 0x91548db5, 0x71c45d05, 0x0406d46f, 0x605015ff, 0x1998fb24, 0xd6bde997, 0x894043cc, 0x67d99e77, 0xb0e842bd, 0x07898b88, 0xe7195b38, 0x79c8eedb, 0xa17c0a47, 0x7c420fe9, 0xf8841ec9, 0x00000000, 0x09808683, 0x322bed48, 0x1e1170ac, 0x6c5a724e, 0xfd0efffb, 0x0f853856, 0x3daed51e, 0x362d3927, 0x0a0fd964, 0x685ca621, 0x9b5b54d1, 0x24362e3a, 0x0c0a67b1, 0x9357e70f, 0xb4ee96d2, 0x1b9b919e, 0x80c0c54f, 0x61dc20a2, 0x5a774b69, 0x1c121a16, 0xe293ba0a, 0xc0a02ae5, 0x3c22e043, 0x121b171d, 0x0e090d0b, 0xf28bc7ad, 0x2db6a8b9, 0x141ea9c8, 0x57f11985, 0xaf75074c, 0xee99ddbb, 0xa37f60fd, 0xf701269f, 0x5c72f5bc, 0x44663bc5, 0x5bfb7e34, 0x8b432976, 0xcb23c6dc, 0xb6edfc68, 0xb8e4f163, 0xd731dcca, 0x42638510, 0x13972240, 0x84c61120, 0x854a247d, 0xd2bb3df8, 0xaef93211, 0xc729a16d, 0x1d9e2f4b, 0xdcb230f3, 0x0d8652ec, 0x77c1e3d0, 0x2bb3166c, 0xa970b999, 0x119448fa, 0x47e96422, 0xa8fc8cc4, 0xa0f03f1a, 0x567d2cd8, 0x223390ef, 0x87494ec7, 0xd938d1c1, 0x8ccaa2fe, 0x98d40b36, 0xa6f581cf, 0xa57ade28, 0xdab78e26, 0x3fadbfa4, 0x2c3a9de4, 0x5078920d, 0x6a5fcc9b, 0x547e4662, 0xf68d13c2, 0x90d8b8e8, 0x2e39f75e, 0x82c3aff5, 0x9f5d80be, 0x69d0937c, 0x6fd52da9, 0xcf2512b3, 0xc8ac993b, 0x10187da7, 0xe89c636e, 0xdb3bbb7b, 0xcd267809, 0x6e5918f4, 0xec9ab701, 0x834f9aa8, 0xe6956e65, 0xaaffe67e, 0x21bccf08, 0xef15e8e6, 0xbae79bd9, 0x4a6f36ce, 0xea9f09d4, 0x29b07cd6, 0x31a4b2af, 0x2a3f2331, 0xc6a59430, 0x35a266c0, 0x744ebc37, 0xfc82caa6, 0xe090d0b0, 0x33a7d815, 0xf104984a, 0x41ecdaf7, 0x7fcd500e, 0x1791f62f, 0x764dd68d, 0x43efb04d, 0xccaa4d54, 0xe49604df, 0x9ed1b5e3, 0x4c6a881b, 0xc12c1fb8, 0x4665517f, 0x9d5eea04, 0x018c355d, 0xfa877473, 0xfb0b412e, 0xb3671d5a, 0x92dbd252, 0xe9105633, 0x6dd64713, 0x9ad7618c, 0x37a10c7a, 0x59f8148e, 0xeb133c89, 0xcea927ee, 0xb761c935, 0xe11ce5ed, 0x7a47b13c, 0x9cd2df59, 0x55f2733f, 0x1814ce79, 0x73c737bf, 0x53f7cdea, 0x5ffdaa5b, 0xdf3d6f14, 0x7844db86, 0xcaaff381, 0xb968c43e, 0x3824342c, 0xc2a3405f, 0x161dc372, 0xbce2250c, 0x283c498b, 0xff0d9541, 0x39a80171, 0x080cb3de, 0xd8b4e49c, 0x6456c190, 0x7bcb8461, 0xd532b670, 0x486c5c74, 0xd0b85742];
  23787. const T6 = [0x5051f4a7, 0x537e4165, 0xc31a17a4, 0x963a275e, 0xcb3bab6b, 0xf11f9d45, 0xabacfa58, 0x934be303, 0x552030fa, 0xf6ad766d, 0x9188cc76, 0x25f5024c, 0xfc4fe5d7, 0xd7c52acb, 0x80263544, 0x8fb562a3, 0x49deb15a, 0x6725ba1b, 0x9845ea0e, 0xe15dfec0, 0x02c32f75, 0x12814cf0, 0xa38d4697, 0xc66bd3f9, 0xe7038f5f, 0x9515929c, 0xebbf6d7a, 0xda955259, 0x2dd4be83, 0xd3587421, 0x2949e069, 0x448ec9c8, 0x6a75c289, 0x78f48e79, 0x6b99583e, 0xdd27b971, 0xb6bee14f, 0x17f088ad, 0x66c920ac, 0xb47dce3a, 0x1863df4a, 0x82e51a31, 0x60975133, 0x4562537f, 0xe0b16477, 0x84bb6bae, 0x1cfe81a0, 0x94f9082b, 0x58704868, 0x198f45fd, 0x8794de6c, 0xb7527bf8, 0x23ab73d3, 0xe2724b02, 0x57e31f8f, 0x2a6655ab, 0x07b2eb28, 0x032fb5c2, 0x9a86c57b, 0xa5d33708, 0xf2302887, 0xb223bfa5, 0xba02036a, 0x5ced1682, 0x2b8acf1c, 0x92a779b4, 0xf0f307f2, 0xa14e69e2, 0xcd65daf4, 0xd50605be, 0x1fd13462, 0x8ac4a6fe, 0x9d342e53, 0xa0a2f355, 0x32058ae1, 0x75a4f6eb, 0x390b83ec, 0xaa4060ef, 0x065e719f, 0x51bd6e10, 0xf93e218a, 0x3d96dd06, 0xaedd3e05, 0x464de6bd, 0xb591548d, 0x0571c45d, 0x6f0406d4, 0xff605015, 0x241998fb, 0x97d6bde9, 0xcc894043, 0x7767d99e, 0xbdb0e842, 0x8807898b, 0x38e7195b, 0xdb79c8ee, 0x47a17c0a, 0xe97c420f, 0xc9f8841e, 0x00000000, 0x83098086, 0x48322bed, 0xac1e1170, 0x4e6c5a72, 0xfbfd0eff, 0x560f8538, 0x1e3daed5, 0x27362d39, 0x640a0fd9, 0x21685ca6, 0xd19b5b54, 0x3a24362e, 0xb10c0a67, 0x0f9357e7, 0xd2b4ee96, 0x9e1b9b91, 0x4f80c0c5, 0xa261dc20, 0x695a774b, 0x161c121a, 0x0ae293ba, 0xe5c0a02a, 0x433c22e0, 0x1d121b17, 0x0b0e090d, 0xadf28bc7, 0xb92db6a8, 0xc8141ea9, 0x8557f119, 0x4caf7507, 0xbbee99dd, 0xfda37f60, 0x9ff70126, 0xbc5c72f5, 0xc544663b, 0x345bfb7e, 0x768b4329, 0xdccb23c6, 0x68b6edfc, 0x63b8e4f1, 0xcad731dc, 0x10426385, 0x40139722, 0x2084c611, 0x7d854a24, 0xf8d2bb3d, 0x11aef932, 0x6dc729a1, 0x4b1d9e2f, 0xf3dcb230, 0xec0d8652, 0xd077c1e3, 0x6c2bb316, 0x99a970b9, 0xfa119448, 0x2247e964, 0xc4a8fc8c, 0x1aa0f03f, 0xd8567d2c, 0xef223390, 0xc787494e, 0xc1d938d1, 0xfe8ccaa2, 0x3698d40b, 0xcfa6f581, 0x28a57ade, 0x26dab78e, 0xa43fadbf, 0xe42c3a9d, 0x0d507892, 0x9b6a5fcc, 0x62547e46, 0xc2f68d13, 0xe890d8b8, 0x5e2e39f7, 0xf582c3af, 0xbe9f5d80, 0x7c69d093, 0xa96fd52d, 0xb3cf2512, 0x3bc8ac99, 0xa710187d, 0x6ee89c63, 0x7bdb3bbb, 0x09cd2678, 0xf46e5918, 0x01ec9ab7, 0xa8834f9a, 0x65e6956e, 0x7eaaffe6, 0x0821bccf, 0xe6ef15e8, 0xd9bae79b, 0xce4a6f36, 0xd4ea9f09, 0xd629b07c, 0xaf31a4b2, 0x312a3f23, 0x30c6a594, 0xc035a266, 0x37744ebc, 0xa6fc82ca, 0xb0e090d0, 0x1533a7d8, 0x4af10498, 0xf741ecda, 0x0e7fcd50, 0x2f1791f6, 0x8d764dd6, 0x4d43efb0, 0x54ccaa4d, 0xdfe49604, 0xe39ed1b5, 0x1b4c6a88, 0xb8c12c1f, 0x7f466551, 0x049d5eea, 0x5d018c35, 0x73fa8774, 0x2efb0b41, 0x5ab3671d, 0x5292dbd2, 0x33e91056, 0x136dd647, 0x8c9ad761, 0x7a37a10c, 0x8e59f814, 0x89eb133c, 0xeecea927, 0x35b761c9, 0xede11ce5, 0x3c7a47b1, 0x599cd2df, 0x3f55f273, 0x791814ce, 0xbf73c737, 0xea53f7cd, 0x5b5ffdaa, 0x14df3d6f, 0x867844db, 0x81caaff3, 0x3eb968c4, 0x2c382434, 0x5fc2a340, 0x72161dc3, 0x0cbce225, 0x8b283c49, 0x41ff0d95, 0x7139a801, 0xde080cb3, 0x9cd8b4e4, 0x906456c1, 0x617bcb84, 0x70d532b6, 0x74486c5c, 0x42d0b857];
  23788. const T7 = [0xa75051f4, 0x65537e41, 0xa4c31a17, 0x5e963a27, 0x6bcb3bab, 0x45f11f9d, 0x58abacfa, 0x03934be3, 0xfa552030, 0x6df6ad76, 0x769188cc, 0x4c25f502, 0xd7fc4fe5, 0xcbd7c52a, 0x44802635, 0xa38fb562, 0x5a49deb1, 0x1b6725ba, 0x0e9845ea, 0xc0e15dfe, 0x7502c32f, 0xf012814c, 0x97a38d46, 0xf9c66bd3, 0x5fe7038f, 0x9c951592, 0x7aebbf6d, 0x59da9552, 0x832dd4be, 0x21d35874, 0x692949e0, 0xc8448ec9, 0x896a75c2, 0x7978f48e, 0x3e6b9958, 0x71dd27b9, 0x4fb6bee1, 0xad17f088, 0xac66c920, 0x3ab47dce, 0x4a1863df, 0x3182e51a, 0x33609751, 0x7f456253, 0x77e0b164, 0xae84bb6b, 0xa01cfe81, 0x2b94f908, 0x68587048, 0xfd198f45, 0x6c8794de, 0xf8b7527b, 0xd323ab73, 0x02e2724b, 0x8f57e31f, 0xab2a6655, 0x2807b2eb, 0xc2032fb5, 0x7b9a86c5, 0x08a5d337, 0x87f23028, 0xa5b223bf, 0x6aba0203, 0x825ced16, 0x1c2b8acf, 0xb492a779, 0xf2f0f307, 0xe2a14e69, 0xf4cd65da, 0xbed50605, 0x621fd134, 0xfe8ac4a6, 0x539d342e, 0x55a0a2f3, 0xe132058a, 0xeb75a4f6, 0xec390b83, 0xefaa4060, 0x9f065e71, 0x1051bd6e, 0x8af93e21, 0x063d96dd, 0x05aedd3e, 0xbd464de6, 0x8db59154, 0x5d0571c4, 0xd46f0406, 0x15ff6050, 0xfb241998, 0xe997d6bd, 0x43cc8940, 0x9e7767d9, 0x42bdb0e8, 0x8b880789, 0x5b38e719, 0xeedb79c8, 0x0a47a17c, 0x0fe97c42, 0x1ec9f884, 0x00000000, 0x86830980, 0xed48322b, 0x70ac1e11, 0x724e6c5a, 0xfffbfd0e, 0x38560f85, 0xd51e3dae, 0x3927362d, 0xd9640a0f, 0xa621685c, 0x54d19b5b, 0x2e3a2436, 0x67b10c0a, 0xe70f9357, 0x96d2b4ee, 0x919e1b9b, 0xc54f80c0, 0x20a261dc, 0x4b695a77, 0x1a161c12, 0xba0ae293, 0x2ae5c0a0, 0xe0433c22, 0x171d121b, 0x0d0b0e09, 0xc7adf28b, 0xa8b92db6, 0xa9c8141e, 0x198557f1, 0x074caf75, 0xddbbee99, 0x60fda37f, 0x269ff701, 0xf5bc5c72, 0x3bc54466, 0x7e345bfb, 0x29768b43, 0xc6dccb23, 0xfc68b6ed, 0xf163b8e4, 0xdccad731, 0x85104263, 0x22401397, 0x112084c6, 0x247d854a, 0x3df8d2bb, 0x3211aef9, 0xa16dc729, 0x2f4b1d9e, 0x30f3dcb2, 0x52ec0d86, 0xe3d077c1, 0x166c2bb3, 0xb999a970, 0x48fa1194, 0x642247e9, 0x8cc4a8fc, 0x3f1aa0f0, 0x2cd8567d, 0x90ef2233, 0x4ec78749, 0xd1c1d938, 0xa2fe8cca, 0x0b3698d4, 0x81cfa6f5, 0xde28a57a, 0x8e26dab7, 0xbfa43fad, 0x9de42c3a, 0x920d5078, 0xcc9b6a5f, 0x4662547e, 0x13c2f68d, 0xb8e890d8, 0xf75e2e39, 0xaff582c3, 0x80be9f5d, 0x937c69d0, 0x2da96fd5, 0x12b3cf25, 0x993bc8ac, 0x7da71018, 0x636ee89c, 0xbb7bdb3b, 0x7809cd26, 0x18f46e59, 0xb701ec9a, 0x9aa8834f, 0x6e65e695, 0xe67eaaff, 0xcf0821bc, 0xe8e6ef15, 0x9bd9bae7, 0x36ce4a6f, 0x09d4ea9f, 0x7cd629b0, 0xb2af31a4, 0x23312a3f, 0x9430c6a5, 0x66c035a2, 0xbc37744e, 0xcaa6fc82, 0xd0b0e090, 0xd81533a7, 0x984af104, 0xdaf741ec, 0x500e7fcd, 0xf62f1791, 0xd68d764d, 0xb04d43ef, 0x4d54ccaa, 0x04dfe496, 0xb5e39ed1, 0x881b4c6a, 0x1fb8c12c, 0x517f4665, 0xea049d5e, 0x355d018c, 0x7473fa87, 0x412efb0b, 0x1d5ab367, 0xd25292db, 0x5633e910, 0x47136dd6, 0x618c9ad7, 0x0c7a37a1, 0x148e59f8, 0x3c89eb13, 0x27eecea9, 0xc935b761, 0xe5ede11c, 0xb13c7a47, 0xdf599cd2, 0x733f55f2, 0xce791814, 0x37bf73c7, 0xcdea53f7, 0xaa5b5ffd, 0x6f14df3d, 0xdb867844, 0xf381caaf, 0xc43eb968, 0x342c3824, 0x405fc2a3, 0xc372161d, 0x250cbce2, 0x498b283c, 0x9541ff0d, 0x017139a8, 0xb3de080c, 0xe49cd8b4, 0xc1906456, 0x84617bcb, 0xb670d532, 0x5c74486c, 0x5742d0b8];
  23789. const T8 = [0xf4a75051, 0x4165537e, 0x17a4c31a, 0x275e963a, 0xab6bcb3b, 0x9d45f11f, 0xfa58abac, 0xe303934b, 0x30fa5520, 0x766df6ad, 0xcc769188, 0x024c25f5, 0xe5d7fc4f, 0x2acbd7c5, 0x35448026, 0x62a38fb5, 0xb15a49de, 0xba1b6725, 0xea0e9845, 0xfec0e15d, 0x2f7502c3, 0x4cf01281, 0x4697a38d, 0xd3f9c66b, 0x8f5fe703, 0x929c9515, 0x6d7aebbf, 0x5259da95, 0xbe832dd4, 0x7421d358, 0xe0692949, 0xc9c8448e, 0xc2896a75, 0x8e7978f4, 0x583e6b99, 0xb971dd27, 0xe14fb6be, 0x88ad17f0, 0x20ac66c9, 0xce3ab47d, 0xdf4a1863, 0x1a3182e5, 0x51336097, 0x537f4562, 0x6477e0b1, 0x6bae84bb, 0x81a01cfe, 0x082b94f9, 0x48685870, 0x45fd198f, 0xde6c8794, 0x7bf8b752, 0x73d323ab, 0x4b02e272, 0x1f8f57e3, 0x55ab2a66, 0xeb2807b2, 0xb5c2032f, 0xc57b9a86, 0x3708a5d3, 0x2887f230, 0xbfa5b223, 0x036aba02, 0x16825ced, 0xcf1c2b8a, 0x79b492a7, 0x07f2f0f3, 0x69e2a14e, 0xdaf4cd65, 0x05bed506, 0x34621fd1, 0xa6fe8ac4, 0x2e539d34, 0xf355a0a2, 0x8ae13205, 0xf6eb75a4, 0x83ec390b, 0x60efaa40, 0x719f065e, 0x6e1051bd, 0x218af93e, 0xdd063d96, 0x3e05aedd, 0xe6bd464d, 0x548db591, 0xc45d0571, 0x06d46f04, 0x5015ff60, 0x98fb2419, 0xbde997d6, 0x4043cc89, 0xd99e7767, 0xe842bdb0, 0x898b8807, 0x195b38e7, 0xc8eedb79, 0x7c0a47a1, 0x420fe97c, 0x841ec9f8, 0x00000000, 0x80868309, 0x2bed4832, 0x1170ac1e, 0x5a724e6c, 0x0efffbfd, 0x8538560f, 0xaed51e3d, 0x2d392736, 0x0fd9640a, 0x5ca62168, 0x5b54d19b, 0x362e3a24, 0x0a67b10c, 0x57e70f93, 0xee96d2b4, 0x9b919e1b, 0xc0c54f80, 0xdc20a261, 0x774b695a, 0x121a161c, 0x93ba0ae2, 0xa02ae5c0, 0x22e0433c, 0x1b171d12, 0x090d0b0e, 0x8bc7adf2, 0xb6a8b92d, 0x1ea9c814, 0xf1198557, 0x75074caf, 0x99ddbbee, 0x7f60fda3, 0x01269ff7, 0x72f5bc5c, 0x663bc544, 0xfb7e345b, 0x4329768b, 0x23c6dccb, 0xedfc68b6, 0xe4f163b8, 0x31dccad7, 0x63851042, 0x97224013, 0xc6112084, 0x4a247d85, 0xbb3df8d2, 0xf93211ae, 0x29a16dc7, 0x9e2f4b1d, 0xb230f3dc, 0x8652ec0d, 0xc1e3d077, 0xb3166c2b, 0x70b999a9, 0x9448fa11, 0xe9642247, 0xfc8cc4a8, 0xf03f1aa0, 0x7d2cd856, 0x3390ef22, 0x494ec787, 0x38d1c1d9, 0xcaa2fe8c, 0xd40b3698, 0xf581cfa6, 0x7ade28a5, 0xb78e26da, 0xadbfa43f, 0x3a9de42c, 0x78920d50, 0x5fcc9b6a, 0x7e466254, 0x8d13c2f6, 0xd8b8e890, 0x39f75e2e, 0xc3aff582, 0x5d80be9f, 0xd0937c69, 0xd52da96f, 0x2512b3cf, 0xac993bc8, 0x187da710, 0x9c636ee8, 0x3bbb7bdb, 0x267809cd, 0x5918f46e, 0x9ab701ec, 0x4f9aa883, 0x956e65e6, 0xffe67eaa, 0xbccf0821, 0x15e8e6ef, 0xe79bd9ba, 0x6f36ce4a, 0x9f09d4ea, 0xb07cd629, 0xa4b2af31, 0x3f23312a, 0xa59430c6, 0xa266c035, 0x4ebc3774, 0x82caa6fc, 0x90d0b0e0, 0xa7d81533, 0x04984af1, 0xecdaf741, 0xcd500e7f, 0x91f62f17, 0x4dd68d76, 0xefb04d43, 0xaa4d54cc, 0x9604dfe4, 0xd1b5e39e, 0x6a881b4c, 0x2c1fb8c1, 0x65517f46, 0x5eea049d, 0x8c355d01, 0x877473fa, 0x0b412efb, 0x671d5ab3, 0xdbd25292, 0x105633e9, 0xd647136d, 0xd7618c9a, 0xa10c7a37, 0xf8148e59, 0x133c89eb, 0xa927eece, 0x61c935b7, 0x1ce5ede1, 0x47b13c7a, 0xd2df599c, 0xf2733f55, 0x14ce7918, 0xc737bf73, 0xf7cdea53, 0xfdaa5b5f, 0x3d6f14df, 0x44db8678, 0xaff381ca, 0x68c43eb9, 0x24342c38, 0xa3405fc2, 0x1dc37216, 0xe2250cbc, 0x3c498b28, 0x0d9541ff, 0xa8017139, 0x0cb3de08, 0xb4e49cd8, 0x56c19064, 0xcb84617b, 0x32b670d5, 0x6c5c7448, 0xb85742d0];
  23790. // Transformations for decryption key expansion
  23791. const U1 = [0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927, 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45, 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb, 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381, 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf, 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66, 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28, 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012, 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec, 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e, 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd, 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7, 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89, 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b, 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815, 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f, 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa, 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8, 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36, 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c, 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742, 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea, 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4, 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e, 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360, 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502, 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87, 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd, 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3, 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621, 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f, 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55, 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26, 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844, 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba, 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480, 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce, 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67, 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929, 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713, 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed, 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f, 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3];
  23792. const U2 = [0x00000000, 0x0b0e090d, 0x161c121a, 0x1d121b17, 0x2c382434, 0x27362d39, 0x3a24362e, 0x312a3f23, 0x58704868, 0x537e4165, 0x4e6c5a72, 0x4562537f, 0x74486c5c, 0x7f466551, 0x62547e46, 0x695a774b, 0xb0e090d0, 0xbbee99dd, 0xa6fc82ca, 0xadf28bc7, 0x9cd8b4e4, 0x97d6bde9, 0x8ac4a6fe, 0x81caaff3, 0xe890d8b8, 0xe39ed1b5, 0xfe8ccaa2, 0xf582c3af, 0xc4a8fc8c, 0xcfa6f581, 0xd2b4ee96, 0xd9bae79b, 0x7bdb3bbb, 0x70d532b6, 0x6dc729a1, 0x66c920ac, 0x57e31f8f, 0x5ced1682, 0x41ff0d95, 0x4af10498, 0x23ab73d3, 0x28a57ade, 0x35b761c9, 0x3eb968c4, 0x0f9357e7, 0x049d5eea, 0x198f45fd, 0x12814cf0, 0xcb3bab6b, 0xc035a266, 0xdd27b971, 0xd629b07c, 0xe7038f5f, 0xec0d8652, 0xf11f9d45, 0xfa119448, 0x934be303, 0x9845ea0e, 0x8557f119, 0x8e59f814, 0xbf73c737, 0xb47dce3a, 0xa96fd52d, 0xa261dc20, 0xf6ad766d, 0xfda37f60, 0xe0b16477, 0xebbf6d7a, 0xda955259, 0xd19b5b54, 0xcc894043, 0xc787494e, 0xaedd3e05, 0xa5d33708, 0xb8c12c1f, 0xb3cf2512, 0x82e51a31, 0x89eb133c, 0x94f9082b, 0x9ff70126, 0x464de6bd, 0x4d43efb0, 0x5051f4a7, 0x5b5ffdaa, 0x6a75c289, 0x617bcb84, 0x7c69d093, 0x7767d99e, 0x1e3daed5, 0x1533a7d8, 0x0821bccf, 0x032fb5c2, 0x32058ae1, 0x390b83ec, 0x241998fb, 0x2f1791f6, 0x8d764dd6, 0x867844db, 0x9b6a5fcc, 0x906456c1, 0xa14e69e2, 0xaa4060ef, 0xb7527bf8, 0xbc5c72f5, 0xd50605be, 0xde080cb3, 0xc31a17a4, 0xc8141ea9, 0xf93e218a, 0xf2302887, 0xef223390, 0xe42c3a9d, 0x3d96dd06, 0x3698d40b, 0x2b8acf1c, 0x2084c611, 0x11aef932, 0x1aa0f03f, 0x07b2eb28, 0x0cbce225, 0x65e6956e, 0x6ee89c63, 0x73fa8774, 0x78f48e79, 0x49deb15a, 0x42d0b857, 0x5fc2a340, 0x54ccaa4d, 0xf741ecda, 0xfc4fe5d7, 0xe15dfec0, 0xea53f7cd, 0xdb79c8ee, 0xd077c1e3, 0xcd65daf4, 0xc66bd3f9, 0xaf31a4b2, 0xa43fadbf, 0xb92db6a8, 0xb223bfa5, 0x83098086, 0x8807898b, 0x9515929c, 0x9e1b9b91, 0x47a17c0a, 0x4caf7507, 0x51bd6e10, 0x5ab3671d, 0x6b99583e, 0x60975133, 0x7d854a24, 0x768b4329, 0x1fd13462, 0x14df3d6f, 0x09cd2678, 0x02c32f75, 0x33e91056, 0x38e7195b, 0x25f5024c, 0x2efb0b41, 0x8c9ad761, 0x8794de6c, 0x9a86c57b, 0x9188cc76, 0xa0a2f355, 0xabacfa58, 0xb6bee14f, 0xbdb0e842, 0xd4ea9f09, 0xdfe49604, 0xc2f68d13, 0xc9f8841e, 0xf8d2bb3d, 0xf3dcb230, 0xeecea927, 0xe5c0a02a, 0x3c7a47b1, 0x37744ebc, 0x2a6655ab, 0x21685ca6, 0x10426385, 0x1b4c6a88, 0x065e719f, 0x0d507892, 0x640a0fd9, 0x6f0406d4, 0x72161dc3, 0x791814ce, 0x48322bed, 0x433c22e0, 0x5e2e39f7, 0x552030fa, 0x01ec9ab7, 0x0ae293ba, 0x17f088ad, 0x1cfe81a0, 0x2dd4be83, 0x26dab78e, 0x3bc8ac99, 0x30c6a594, 0x599cd2df, 0x5292dbd2, 0x4f80c0c5, 0x448ec9c8, 0x75a4f6eb, 0x7eaaffe6, 0x63b8e4f1, 0x68b6edfc, 0xb10c0a67, 0xba02036a, 0xa710187d, 0xac1e1170, 0x9d342e53, 0x963a275e, 0x8b283c49, 0x80263544, 0xe97c420f, 0xe2724b02, 0xff605015, 0xf46e5918, 0xc544663b, 0xce4a6f36, 0xd3587421, 0xd8567d2c, 0x7a37a10c, 0x7139a801, 0x6c2bb316, 0x6725ba1b, 0x560f8538, 0x5d018c35, 0x40139722, 0x4b1d9e2f, 0x2247e964, 0x2949e069, 0x345bfb7e, 0x3f55f273, 0x0e7fcd50, 0x0571c45d, 0x1863df4a, 0x136dd647, 0xcad731dc, 0xc1d938d1, 0xdccb23c6, 0xd7c52acb, 0xe6ef15e8, 0xede11ce5, 0xf0f307f2, 0xfbfd0eff, 0x92a779b4, 0x99a970b9, 0x84bb6bae, 0x8fb562a3, 0xbe9f5d80, 0xb591548d, 0xa8834f9a, 0xa38d4697];
  23793. const U3 = [0x00000000, 0x0d0b0e09, 0x1a161c12, 0x171d121b, 0x342c3824, 0x3927362d, 0x2e3a2436, 0x23312a3f, 0x68587048, 0x65537e41, 0x724e6c5a, 0x7f456253, 0x5c74486c, 0x517f4665, 0x4662547e, 0x4b695a77, 0xd0b0e090, 0xddbbee99, 0xcaa6fc82, 0xc7adf28b, 0xe49cd8b4, 0xe997d6bd, 0xfe8ac4a6, 0xf381caaf, 0xb8e890d8, 0xb5e39ed1, 0xa2fe8cca, 0xaff582c3, 0x8cc4a8fc, 0x81cfa6f5, 0x96d2b4ee, 0x9bd9bae7, 0xbb7bdb3b, 0xb670d532, 0xa16dc729, 0xac66c920, 0x8f57e31f, 0x825ced16, 0x9541ff0d, 0x984af104, 0xd323ab73, 0xde28a57a, 0xc935b761, 0xc43eb968, 0xe70f9357, 0xea049d5e, 0xfd198f45, 0xf012814c, 0x6bcb3bab, 0x66c035a2, 0x71dd27b9, 0x7cd629b0, 0x5fe7038f, 0x52ec0d86, 0x45f11f9d, 0x48fa1194, 0x03934be3, 0x0e9845ea, 0x198557f1, 0x148e59f8, 0x37bf73c7, 0x3ab47dce, 0x2da96fd5, 0x20a261dc, 0x6df6ad76, 0x60fda37f, 0x77e0b164, 0x7aebbf6d, 0x59da9552, 0x54d19b5b, 0x43cc8940, 0x4ec78749, 0x05aedd3e, 0x08a5d337, 0x1fb8c12c, 0x12b3cf25, 0x3182e51a, 0x3c89eb13, 0x2b94f908, 0x269ff701, 0xbd464de6, 0xb04d43ef, 0xa75051f4, 0xaa5b5ffd, 0x896a75c2, 0x84617bcb, 0x937c69d0, 0x9e7767d9, 0xd51e3dae, 0xd81533a7, 0xcf0821bc, 0xc2032fb5, 0xe132058a, 0xec390b83, 0xfb241998, 0xf62f1791, 0xd68d764d, 0xdb867844, 0xcc9b6a5f, 0xc1906456, 0xe2a14e69, 0xefaa4060, 0xf8b7527b, 0xf5bc5c72, 0xbed50605, 0xb3de080c, 0xa4c31a17, 0xa9c8141e, 0x8af93e21, 0x87f23028, 0x90ef2233, 0x9de42c3a, 0x063d96dd, 0x0b3698d4, 0x1c2b8acf, 0x112084c6, 0x3211aef9, 0x3f1aa0f0, 0x2807b2eb, 0x250cbce2, 0x6e65e695, 0x636ee89c, 0x7473fa87, 0x7978f48e, 0x5a49deb1, 0x5742d0b8, 0x405fc2a3, 0x4d54ccaa, 0xdaf741ec, 0xd7fc4fe5, 0xc0e15dfe, 0xcdea53f7, 0xeedb79c8, 0xe3d077c1, 0xf4cd65da, 0xf9c66bd3, 0xb2af31a4, 0xbfa43fad, 0xa8b92db6, 0xa5b223bf, 0x86830980, 0x8b880789, 0x9c951592, 0x919e1b9b, 0x0a47a17c, 0x074caf75, 0x1051bd6e, 0x1d5ab367, 0x3e6b9958, 0x33609751, 0x247d854a, 0x29768b43, 0x621fd134, 0x6f14df3d, 0x7809cd26, 0x7502c32f, 0x5633e910, 0x5b38e719, 0x4c25f502, 0x412efb0b, 0x618c9ad7, 0x6c8794de, 0x7b9a86c5, 0x769188cc, 0x55a0a2f3, 0x58abacfa, 0x4fb6bee1, 0x42bdb0e8, 0x09d4ea9f, 0x04dfe496, 0x13c2f68d, 0x1ec9f884, 0x3df8d2bb, 0x30f3dcb2, 0x27eecea9, 0x2ae5c0a0, 0xb13c7a47, 0xbc37744e, 0xab2a6655, 0xa621685c, 0x85104263, 0x881b4c6a, 0x9f065e71, 0x920d5078, 0xd9640a0f, 0xd46f0406, 0xc372161d, 0xce791814, 0xed48322b, 0xe0433c22, 0xf75e2e39, 0xfa552030, 0xb701ec9a, 0xba0ae293, 0xad17f088, 0xa01cfe81, 0x832dd4be, 0x8e26dab7, 0x993bc8ac, 0x9430c6a5, 0xdf599cd2, 0xd25292db, 0xc54f80c0, 0xc8448ec9, 0xeb75a4f6, 0xe67eaaff, 0xf163b8e4, 0xfc68b6ed, 0x67b10c0a, 0x6aba0203, 0x7da71018, 0x70ac1e11, 0x539d342e, 0x5e963a27, 0x498b283c, 0x44802635, 0x0fe97c42, 0x02e2724b, 0x15ff6050, 0x18f46e59, 0x3bc54466, 0x36ce4a6f, 0x21d35874, 0x2cd8567d, 0x0c7a37a1, 0x017139a8, 0x166c2bb3, 0x1b6725ba, 0x38560f85, 0x355d018c, 0x22401397, 0x2f4b1d9e, 0x642247e9, 0x692949e0, 0x7e345bfb, 0x733f55f2, 0x500e7fcd, 0x5d0571c4, 0x4a1863df, 0x47136dd6, 0xdccad731, 0xd1c1d938, 0xc6dccb23, 0xcbd7c52a, 0xe8e6ef15, 0xe5ede11c, 0xf2f0f307, 0xfffbfd0e, 0xb492a779, 0xb999a970, 0xae84bb6b, 0xa38fb562, 0x80be9f5d, 0x8db59154, 0x9aa8834f, 0x97a38d46];
  23794. const U4 = [0x00000000, 0x090d0b0e, 0x121a161c, 0x1b171d12, 0x24342c38, 0x2d392736, 0x362e3a24, 0x3f23312a, 0x48685870, 0x4165537e, 0x5a724e6c, 0x537f4562, 0x6c5c7448, 0x65517f46, 0x7e466254, 0x774b695a, 0x90d0b0e0, 0x99ddbbee, 0x82caa6fc, 0x8bc7adf2, 0xb4e49cd8, 0xbde997d6, 0xa6fe8ac4, 0xaff381ca, 0xd8b8e890, 0xd1b5e39e, 0xcaa2fe8c, 0xc3aff582, 0xfc8cc4a8, 0xf581cfa6, 0xee96d2b4, 0xe79bd9ba, 0x3bbb7bdb, 0x32b670d5, 0x29a16dc7, 0x20ac66c9, 0x1f8f57e3, 0x16825ced, 0x0d9541ff, 0x04984af1, 0x73d323ab, 0x7ade28a5, 0x61c935b7, 0x68c43eb9, 0x57e70f93, 0x5eea049d, 0x45fd198f, 0x4cf01281, 0xab6bcb3b, 0xa266c035, 0xb971dd27, 0xb07cd629, 0x8f5fe703, 0x8652ec0d, 0x9d45f11f, 0x9448fa11, 0xe303934b, 0xea0e9845, 0xf1198557, 0xf8148e59, 0xc737bf73, 0xce3ab47d, 0xd52da96f, 0xdc20a261, 0x766df6ad, 0x7f60fda3, 0x6477e0b1, 0x6d7aebbf, 0x5259da95, 0x5b54d19b, 0x4043cc89, 0x494ec787, 0x3e05aedd, 0x3708a5d3, 0x2c1fb8c1, 0x2512b3cf, 0x1a3182e5, 0x133c89eb, 0x082b94f9, 0x01269ff7, 0xe6bd464d, 0xefb04d43, 0xf4a75051, 0xfdaa5b5f, 0xc2896a75, 0xcb84617b, 0xd0937c69, 0xd99e7767, 0xaed51e3d, 0xa7d81533, 0xbccf0821, 0xb5c2032f, 0x8ae13205, 0x83ec390b, 0x98fb2419, 0x91f62f17, 0x4dd68d76, 0x44db8678, 0x5fcc9b6a, 0x56c19064, 0x69e2a14e, 0x60efaa40, 0x7bf8b752, 0x72f5bc5c, 0x05bed506, 0x0cb3de08, 0x17a4c31a, 0x1ea9c814, 0x218af93e, 0x2887f230, 0x3390ef22, 0x3a9de42c, 0xdd063d96, 0xd40b3698, 0xcf1c2b8a, 0xc6112084, 0xf93211ae, 0xf03f1aa0, 0xeb2807b2, 0xe2250cbc, 0x956e65e6, 0x9c636ee8, 0x877473fa, 0x8e7978f4, 0xb15a49de, 0xb85742d0, 0xa3405fc2, 0xaa4d54cc, 0xecdaf741, 0xe5d7fc4f, 0xfec0e15d, 0xf7cdea53, 0xc8eedb79, 0xc1e3d077, 0xdaf4cd65, 0xd3f9c66b, 0xa4b2af31, 0xadbfa43f, 0xb6a8b92d, 0xbfa5b223, 0x80868309, 0x898b8807, 0x929c9515, 0x9b919e1b, 0x7c0a47a1, 0x75074caf, 0x6e1051bd, 0x671d5ab3, 0x583e6b99, 0x51336097, 0x4a247d85, 0x4329768b, 0x34621fd1, 0x3d6f14df, 0x267809cd, 0x2f7502c3, 0x105633e9, 0x195b38e7, 0x024c25f5, 0x0b412efb, 0xd7618c9a, 0xde6c8794, 0xc57b9a86, 0xcc769188, 0xf355a0a2, 0xfa58abac, 0xe14fb6be, 0xe842bdb0, 0x9f09d4ea, 0x9604dfe4, 0x8d13c2f6, 0x841ec9f8, 0xbb3df8d2, 0xb230f3dc, 0xa927eece, 0xa02ae5c0, 0x47b13c7a, 0x4ebc3774, 0x55ab2a66, 0x5ca62168, 0x63851042, 0x6a881b4c, 0x719f065e, 0x78920d50, 0x0fd9640a, 0x06d46f04, 0x1dc37216, 0x14ce7918, 0x2bed4832, 0x22e0433c, 0x39f75e2e, 0x30fa5520, 0x9ab701ec, 0x93ba0ae2, 0x88ad17f0, 0x81a01cfe, 0xbe832dd4, 0xb78e26da, 0xac993bc8, 0xa59430c6, 0xd2df599c, 0xdbd25292, 0xc0c54f80, 0xc9c8448e, 0xf6eb75a4, 0xffe67eaa, 0xe4f163b8, 0xedfc68b6, 0x0a67b10c, 0x036aba02, 0x187da710, 0x1170ac1e, 0x2e539d34, 0x275e963a, 0x3c498b28, 0x35448026, 0x420fe97c, 0x4b02e272, 0x5015ff60, 0x5918f46e, 0x663bc544, 0x6f36ce4a, 0x7421d358, 0x7d2cd856, 0xa10c7a37, 0xa8017139, 0xb3166c2b, 0xba1b6725, 0x8538560f, 0x8c355d01, 0x97224013, 0x9e2f4b1d, 0xe9642247, 0xe0692949, 0xfb7e345b, 0xf2733f55, 0xcd500e7f, 0xc45d0571, 0xdf4a1863, 0xd647136d, 0x31dccad7, 0x38d1c1d9, 0x23c6dccb, 0x2acbd7c5, 0x15e8e6ef, 0x1ce5ede1, 0x07f2f0f3, 0x0efffbfd, 0x79b492a7, 0x70b999a9, 0x6bae84bb, 0x62a38fb5, 0x5d80be9f, 0x548db591, 0x4f9aa883, 0x4697a38d];
  23795. function convertToInt32(bytes) {
  23796. const result = [];
  23797. for (let i = 0; i < bytes.length; i += 4) {
  23798. result.push((bytes[i] << 24) | (bytes[i + 1] << 16) | (bytes[i + 2] << 8) | bytes[i + 3]);
  23799. }
  23800. return result;
  23801. }
  23802. class AES {
  23803. get key() { return __classPrivateFieldGet$2(this, _AES_key, "f").slice(); }
  23804. constructor(key) {
  23805. _AES_key.set(this, void 0);
  23806. _AES_Kd.set(this, void 0);
  23807. _AES_Ke.set(this, void 0);
  23808. if (!(this instanceof AES)) {
  23809. throw Error('AES must be instanitated with `new`');
  23810. }
  23811. __classPrivateFieldSet$2(this, _AES_key, new Uint8Array(key), "f");
  23812. const rounds = numberOfRounds[this.key.length];
  23813. if (rounds == null) {
  23814. throw new TypeError('invalid key size (must be 16, 24 or 32 bytes)');
  23815. }
  23816. // encryption round keys
  23817. __classPrivateFieldSet$2(this, _AES_Ke, [], "f");
  23818. // decryption round keys
  23819. __classPrivateFieldSet$2(this, _AES_Kd, [], "f");
  23820. for (let i = 0; i <= rounds; i++) {
  23821. __classPrivateFieldGet$2(this, _AES_Ke, "f").push([0, 0, 0, 0]);
  23822. __classPrivateFieldGet$2(this, _AES_Kd, "f").push([0, 0, 0, 0]);
  23823. }
  23824. const roundKeyCount = (rounds + 1) * 4;
  23825. const KC = this.key.length / 4;
  23826. // convert the key into ints
  23827. const tk = convertToInt32(this.key);
  23828. // copy values into round key arrays
  23829. let index;
  23830. for (let i = 0; i < KC; i++) {
  23831. index = i >> 2;
  23832. __classPrivateFieldGet$2(this, _AES_Ke, "f")[index][i % 4] = tk[i];
  23833. __classPrivateFieldGet$2(this, _AES_Kd, "f")[rounds - index][i % 4] = tk[i];
  23834. }
  23835. // key expansion (fips-197 section 5.2)
  23836. let rconpointer = 0;
  23837. let t = KC, tt;
  23838. while (t < roundKeyCount) {
  23839. tt = tk[KC - 1];
  23840. tk[0] ^= ((S[(tt >> 16) & 0xFF] << 24) ^
  23841. (S[(tt >> 8) & 0xFF] << 16) ^
  23842. (S[tt & 0xFF] << 8) ^
  23843. S[(tt >> 24) & 0xFF] ^
  23844. (rcon[rconpointer] << 24));
  23845. rconpointer += 1;
  23846. // key expansion (for non-256 bit)
  23847. if (KC != 8) {
  23848. for (let i = 1; i < KC; i++) {
  23849. tk[i] ^= tk[i - 1];
  23850. }
  23851. // key expansion for 256-bit keys is "slightly different" (fips-197)
  23852. }
  23853. else {
  23854. for (let i = 1; i < (KC / 2); i++) {
  23855. tk[i] ^= tk[i - 1];
  23856. }
  23857. tt = tk[(KC / 2) - 1];
  23858. tk[KC / 2] ^= (S[tt & 0xFF] ^
  23859. (S[(tt >> 8) & 0xFF] << 8) ^
  23860. (S[(tt >> 16) & 0xFF] << 16) ^
  23861. (S[(tt >> 24) & 0xFF] << 24));
  23862. for (let i = (KC / 2) + 1; i < KC; i++) {
  23863. tk[i] ^= tk[i - 1];
  23864. }
  23865. }
  23866. // copy values into round key arrays
  23867. let i = 0, r, c;
  23868. while (i < KC && t < roundKeyCount) {
  23869. r = t >> 2;
  23870. c = t % 4;
  23871. __classPrivateFieldGet$2(this, _AES_Ke, "f")[r][c] = tk[i];
  23872. __classPrivateFieldGet$2(this, _AES_Kd, "f")[rounds - r][c] = tk[i++];
  23873. t++;
  23874. }
  23875. }
  23876. // inverse-cipher-ify the decryption round key (fips-197 section 5.3)
  23877. for (let r = 1; r < rounds; r++) {
  23878. for (let c = 0; c < 4; c++) {
  23879. tt = __classPrivateFieldGet$2(this, _AES_Kd, "f")[r][c];
  23880. __classPrivateFieldGet$2(this, _AES_Kd, "f")[r][c] = (U1[(tt >> 24) & 0xFF] ^
  23881. U2[(tt >> 16) & 0xFF] ^
  23882. U3[(tt >> 8) & 0xFF] ^
  23883. U4[tt & 0xFF]);
  23884. }
  23885. }
  23886. }
  23887. encrypt(plaintext) {
  23888. if (plaintext.length != 16) {
  23889. throw new TypeError('invalid plaintext size (must be 16 bytes)');
  23890. }
  23891. const rounds = __classPrivateFieldGet$2(this, _AES_Ke, "f").length - 1;
  23892. const a = [0, 0, 0, 0];
  23893. // convert plaintext to (ints ^ key)
  23894. let t = convertToInt32(plaintext);
  23895. for (let i = 0; i < 4; i++) {
  23896. t[i] ^= __classPrivateFieldGet$2(this, _AES_Ke, "f")[0][i];
  23897. }
  23898. // apply round transforms
  23899. for (let r = 1; r < rounds; r++) {
  23900. for (let i = 0; i < 4; i++) {
  23901. a[i] = (T1[(t[i] >> 24) & 0xff] ^
  23902. T2[(t[(i + 1) % 4] >> 16) & 0xff] ^
  23903. T3[(t[(i + 2) % 4] >> 8) & 0xff] ^
  23904. T4[t[(i + 3) % 4] & 0xff] ^
  23905. __classPrivateFieldGet$2(this, _AES_Ke, "f")[r][i]);
  23906. }
  23907. t = a.slice();
  23908. }
  23909. // the last round is special
  23910. const result = new Uint8Array(16);
  23911. let tt = 0;
  23912. for (let i = 0; i < 4; i++) {
  23913. tt = __classPrivateFieldGet$2(this, _AES_Ke, "f")[rounds][i];
  23914. result[4 * i] = (S[(t[i] >> 24) & 0xff] ^ (tt >> 24)) & 0xff;
  23915. result[4 * i + 1] = (S[(t[(i + 1) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff;
  23916. result[4 * i + 2] = (S[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff;
  23917. result[4 * i + 3] = (S[t[(i + 3) % 4] & 0xff] ^ tt) & 0xff;
  23918. }
  23919. return result;
  23920. }
  23921. decrypt(ciphertext) {
  23922. if (ciphertext.length != 16) {
  23923. throw new TypeError('invalid ciphertext size (must be 16 bytes)');
  23924. }
  23925. const rounds = __classPrivateFieldGet$2(this, _AES_Kd, "f").length - 1;
  23926. const a = [0, 0, 0, 0];
  23927. // convert plaintext to (ints ^ key)
  23928. let t = convertToInt32(ciphertext);
  23929. for (let i = 0; i < 4; i++) {
  23930. t[i] ^= __classPrivateFieldGet$2(this, _AES_Kd, "f")[0][i];
  23931. }
  23932. // apply round transforms
  23933. for (let r = 1; r < rounds; r++) {
  23934. for (let i = 0; i < 4; i++) {
  23935. a[i] = (T5[(t[i] >> 24) & 0xff] ^
  23936. T6[(t[(i + 3) % 4] >> 16) & 0xff] ^
  23937. T7[(t[(i + 2) % 4] >> 8) & 0xff] ^
  23938. T8[t[(i + 1) % 4] & 0xff] ^
  23939. __classPrivateFieldGet$2(this, _AES_Kd, "f")[r][i]);
  23940. }
  23941. t = a.slice();
  23942. }
  23943. // the last round is special
  23944. const result = new Uint8Array(16);
  23945. let tt = 0;
  23946. for (let i = 0; i < 4; i++) {
  23947. tt = __classPrivateFieldGet$2(this, _AES_Kd, "f")[rounds][i];
  23948. result[4 * i] = (Si[(t[i] >> 24) & 0xff] ^ (tt >> 24)) & 0xff;
  23949. result[4 * i + 1] = (Si[(t[(i + 3) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff;
  23950. result[4 * i + 2] = (Si[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff;
  23951. result[4 * i + 3] = (Si[t[(i + 1) % 4] & 0xff] ^ tt) & 0xff;
  23952. }
  23953. return result;
  23954. }
  23955. }
  23956. _AES_key = new WeakMap(), _AES_Kd = new WeakMap(), _AES_Ke = new WeakMap();
  23957. class ModeOfOperation {
  23958. constructor(name, key, cls) {
  23959. if (cls && !(this instanceof cls)) {
  23960. throw new Error(`${name} must be instantiated with "new"`);
  23961. }
  23962. Object.defineProperties(this, {
  23963. aes: { enumerable: true, value: new AES(key) },
  23964. name: { enumerable: true, value: name }
  23965. });
  23966. }
  23967. }
  23968. // Cipher Block Chaining
  23969. var __classPrivateFieldSet$1 = (__$G && __$G.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
  23970. if (kind === "m") throw new TypeError("Private method is not writable");
  23971. if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
  23972. if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  23973. return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
  23974. };
  23975. var __classPrivateFieldGet$1 = (__$G && __$G.__classPrivateFieldGet) || function (receiver, state, kind, f) {
  23976. if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
  23977. if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  23978. return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
  23979. };
  23980. var _CBC_iv, _CBC_lastBlock;
  23981. class CBC extends ModeOfOperation {
  23982. constructor(key, iv) {
  23983. super("ECC", key, CBC);
  23984. _CBC_iv.set(this, void 0);
  23985. _CBC_lastBlock.set(this, void 0);
  23986. if (iv) {
  23987. if (iv.length % 16) {
  23988. throw new TypeError("invalid iv size (must be 16 bytes)");
  23989. }
  23990. __classPrivateFieldSet$1(this, _CBC_iv, new Uint8Array(iv), "f");
  23991. }
  23992. else {
  23993. __classPrivateFieldSet$1(this, _CBC_iv, new Uint8Array(16), "f");
  23994. }
  23995. __classPrivateFieldSet$1(this, _CBC_lastBlock, this.iv, "f");
  23996. }
  23997. get iv() { return new Uint8Array(__classPrivateFieldGet$1(this, _CBC_iv, "f")); }
  23998. encrypt(plaintext) {
  23999. if (plaintext.length % 16) {
  24000. throw new TypeError("invalid plaintext size (must be multiple of 16 bytes)");
  24001. }
  24002. const ciphertext = new Uint8Array(plaintext.length);
  24003. for (let i = 0; i < plaintext.length; i += 16) {
  24004. for (let j = 0; j < 16; j++) {
  24005. __classPrivateFieldGet$1(this, _CBC_lastBlock, "f")[j] ^= plaintext[i + j];
  24006. }
  24007. __classPrivateFieldSet$1(this, _CBC_lastBlock, this.aes.encrypt(__classPrivateFieldGet$1(this, _CBC_lastBlock, "f")), "f");
  24008. ciphertext.set(__classPrivateFieldGet$1(this, _CBC_lastBlock, "f"), i);
  24009. }
  24010. return ciphertext;
  24011. }
  24012. decrypt(ciphertext) {
  24013. if (ciphertext.length % 16) {
  24014. throw new TypeError("invalid ciphertext size (must be multiple of 16 bytes)");
  24015. }
  24016. const plaintext = new Uint8Array(ciphertext.length);
  24017. for (let i = 0; i < ciphertext.length; i += 16) {
  24018. const block = this.aes.decrypt(ciphertext.subarray(i, i + 16));
  24019. for (let j = 0; j < 16; j++) {
  24020. plaintext[i + j] = block[j] ^ __classPrivateFieldGet$1(this, _CBC_lastBlock, "f")[j];
  24021. __classPrivateFieldGet$1(this, _CBC_lastBlock, "f")[j] = ciphertext[i + j];
  24022. }
  24023. }
  24024. return plaintext;
  24025. }
  24026. }
  24027. _CBC_iv = new WeakMap(), _CBC_lastBlock = new WeakMap();
  24028. // Counter Mode
  24029. var __classPrivateFieldSet = (__$G && __$G.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
  24030. if (kind === "m") throw new TypeError("Private method is not writable");
  24031. if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
  24032. if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  24033. return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
  24034. };
  24035. var __classPrivateFieldGet = (__$G && __$G.__classPrivateFieldGet) || function (receiver, state, kind, f) {
  24036. if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
  24037. if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  24038. return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
  24039. };
  24040. var _CTR_remaining, _CTR_remainingIndex, _CTR_counter;
  24041. class CTR extends ModeOfOperation {
  24042. constructor(key, initialValue) {
  24043. super("CTR", key, CTR);
  24044. // Remaining bytes for the one-time pad
  24045. _CTR_remaining.set(this, void 0);
  24046. _CTR_remainingIndex.set(this, void 0);
  24047. // The current counter
  24048. _CTR_counter.set(this, void 0);
  24049. __classPrivateFieldSet(this, _CTR_counter, new Uint8Array(16), "f");
  24050. __classPrivateFieldGet(this, _CTR_counter, "f").fill(0);
  24051. __classPrivateFieldSet(this, _CTR_remaining, __classPrivateFieldGet(this, _CTR_counter, "f"), "f"); // This will be discarded immediately
  24052. __classPrivateFieldSet(this, _CTR_remainingIndex, 16, "f");
  24053. if (initialValue == null) {
  24054. initialValue = 1;
  24055. }
  24056. if (typeof (initialValue) === "number") {
  24057. this.setCounterValue(initialValue);
  24058. }
  24059. else {
  24060. this.setCounterBytes(initialValue);
  24061. }
  24062. }
  24063. get counter() { return new Uint8Array(__classPrivateFieldGet(this, _CTR_counter, "f")); }
  24064. setCounterValue(value) {
  24065. if (!Number.isInteger(value) || value < 0 || value > Number.MAX_SAFE_INTEGER) {
  24066. throw new TypeError("invalid counter initial integer value");
  24067. }
  24068. for (let index = 15; index >= 0; --index) {
  24069. __classPrivateFieldGet(this, _CTR_counter, "f")[index] = value % 256;
  24070. value = Math.floor(value / 256);
  24071. }
  24072. }
  24073. setCounterBytes(value) {
  24074. if (value.length !== 16) {
  24075. throw new TypeError("invalid counter initial Uint8Array value length");
  24076. }
  24077. __classPrivateFieldGet(this, _CTR_counter, "f").set(value);
  24078. }
  24079. increment() {
  24080. for (let i = 15; i >= 0; i--) {
  24081. if (__classPrivateFieldGet(this, _CTR_counter, "f")[i] === 255) {
  24082. __classPrivateFieldGet(this, _CTR_counter, "f")[i] = 0;
  24083. }
  24084. else {
  24085. __classPrivateFieldGet(this, _CTR_counter, "f")[i]++;
  24086. break;
  24087. }
  24088. }
  24089. }
  24090. encrypt(plaintext) {
  24091. var _a, _b;
  24092. const crypttext = new Uint8Array(plaintext);
  24093. for (let i = 0; i < crypttext.length; i++) {
  24094. if (__classPrivateFieldGet(this, _CTR_remainingIndex, "f") === 16) {
  24095. __classPrivateFieldSet(this, _CTR_remaining, this.aes.encrypt(__classPrivateFieldGet(this, _CTR_counter, "f")), "f");
  24096. __classPrivateFieldSet(this, _CTR_remainingIndex, 0, "f");
  24097. this.increment();
  24098. }
  24099. crypttext[i] ^= __classPrivateFieldGet(this, _CTR_remaining, "f")[__classPrivateFieldSet(this, _CTR_remainingIndex, (_b = __classPrivateFieldGet(this, _CTR_remainingIndex, "f"), _a = _b++, _b), "f"), _a];
  24100. }
  24101. return crypttext;
  24102. }
  24103. decrypt(ciphertext) {
  24104. return this.encrypt(ciphertext);
  24105. }
  24106. }
  24107. _CTR_remaining = new WeakMap(), _CTR_remainingIndex = new WeakMap(), _CTR_counter = new WeakMap();
  24108. function pkcs7Strip(data) {
  24109. if (data.length < 16) {
  24110. throw new TypeError('PKCS#7 invalid length');
  24111. }
  24112. const padder = data[data.length - 1];
  24113. if (padder > 16) {
  24114. throw new TypeError('PKCS#7 padding byte out of range');
  24115. }
  24116. const length = data.length - padder;
  24117. for (let i = 0; i < padder; i++) {
  24118. if (data[length + i] !== padder) {
  24119. throw new TypeError('PKCS#7 invalid padding byte');
  24120. }
  24121. }
  24122. return new Uint8Array(data.subarray(0, length));
  24123. }
  24124. /**
  24125. * @_ignore
  24126. */
  24127. function looseArrayify(hexString) {
  24128. if (typeof (hexString) === "string" && !hexString.startsWith("0x")) {
  24129. hexString = "0x" + hexString;
  24130. }
  24131. return getBytesCopy(hexString);
  24132. }
  24133. function zpad$1(value, length) {
  24134. value = String(value);
  24135. while (value.length < length) {
  24136. value = '0' + value;
  24137. }
  24138. return value;
  24139. }
  24140. function getPassword(password) {
  24141. if (typeof (password) === 'string') {
  24142. return toUtf8Bytes(password, "NFKC");
  24143. }
  24144. return getBytesCopy(password);
  24145. }
  24146. function spelunk(object, _path) {
  24147. const match = _path.match(/^([a-z0-9$_.-]*)(:([a-z]+))?(!)?$/i);
  24148. assertArgument(match != null, "invalid path", "path", _path);
  24149. const path = match[1];
  24150. const type = match[3];
  24151. const reqd = (match[4] === "!");
  24152. let cur = object;
  24153. for (const comp of path.toLowerCase().split('.')) {
  24154. // Search for a child object with a case-insensitive matching key
  24155. if (Array.isArray(cur)) {
  24156. if (!comp.match(/^[0-9]+$/)) {
  24157. break;
  24158. }
  24159. cur = cur[parseInt(comp)];
  24160. }
  24161. else if (typeof (cur) === "object") {
  24162. let found = null;
  24163. for (const key in cur) {
  24164. if (key.toLowerCase() === comp) {
  24165. found = cur[key];
  24166. break;
  24167. }
  24168. }
  24169. cur = found;
  24170. }
  24171. else {
  24172. cur = null;
  24173. }
  24174. if (cur == null) {
  24175. break;
  24176. }
  24177. }
  24178. assertArgument(!reqd || cur != null, "missing required value", "path", path);
  24179. if (type && cur != null) {
  24180. if (type === "int") {
  24181. if (typeof (cur) === "string" && cur.match(/^-?[0-9]+$/)) {
  24182. return parseInt(cur);
  24183. }
  24184. else if (Number.isSafeInteger(cur)) {
  24185. return cur;
  24186. }
  24187. }
  24188. if (type === "number") {
  24189. if (typeof (cur) === "string" && cur.match(/^-?[0-9.]*$/)) {
  24190. return parseFloat(cur);
  24191. }
  24192. }
  24193. if (type === "data") {
  24194. if (typeof (cur) === "string") {
  24195. return looseArrayify(cur);
  24196. }
  24197. }
  24198. if (type === "array" && Array.isArray(cur)) {
  24199. return cur;
  24200. }
  24201. if (type === typeof (cur)) {
  24202. return cur;
  24203. }
  24204. assertArgument(false, `wrong type found for ${type} `, "path", path);
  24205. }
  24206. return cur;
  24207. }
  24208. /*
  24209. export function follow(object: any, path: string): null | string {
  24210. let currentChild = object;
  24211. for (const comp of path.toLowerCase().split('/')) {
  24212. // Search for a child object with a case-insensitive matching key
  24213. let matchingChild = null;
  24214. for (const key in currentChild) {
  24215. if (key.toLowerCase() === comp) {
  24216. matchingChild = currentChild[key];
  24217. break;
  24218. }
  24219. }
  24220. if (matchingChild === null) { return null; }
  24221. currentChild = matchingChild;
  24222. }
  24223. return currentChild;
  24224. }
  24225. // "path/to/something:type!"
  24226. export function followRequired(data: any, path: string): string {
  24227. const value = follow(data, path);
  24228. if (value != null) { return value; }
  24229. return logger.throwArgumentError("invalid value", `data:${ path }`,
  24230. JSON.stringify(data));
  24231. }
  24232. */
  24233. // See: https://www.ietf.org/rfc/rfc4122.txt (Section 4.4)
  24234. /*
  24235. export function uuidV4(randomBytes: BytesLike): string {
  24236. const bytes = getBytes(randomBytes, "randomBytes");
  24237. // Section: 4.1.3:
  24238. // - time_hi_and_version[12:16] = 0b0100
  24239. bytes[6] = (bytes[6] & 0x0f) | 0x40;
  24240. // Section 4.4
  24241. // - clock_seq_hi_and_reserved[6] = 0b0
  24242. // - clock_seq_hi_and_reserved[7] = 0b1
  24243. bytes[8] = (bytes[8] & 0x3f) | 0x80;
  24244. const value = hexlify(bytes);
  24245. return [
  24246. value.substring(2, 10),
  24247. value.substring(10, 14),
  24248. value.substring(14, 18),
  24249. value.substring(18, 22),
  24250. value.substring(22, 34),
  24251. ].join("-");
  24252. }
  24253. */
  24254. /**
  24255. * The JSON Wallet formats allow a simple way to store the private
  24256. * keys needed in Ethereum along with related information and allows
  24257. * for extensible forms of encryption.
  24258. *
  24259. * These utilities facilitate decrypting and encrypting the most common
  24260. * JSON Wallet formats.
  24261. *
  24262. * @_subsection: api/wallet:JSON Wallets [json-wallets]
  24263. */
  24264. const defaultPath$1 = "m/44'/60'/0'/0/0";
  24265. /**
  24266. * Returns true if %%json%% is a valid JSON Keystore Wallet.
  24267. */
  24268. function isKeystoreJson(json) {
  24269. try {
  24270. const data = JSON.parse(json);
  24271. const version = ((data.version != null) ? parseInt(data.version) : 0);
  24272. if (version === 3) {
  24273. return true;
  24274. }
  24275. }
  24276. catch (error) { }
  24277. return false;
  24278. }
  24279. function decrypt(data, key, ciphertext) {
  24280. const cipher = spelunk(data, "crypto.cipher:string");
  24281. if (cipher === "aes-128-ctr") {
  24282. const iv = spelunk(data, "crypto.cipherparams.iv:data!");
  24283. const aesCtr = new CTR(key, iv);
  24284. return hexlify(aesCtr.decrypt(ciphertext));
  24285. }
  24286. assert(false, "unsupported cipher", "UNSUPPORTED_OPERATION", {
  24287. operation: "decrypt"
  24288. });
  24289. }
  24290. function getAccount(data, _key) {
  24291. const key = getBytes(_key);
  24292. const ciphertext = spelunk(data, "crypto.ciphertext:data!");
  24293. const computedMAC = hexlify(keccak256(concat([key.slice(16, 32), ciphertext]))).substring(2);
  24294. assertArgument(computedMAC === spelunk(data, "crypto.mac:string!").toLowerCase(), "incorrect password", "password", "[ REDACTED ]");
  24295. const privateKey = decrypt(data, key.slice(0, 16), ciphertext);
  24296. const address = computeAddress(privateKey);
  24297. if (data.address) {
  24298. let check = data.address.toLowerCase();
  24299. if (!check.startsWith("0x")) {
  24300. check = "0x" + check;
  24301. }
  24302. assertArgument(getAddress(check) === address, "keystore address/privateKey mismatch", "address", data.address);
  24303. }
  24304. const account = { address, privateKey };
  24305. // Version 0.1 x-ethers metadata must contain an encrypted mnemonic phrase
  24306. const version = spelunk(data, "x-ethers.version:string");
  24307. if (version === "0.1") {
  24308. const mnemonicKey = key.slice(32, 64);
  24309. const mnemonicCiphertext = spelunk(data, "x-ethers.mnemonicCiphertext:data!");
  24310. const mnemonicIv = spelunk(data, "x-ethers.mnemonicCounter:data!");
  24311. const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv);
  24312. account.mnemonic = {
  24313. path: (spelunk(data, "x-ethers.path:string") || defaultPath$1),
  24314. locale: (spelunk(data, "x-ethers.locale:string") || "en"),
  24315. entropy: hexlify(getBytes(mnemonicAesCtr.decrypt(mnemonicCiphertext)))
  24316. };
  24317. }
  24318. return account;
  24319. }
  24320. function getDecryptKdfParams(data) {
  24321. const kdf = spelunk(data, "crypto.kdf:string");
  24322. if (kdf && typeof (kdf) === "string") {
  24323. if (kdf.toLowerCase() === "scrypt") {
  24324. const salt = spelunk(data, "crypto.kdfparams.salt:data!");
  24325. const N = spelunk(data, "crypto.kdfparams.n:int!");
  24326. const r = spelunk(data, "crypto.kdfparams.r:int!");
  24327. const p = spelunk(data, "crypto.kdfparams.p:int!");
  24328. // Make sure N is a power of 2
  24329. assertArgument(N > 0 && (N & (N - 1)) === 0, "invalid kdf.N", "kdf.N", N);
  24330. assertArgument(r > 0 && p > 0, "invalid kdf", "kdf", kdf);
  24331. const dkLen = spelunk(data, "crypto.kdfparams.dklen:int!");
  24332. assertArgument(dkLen === 32, "invalid kdf.dklen", "kdf.dflen", dkLen);
  24333. return { name: "scrypt", salt, N, r, p, dkLen: 64 };
  24334. }
  24335. else if (kdf.toLowerCase() === "pbkdf2") {
  24336. const salt = spelunk(data, "crypto.kdfparams.salt:data!");
  24337. const prf = spelunk(data, "crypto.kdfparams.prf:string!");
  24338. const algorithm = prf.split("-").pop();
  24339. assertArgument(algorithm === "sha256" || algorithm === "sha512", "invalid kdf.pdf", "kdf.pdf", prf);
  24340. const count = spelunk(data, "crypto.kdfparams.c:int!");
  24341. const dkLen = spelunk(data, "crypto.kdfparams.dklen:int!");
  24342. assertArgument(dkLen === 32, "invalid kdf.dklen", "kdf.dklen", dkLen);
  24343. return { name: "pbkdf2", salt, count, dkLen, algorithm };
  24344. }
  24345. }
  24346. assertArgument(false, "unsupported key-derivation function", "kdf", kdf);
  24347. }
  24348. /**
  24349. * Returns the account details for the JSON Keystore Wallet %%json%%
  24350. * using %%password%%.
  24351. *
  24352. * It is preferred to use the [async version](decryptKeystoreJson)
  24353. * instead, which allows a [[ProgressCallback]] to keep the user informed
  24354. * as to the decryption status.
  24355. *
  24356. * This method will block the event loop (freezing all UI) until decryption
  24357. * is complete, which can take quite some time, depending on the wallet
  24358. * paramters and platform.
  24359. */
  24360. function decryptKeystoreJsonSync(json, _password) {
  24361. const data = JSON.parse(json);
  24362. const password = getPassword(_password);
  24363. const params = getDecryptKdfParams(data);
  24364. if (params.name === "pbkdf2") {
  24365. const { salt, count, dkLen, algorithm } = params;
  24366. const key = pbkdf2(password, salt, count, dkLen, algorithm);
  24367. return getAccount(data, key);
  24368. }
  24369. assert(params.name === "scrypt", "cannot be reached", "UNKNOWN_ERROR", { params });
  24370. const { salt, N, r, p, dkLen } = params;
  24371. const key = scryptSync(password, salt, N, r, p, dkLen);
  24372. return getAccount(data, key);
  24373. }
  24374. function stall$1(duration) {
  24375. return new Promise((resolve) => { setTimeout(() => { resolve(); }, duration); });
  24376. }
  24377. /**
  24378. * Resolves to the decrypted JSON Keystore Wallet %%json%% using the
  24379. * %%password%%.
  24380. *
  24381. * If provided, %%progress%% will be called periodically during the
  24382. * decrpytion to provide feedback, and if the function returns
  24383. * ``false`` will halt decryption.
  24384. *
  24385. * The %%progressCallback%% will **always** receive ``0`` before
  24386. * decryption begins and ``1`` when complete.
  24387. */
  24388. async function decryptKeystoreJson(json, _password, progress) {
  24389. const data = JSON.parse(json);
  24390. const password = getPassword(_password);
  24391. const params = getDecryptKdfParams(data);
  24392. if (params.name === "pbkdf2") {
  24393. if (progress) {
  24394. progress(0);
  24395. await stall$1(0);
  24396. }
  24397. const { salt, count, dkLen, algorithm } = params;
  24398. const key = pbkdf2(password, salt, count, dkLen, algorithm);
  24399. if (progress) {
  24400. progress(1);
  24401. await stall$1(0);
  24402. }
  24403. return getAccount(data, key);
  24404. }
  24405. assert(params.name === "scrypt", "cannot be reached", "UNKNOWN_ERROR", { params });
  24406. const { salt, N, r, p, dkLen } = params;
  24407. const key = await scrypt(password, salt, N, r, p, dkLen, progress);
  24408. return getAccount(data, key);
  24409. }
  24410. function getEncryptKdfParams(options) {
  24411. // Check/generate the salt
  24412. const salt = (options.salt != null) ? getBytes(options.salt, "options.salt") : randomBytes(32);
  24413. // Override the scrypt password-based key derivation function parameters
  24414. let N = (1 << 17), r = 8, p = 1;
  24415. if (options.scrypt) {
  24416. if (options.scrypt.N) {
  24417. N = options.scrypt.N;
  24418. }
  24419. if (options.scrypt.r) {
  24420. r = options.scrypt.r;
  24421. }
  24422. if (options.scrypt.p) {
  24423. p = options.scrypt.p;
  24424. }
  24425. }
  24426. assertArgument(typeof (N) === "number" && N > 0 && Number.isSafeInteger(N) && (BigInt(N) & BigInt(N - 1)) === BigInt(0), "invalid scrypt N parameter", "options.N", N);
  24427. assertArgument(typeof (r) === "number" && r > 0 && Number.isSafeInteger(r), "invalid scrypt r parameter", "options.r", r);
  24428. assertArgument(typeof (p) === "number" && p > 0 && Number.isSafeInteger(p), "invalid scrypt p parameter", "options.p", p);
  24429. return { name: "scrypt", dkLen: 32, salt, N, r, p };
  24430. }
  24431. function _encryptKeystore(key, kdf, account, options) {
  24432. const privateKey = getBytes(account.privateKey, "privateKey");
  24433. // Override initialization vector
  24434. const iv = (options.iv != null) ? getBytes(options.iv, "options.iv") : randomBytes(16);
  24435. assertArgument(iv.length === 16, "invalid options.iv length", "options.iv", options.iv);
  24436. // Override the uuid
  24437. const uuidRandom = (options.uuid != null) ? getBytes(options.uuid, "options.uuid") : randomBytes(16);
  24438. assertArgument(uuidRandom.length === 16, "invalid options.uuid length", "options.uuid", options.iv);
  24439. // This will be used to encrypt the wallet (as per Web3 secret storage)
  24440. // - 32 bytes As normal for the Web3 secret storage (derivedKey, macPrefix)
  24441. // - 32 bytes AES key to encrypt mnemonic with (required here to be Ethers Wallet)
  24442. const derivedKey = key.slice(0, 16);
  24443. const macPrefix = key.slice(16, 32);
  24444. // Encrypt the private key
  24445. const aesCtr = new CTR(derivedKey, iv);
  24446. const ciphertext = getBytes(aesCtr.encrypt(privateKey));
  24447. // Compute the message authentication code, used to check the password
  24448. const mac = keccak256(concat([macPrefix, ciphertext]));
  24449. // See: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition
  24450. const data = {
  24451. address: account.address.substring(2).toLowerCase(),
  24452. id: uuidV4(uuidRandom),
  24453. version: 3,
  24454. Crypto: {
  24455. cipher: "aes-128-ctr",
  24456. cipherparams: {
  24457. iv: hexlify(iv).substring(2),
  24458. },
  24459. ciphertext: hexlify(ciphertext).substring(2),
  24460. kdf: "scrypt",
  24461. kdfparams: {
  24462. salt: hexlify(kdf.salt).substring(2),
  24463. n: kdf.N,
  24464. dklen: 32,
  24465. p: kdf.p,
  24466. r: kdf.r
  24467. },
  24468. mac: mac.substring(2)
  24469. }
  24470. };
  24471. // If we have a mnemonic, encrypt it into the JSON wallet
  24472. if (account.mnemonic) {
  24473. const client = (options.client != null) ? options.client : `ethers/${version}`;
  24474. const path = account.mnemonic.path || defaultPath$1;
  24475. const locale = account.mnemonic.locale || "en";
  24476. const mnemonicKey = key.slice(32, 64);
  24477. const entropy = getBytes(account.mnemonic.entropy, "account.mnemonic.entropy");
  24478. const mnemonicIv = randomBytes(16);
  24479. const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv);
  24480. const mnemonicCiphertext = getBytes(mnemonicAesCtr.encrypt(entropy));
  24481. const now = new Date();
  24482. const timestamp = (now.getUTCFullYear() + "-" +
  24483. zpad$1(now.getUTCMonth() + 1, 2) + "-" +
  24484. zpad$1(now.getUTCDate(), 2) + "T" +
  24485. zpad$1(now.getUTCHours(), 2) + "-" +
  24486. zpad$1(now.getUTCMinutes(), 2) + "-" +
  24487. zpad$1(now.getUTCSeconds(), 2) + ".0Z");
  24488. const gethFilename = ("UTC--" + timestamp + "--" + data.address);
  24489. data["x-ethers"] = {
  24490. client, gethFilename, path, locale,
  24491. mnemonicCounter: hexlify(mnemonicIv).substring(2),
  24492. mnemonicCiphertext: hexlify(mnemonicCiphertext).substring(2),
  24493. version: "0.1"
  24494. };
  24495. }
  24496. return JSON.stringify(data);
  24497. }
  24498. /**
  24499. * Return the JSON Keystore Wallet for %%account%% encrypted with
  24500. * %%password%%.
  24501. *
  24502. * The %%options%% can be used to tune the password-based key
  24503. * derivation function parameters, explicitly set the random values
  24504. * used. Any provided [[ProgressCallback]] is ignord.
  24505. */
  24506. function encryptKeystoreJsonSync(account, password, options) {
  24507. if (options == null) {
  24508. options = {};
  24509. }
  24510. const passwordBytes = getPassword(password);
  24511. const kdf = getEncryptKdfParams(options);
  24512. const key = scryptSync(passwordBytes, kdf.salt, kdf.N, kdf.r, kdf.p, 64);
  24513. return _encryptKeystore(getBytes(key), kdf, account, options);
  24514. }
  24515. /**
  24516. * Resolved to the JSON Keystore Wallet for %%account%% encrypted
  24517. * with %%password%%.
  24518. *
  24519. * The %%options%% can be used to tune the password-based key
  24520. * derivation function parameters, explicitly set the random values
  24521. * used and provide a [[ProgressCallback]] to receive periodic updates
  24522. * on the completion status..
  24523. */
  24524. async function encryptKeystoreJson(account, password, options) {
  24525. if (options == null) {
  24526. options = {};
  24527. }
  24528. const passwordBytes = getPassword(password);
  24529. const kdf = getEncryptKdfParams(options);
  24530. const key = await scrypt(passwordBytes, kdf.salt, kdf.N, kdf.r, kdf.p, 64, options.progressCallback);
  24531. return _encryptKeystore(getBytes(key), kdf, account, options);
  24532. }
  24533. /**
  24534. * Explain HD Wallets..
  24535. *
  24536. * @_subsection: api/wallet:HD Wallets [hd-wallets]
  24537. */
  24538. /**
  24539. * The default derivation path for Ethereum HD Nodes. (i.e. ``"m/44'/60'/0'/0/0"``)
  24540. */
  24541. const defaultPath = "m/44'/60'/0'/0/0";
  24542. // "Bitcoin seed"
  24543. const MasterSecret = new Uint8Array([66, 105, 116, 99, 111, 105, 110, 32, 115, 101, 101, 100]);
  24544. const HardenedBit = 0x80000000;
  24545. const N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");
  24546. const Nibbles = "0123456789abcdef";
  24547. function zpad(value, length) {
  24548. let result = "";
  24549. while (value) {
  24550. result = Nibbles[value % 16] + result;
  24551. value = Math.trunc(value / 16);
  24552. }
  24553. while (result.length < length * 2) {
  24554. result = "0" + result;
  24555. }
  24556. return "0x" + result;
  24557. }
  24558. function encodeBase58Check(_value) {
  24559. const value = getBytes(_value);
  24560. const check = dataSlice(sha256(sha256(value)), 0, 4);
  24561. const bytes = concat([value, check]);
  24562. return encodeBase58(bytes);
  24563. }
  24564. const _guard = {};
  24565. function ser_I(index, chainCode, publicKey, privateKey) {
  24566. const data = new Uint8Array(37);
  24567. if (index & HardenedBit) {
  24568. assert(privateKey != null, "cannot derive child of neutered node", "UNSUPPORTED_OPERATION", {
  24569. operation: "deriveChild"
  24570. });
  24571. // Data = 0x00 || ser_256(k_par)
  24572. data.set(getBytes(privateKey), 1);
  24573. }
  24574. else {
  24575. // Data = ser_p(point(k_par))
  24576. data.set(getBytes(publicKey));
  24577. }
  24578. // Data += ser_32(i)
  24579. for (let i = 24; i >= 0; i -= 8) {
  24580. data[33 + (i >> 3)] = ((index >> (24 - i)) & 0xff);
  24581. }
  24582. const I = getBytes(computeHmac("sha512", chainCode, data));
  24583. return { IL: I.slice(0, 32), IR: I.slice(32) };
  24584. }
  24585. function derivePath(node, path) {
  24586. const components = path.split("/");
  24587. assertArgument(components.length > 0, "invalid path", "path", path);
  24588. if (components[0] === "m") {
  24589. assertArgument(node.depth === 0, `cannot derive root path (i.e. path starting with "m/") for a node at non-zero depth ${node.depth}`, "path", path);
  24590. components.shift();
  24591. }
  24592. let result = node;
  24593. for (let i = 0; i < components.length; i++) {
  24594. const component = components[i];
  24595. if (component.match(/^[0-9]+'$/)) {
  24596. const index = parseInt(component.substring(0, component.length - 1));
  24597. assertArgument(index < HardenedBit, "invalid path index", `path[${i}]`, component);
  24598. result = result.deriveChild(HardenedBit + index);
  24599. }
  24600. else if (component.match(/^[0-9]+$/)) {
  24601. const index = parseInt(component);
  24602. assertArgument(index < HardenedBit, "invalid path index", `path[${i}]`, component);
  24603. result = result.deriveChild(index);
  24604. }
  24605. else {
  24606. assertArgument(false, "invalid path component", `path[${i}]`, component);
  24607. }
  24608. }
  24609. return result;
  24610. }
  24611. /**
  24612. * An **HDNodeWallet** is a [[Signer]] backed by the private key derived
  24613. * from an HD Node using the [[link-bip-32]] stantard.
  24614. *
  24615. * An HD Node forms a hierarchal structure with each HD Node having a
  24616. * private key and the ability to derive child HD Nodes, defined by
  24617. * a path indicating the index of each child.
  24618. */
  24619. class HDNodeWallet extends BaseWallet {
  24620. /**
  24621. * The compressed public key.
  24622. */
  24623. publicKey;
  24624. /**
  24625. * The fingerprint.
  24626. *
  24627. * A fingerprint allows quick qay to detect parent and child nodes,
  24628. * but developers should be prepared to deal with collisions as it
  24629. * is only 4 bytes.
  24630. */
  24631. fingerprint;
  24632. /**
  24633. * The parent fingerprint.
  24634. */
  24635. parentFingerprint;
  24636. /**
  24637. * The mnemonic used to create this HD Node, if available.
  24638. *
  24639. * Sources such as extended keys do not encode the mnemonic, in
  24640. * which case this will be ``null``.
  24641. */
  24642. mnemonic;
  24643. /**
  24644. * The chaincode, which is effectively a public key used
  24645. * to derive children.
  24646. */
  24647. chainCode;
  24648. /**
  24649. * The derivation path of this wallet.
  24650. *
  24651. * Since extended keys do not provide full path details, this
  24652. * may be ``null``, if instantiated from a source that does not
  24653. * encode it.
  24654. */
  24655. path;
  24656. /**
  24657. * The child index of this wallet. Values over ``2 *\* 31`` indicate
  24658. * the node is hardened.
  24659. */
  24660. index;
  24661. /**
  24662. * The depth of this wallet, which is the number of components
  24663. * in its path.
  24664. */
  24665. depth;
  24666. /**
  24667. * @private
  24668. */
  24669. constructor(guard, signingKey, parentFingerprint, chainCode, path, index, depth, mnemonic, provider) {
  24670. super(signingKey, provider);
  24671. assertPrivate(guard, _guard, "HDNodeWallet");
  24672. defineProperties(this, { publicKey: signingKey.compressedPublicKey });
  24673. const fingerprint = dataSlice(ripemd160(sha256(this.publicKey)), 0, 4);
  24674. defineProperties(this, {
  24675. parentFingerprint, fingerprint,
  24676. chainCode, path, index, depth
  24677. });
  24678. defineProperties(this, { mnemonic });
  24679. }
  24680. connect(provider) {
  24681. return new HDNodeWallet(_guard, this.signingKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.mnemonic, provider);
  24682. }
  24683. #account() {
  24684. const account = { address: this.address, privateKey: this.privateKey };
  24685. const m = this.mnemonic;
  24686. if (this.path && m && m.wordlist.locale === "en" && m.password === "") {
  24687. account.mnemonic = {
  24688. path: this.path,
  24689. locale: "en",
  24690. entropy: m.entropy
  24691. };
  24692. }
  24693. return account;
  24694. }
  24695. /**
  24696. * Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with
  24697. * %%password%%.
  24698. *
  24699. * If %%progressCallback%% is specified, it will receive periodic
  24700. * updates as the encryption process progreses.
  24701. */
  24702. async encrypt(password, progressCallback) {
  24703. return await encryptKeystoreJson(this.#account(), password, { progressCallback });
  24704. }
  24705. /**
  24706. * Returns a [JSON Keystore Wallet](json-wallets) encryped with
  24707. * %%password%%.
  24708. *
  24709. * It is preferred to use the [async version](encrypt) instead,
  24710. * which allows a [[ProgressCallback]] to keep the user informed.
  24711. *
  24712. * This method will block the event loop (freezing all UI) until
  24713. * it is complete, which may be a non-trivial duration.
  24714. */
  24715. encryptSync(password) {
  24716. return encryptKeystoreJsonSync(this.#account(), password);
  24717. }
  24718. /**
  24719. * The extended key.
  24720. *
  24721. * This key will begin with the prefix ``xpriv`` and can be used to
  24722. * reconstruct this HD Node to derive its children.
  24723. */
  24724. get extendedKey() {
  24725. // We only support the mainnet values for now, but if anyone needs
  24726. // testnet values, let me know. I believe current sentiment is that
  24727. // we should always use mainnet, and use BIP-44 to derive the network
  24728. // - Mainnet: public=0x0488B21E, private=0x0488ADE4
  24729. // - Testnet: public=0x043587CF, private=0x04358394
  24730. assert(this.depth < 256, "Depth too deep", "UNSUPPORTED_OPERATION", { operation: "extendedKey" });
  24731. return encodeBase58Check(concat([
  24732. "0x0488ADE4", zpad(this.depth, 1), this.parentFingerprint,
  24733. zpad(this.index, 4), this.chainCode,
  24734. concat(["0x00", this.privateKey])
  24735. ]));
  24736. }
  24737. /**
  24738. * Returns true if this wallet has a path, providing a Type Guard
  24739. * that the path is non-null.
  24740. */
  24741. hasPath() { return (this.path != null); }
  24742. /**
  24743. * Returns a neutered HD Node, which removes the private details
  24744. * of an HD Node.
  24745. *
  24746. * A neutered node has no private key, but can be used to derive
  24747. * child addresses and other public data about the HD Node.
  24748. */
  24749. neuter() {
  24750. return new HDNodeVoidWallet(_guard, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.provider);
  24751. }
  24752. /**
  24753. * Return the child for %%index%%.
  24754. */
  24755. deriveChild(_index) {
  24756. const index = getNumber(_index, "index");
  24757. assertArgument(index <= 0xffffffff, "invalid index", "index", index);
  24758. // Base path
  24759. let path = this.path;
  24760. if (path) {
  24761. path += "/" + (index & ~HardenedBit);
  24762. if (index & HardenedBit) {
  24763. path += "'";
  24764. }
  24765. }
  24766. const { IR, IL } = ser_I(index, this.chainCode, this.publicKey, this.privateKey);
  24767. const ki = new SigningKey(toBeHex((toBigInt(IL) + BigInt(this.privateKey)) % N, 32));
  24768. return new HDNodeWallet(_guard, ki, this.fingerprint, hexlify(IR), path, index, this.depth + 1, this.mnemonic, this.provider);
  24769. }
  24770. /**
  24771. * Return the HDNode for %%path%% from this node.
  24772. */
  24773. derivePath(path) {
  24774. return derivePath(this, path);
  24775. }
  24776. static #fromSeed(_seed, mnemonic) {
  24777. assertArgument(isBytesLike(_seed), "invalid seed", "seed", "[REDACTED]");
  24778. const seed = getBytes(_seed, "seed");
  24779. assertArgument(seed.length >= 16 && seed.length <= 64, "invalid seed", "seed", "[REDACTED]");
  24780. const I = getBytes(computeHmac("sha512", MasterSecret, seed));
  24781. const signingKey = new SigningKey(hexlify(I.slice(0, 32)));
  24782. return new HDNodeWallet(_guard, signingKey, "0x00000000", hexlify(I.slice(32)), "m", 0, 0, mnemonic, null);
  24783. }
  24784. /**
  24785. * Creates a new HD Node from %%extendedKey%%.
  24786. *
  24787. * If the %%extendedKey%% will either have a prefix or ``xpub`` or
  24788. * ``xpriv``, returning a neutered HD Node ([[HDNodeVoidWallet]])
  24789. * or full HD Node ([[HDNodeWallet) respectively.
  24790. */
  24791. static fromExtendedKey(extendedKey) {
  24792. const bytes = toBeArray(decodeBase58(extendedKey)); // @TODO: redact
  24793. assertArgument(bytes.length === 82 || encodeBase58Check(bytes.slice(0, 78)) === extendedKey, "invalid extended key", "extendedKey", "[ REDACTED ]");
  24794. const depth = bytes[4];
  24795. const parentFingerprint = hexlify(bytes.slice(5, 9));
  24796. const index = parseInt(hexlify(bytes.slice(9, 13)).substring(2), 16);
  24797. const chainCode = hexlify(bytes.slice(13, 45));
  24798. const key = bytes.slice(45, 78);
  24799. switch (hexlify(bytes.slice(0, 4))) {
  24800. // Public Key
  24801. case "0x0488b21e":
  24802. case "0x043587cf": {
  24803. const publicKey = hexlify(key);
  24804. return new HDNodeVoidWallet(_guard, computeAddress(publicKey), publicKey, parentFingerprint, chainCode, null, index, depth, null);
  24805. }
  24806. // Private Key
  24807. case "0x0488ade4":
  24808. case "0x04358394 ":
  24809. if (key[0] !== 0) {
  24810. break;
  24811. }
  24812. return new HDNodeWallet(_guard, new SigningKey(key.slice(1)), parentFingerprint, chainCode, null, index, depth, null, null);
  24813. }
  24814. assertArgument(false, "invalid extended key prefix", "extendedKey", "[ REDACTED ]");
  24815. }
  24816. /**
  24817. * Creates a new random HDNode.
  24818. */
  24819. static createRandom(password, path, wordlist) {
  24820. if (password == null) {
  24821. password = "";
  24822. }
  24823. if (path == null) {
  24824. path = defaultPath;
  24825. }
  24826. if (wordlist == null) {
  24827. wordlist = LangEn.wordlist();
  24828. }
  24829. const mnemonic = Mnemonic.fromEntropy(randomBytes(16), password, wordlist);
  24830. return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path);
  24831. }
  24832. /**
  24833. * Create an HD Node from %%mnemonic%%.
  24834. */
  24835. static fromMnemonic(mnemonic, path) {
  24836. if (!path) {
  24837. path = defaultPath;
  24838. }
  24839. return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path);
  24840. }
  24841. /**
  24842. * Creates an HD Node from a mnemonic %%phrase%%.
  24843. */
  24844. static fromPhrase(phrase, password, path, wordlist) {
  24845. if (password == null) {
  24846. password = "";
  24847. }
  24848. if (path == null) {
  24849. path = defaultPath;
  24850. }
  24851. if (wordlist == null) {
  24852. wordlist = LangEn.wordlist();
  24853. }
  24854. const mnemonic = Mnemonic.fromPhrase(phrase, password, wordlist);
  24855. return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path);
  24856. }
  24857. /**
  24858. * Creates an HD Node from a %%seed%%.
  24859. */
  24860. static fromSeed(seed) {
  24861. return HDNodeWallet.#fromSeed(seed, null);
  24862. }
  24863. }
  24864. /**
  24865. * A **HDNodeVoidWallet** cannot sign, but provides access to
  24866. * the children nodes of a [[link-bip-32]] HD wallet addresses.
  24867. *
  24868. * The can be created by using an extended ``xpub`` key to
  24869. * [[HDNodeWallet_fromExtendedKey]] or by
  24870. * [nuetering](HDNodeWallet-neuter) a [[HDNodeWallet]].
  24871. */
  24872. class HDNodeVoidWallet extends VoidSigner {
  24873. /**
  24874. * The compressed public key.
  24875. */
  24876. publicKey;
  24877. /**
  24878. * The fingerprint.
  24879. *
  24880. * A fingerprint allows quick qay to detect parent and child nodes,
  24881. * but developers should be prepared to deal with collisions as it
  24882. * is only 4 bytes.
  24883. */
  24884. fingerprint;
  24885. /**
  24886. * The parent node fingerprint.
  24887. */
  24888. parentFingerprint;
  24889. /**
  24890. * The chaincode, which is effectively a public key used
  24891. * to derive children.
  24892. */
  24893. chainCode;
  24894. /**
  24895. * The derivation path of this wallet.
  24896. *
  24897. * Since extended keys do not provider full path details, this
  24898. * may be ``null``, if instantiated from a source that does not
  24899. * enocde it.
  24900. */
  24901. path;
  24902. /**
  24903. * The child index of this wallet. Values over ``2 *\* 31`` indicate
  24904. * the node is hardened.
  24905. */
  24906. index;
  24907. /**
  24908. * The depth of this wallet, which is the number of components
  24909. * in its path.
  24910. */
  24911. depth;
  24912. /**
  24913. * @private
  24914. */
  24915. constructor(guard, address, publicKey, parentFingerprint, chainCode, path, index, depth, provider) {
  24916. super(address, provider);
  24917. assertPrivate(guard, _guard, "HDNodeVoidWallet");
  24918. defineProperties(this, { publicKey });
  24919. const fingerprint = dataSlice(ripemd160(sha256(publicKey)), 0, 4);
  24920. defineProperties(this, {
  24921. publicKey, fingerprint, parentFingerprint, chainCode, path, index, depth
  24922. });
  24923. }
  24924. connect(provider) {
  24925. return new HDNodeVoidWallet(_guard, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, provider);
  24926. }
  24927. /**
  24928. * The extended key.
  24929. *
  24930. * This key will begin with the prefix ``xpub`` and can be used to
  24931. * reconstruct this neutered key to derive its children addresses.
  24932. */
  24933. get extendedKey() {
  24934. // We only support the mainnet values for now, but if anyone needs
  24935. // testnet values, let me know. I believe current sentiment is that
  24936. // we should always use mainnet, and use BIP-44 to derive the network
  24937. // - Mainnet: public=0x0488B21E, private=0x0488ADE4
  24938. // - Testnet: public=0x043587CF, private=0x04358394
  24939. assert(this.depth < 256, "Depth too deep", "UNSUPPORTED_OPERATION", { operation: "extendedKey" });
  24940. return encodeBase58Check(concat([
  24941. "0x0488B21E",
  24942. zpad(this.depth, 1),
  24943. this.parentFingerprint,
  24944. zpad(this.index, 4),
  24945. this.chainCode,
  24946. this.publicKey,
  24947. ]));
  24948. }
  24949. /**
  24950. * Returns true if this wallet has a path, providing a Type Guard
  24951. * that the path is non-null.
  24952. */
  24953. hasPath() { return (this.path != null); }
  24954. /**
  24955. * Return the child for %%index%%.
  24956. */
  24957. deriveChild(_index) {
  24958. const index = getNumber(_index, "index");
  24959. assertArgument(index <= 0xffffffff, "invalid index", "index", index);
  24960. // Base path
  24961. let path = this.path;
  24962. if (path) {
  24963. path += "/" + (index & ~HardenedBit);
  24964. if (index & HardenedBit) {
  24965. path += "'";
  24966. }
  24967. }
  24968. const { IR, IL } = ser_I(index, this.chainCode, this.publicKey, null);
  24969. const Ki = SigningKey.addPoints(IL, this.publicKey, true);
  24970. const address = computeAddress(Ki);
  24971. return new HDNodeVoidWallet(_guard, address, Ki, this.fingerprint, hexlify(IR), path, index, this.depth + 1, this.provider);
  24972. }
  24973. /**
  24974. * Return the signer for %%path%% from this node.
  24975. */
  24976. derivePath(path) {
  24977. return derivePath(this, path);
  24978. }
  24979. }
  24980. /*
  24981. export class HDNodeWalletManager {
  24982. #root: HDNodeWallet;
  24983. constructor(phrase: string, password?: null | string, path?: null | string, locale?: null | Wordlist) {
  24984. if (password == null) { password = ""; }
  24985. if (path == null) { path = "m/44'/60'/0'/0"; }
  24986. if (locale == null) { locale = LangEn.wordlist(); }
  24987. this.#root = HDNodeWallet.fromPhrase(phrase, password, path, locale);
  24988. }
  24989. getSigner(index?: number): HDNodeWallet {
  24990. return this.#root.deriveChild((index == null) ? 0: index);
  24991. }
  24992. }
  24993. */
  24994. /**
  24995. * Returns the [[link-bip-32]] path for the account at %%index%%.
  24996. *
  24997. * This is the pattern used by wallets like Ledger.
  24998. *
  24999. * There is also an [alternate pattern](getIndexedAccountPath) used by
  25000. * some software.
  25001. */
  25002. function getAccountPath(_index) {
  25003. const index = getNumber(_index, "index");
  25004. assertArgument(index >= 0 && index < HardenedBit, "invalid account index", "index", index);
  25005. return `m/44'/60'/${index}'/0/0`;
  25006. }
  25007. /**
  25008. * Returns the path using an alternative pattern for deriving accounts,
  25009. * at %%index%%.
  25010. *
  25011. * This derivation path uses the //index// component rather than the
  25012. * //account// component to derive sequential accounts.
  25013. *
  25014. * This is the pattern used by wallets like MetaMask.
  25015. */
  25016. function getIndexedAccountPath(_index) {
  25017. const index = getNumber(_index, "index");
  25018. assertArgument(index >= 0 && index < HardenedBit, "invalid account index", "index", index);
  25019. return `m/44'/60'/0'/0/${index}`;
  25020. }
  25021. /**
  25022. * @_subsection: api/wallet:JSON Wallets [json-wallets]
  25023. */
  25024. /**
  25025. * Returns true if %%json%% is a valid JSON Crowdsale wallet.
  25026. */
  25027. function isCrowdsaleJson(json) {
  25028. try {
  25029. const data = JSON.parse(json);
  25030. if (data.encseed) {
  25031. return true;
  25032. }
  25033. }
  25034. catch (error) { }
  25035. return false;
  25036. }
  25037. // See: https://github.com/ethereum/pyethsaletool
  25038. /**
  25039. * Before Ethereum launched, it was necessary to create a wallet
  25040. * format for backers to use, which would be used to receive ether
  25041. * as a reward for contributing to the project.
  25042. *
  25043. * The [[link-crowdsale]] format is now obsolete, but it is still
  25044. * useful to support and the additional code is fairly trivial as
  25045. * all the primitives required are used through core portions of
  25046. * the library.
  25047. */
  25048. function decryptCrowdsaleJson(json, _password) {
  25049. const data = JSON.parse(json);
  25050. const password = getPassword(_password);
  25051. // Ethereum Address
  25052. const address = getAddress(spelunk(data, "ethaddr:string!"));
  25053. // Encrypted Seed
  25054. const encseed = looseArrayify(spelunk(data, "encseed:string!"));
  25055. assertArgument(encseed && (encseed.length % 16) === 0, "invalid encseed", "json", json);
  25056. const key = getBytes(pbkdf2(password, password, 2000, 32, "sha256")).slice(0, 16);
  25057. const iv = encseed.slice(0, 16);
  25058. const encryptedSeed = encseed.slice(16);
  25059. // Decrypt the seed
  25060. const aesCbc = new CBC(key, iv);
  25061. const seed = pkcs7Strip(getBytes(aesCbc.decrypt(encryptedSeed)));
  25062. // This wallet format is weird... Convert the binary encoded hex to a string.
  25063. let seedHex = "";
  25064. for (let i = 0; i < seed.length; i++) {
  25065. seedHex += String.fromCharCode(seed[i]);
  25066. }
  25067. return { address, privateKey: id(seedHex) };
  25068. }
  25069. function stall(duration) {
  25070. return new Promise((resolve) => { setTimeout(() => { resolve(); }, duration); });
  25071. }
  25072. /**
  25073. * A **Wallet** manages a single private key which is used to sign
  25074. * transactions, messages and other common payloads.
  25075. *
  25076. * This class is generally the main entry point for developers
  25077. * that wish to use a private key directly, as it can create
  25078. * instances from a large variety of common sources, including
  25079. * raw private key, [[link-bip-39]] mnemonics and encrypte JSON
  25080. * wallets.
  25081. */
  25082. class Wallet extends BaseWallet {
  25083. /**
  25084. * Create a new wallet for the private %%key%%, optionally connected
  25085. * to %%provider%%.
  25086. */
  25087. constructor(key, provider) {
  25088. if (typeof (key) === "string" && !key.startsWith("0x")) {
  25089. key = "0x" + key;
  25090. }
  25091. let signingKey = (typeof (key) === "string") ? new SigningKey(key) : key;
  25092. super(signingKey, provider);
  25093. }
  25094. connect(provider) {
  25095. return new Wallet(this.signingKey, provider);
  25096. }
  25097. /**
  25098. * Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with
  25099. * %%password%%.
  25100. *
  25101. * If %%progressCallback%% is specified, it will receive periodic
  25102. * updates as the encryption process progreses.
  25103. */
  25104. async encrypt(password, progressCallback) {
  25105. const account = { address: this.address, privateKey: this.privateKey };
  25106. return await encryptKeystoreJson(account, password, { progressCallback });
  25107. }
  25108. /**
  25109. * Returns a [JSON Keystore Wallet](json-wallets) encryped with
  25110. * %%password%%.
  25111. *
  25112. * It is preferred to use the [async version](encrypt) instead,
  25113. * which allows a [[ProgressCallback]] to keep the user informed.
  25114. *
  25115. * This method will block the event loop (freezing all UI) until
  25116. * it is complete, which may be a non-trivial duration.
  25117. */
  25118. encryptSync(password) {
  25119. const account = { address: this.address, privateKey: this.privateKey };
  25120. return encryptKeystoreJsonSync(account, password);
  25121. }
  25122. static #fromAccount(account) {
  25123. assertArgument(account, "invalid JSON wallet", "json", "[ REDACTED ]");
  25124. if ("mnemonic" in account && account.mnemonic && account.mnemonic.locale === "en") {
  25125. const mnemonic = Mnemonic.fromEntropy(account.mnemonic.entropy);
  25126. const wallet = HDNodeWallet.fromMnemonic(mnemonic, account.mnemonic.path);
  25127. if (wallet.address === account.address && wallet.privateKey === account.privateKey) {
  25128. return wallet;
  25129. }
  25130. console.log("WARNING: JSON mismatch address/privateKey != mnemonic; fallback onto private key");
  25131. }
  25132. const wallet = new Wallet(account.privateKey);
  25133. assertArgument(wallet.address === account.address, "address/privateKey mismatch", "json", "[ REDACTED ]");
  25134. return wallet;
  25135. }
  25136. /**
  25137. * Creates (asynchronously) a **Wallet** by decrypting the %%json%%
  25138. * with %%password%%.
  25139. *
  25140. * If %%progress%% is provided, it is called periodically during
  25141. * decryption so that any UI can be updated.
  25142. */
  25143. static async fromEncryptedJson(json, password, progress) {
  25144. let account = null;
  25145. if (isKeystoreJson(json)) {
  25146. account = await decryptKeystoreJson(json, password, progress);
  25147. }
  25148. else if (isCrowdsaleJson(json)) {
  25149. if (progress) {
  25150. progress(0);
  25151. await stall(0);
  25152. }
  25153. account = decryptCrowdsaleJson(json, password);
  25154. if (progress) {
  25155. progress(1);
  25156. await stall(0);
  25157. }
  25158. }
  25159. return Wallet.#fromAccount(account);
  25160. }
  25161. /**
  25162. * Creates a **Wallet** by decrypting the %%json%% with %%password%%.
  25163. *
  25164. * The [[fromEncryptedJson]] method is preferred, as this method
  25165. * will lock up and freeze the UI during decryption, which may take
  25166. * some time.
  25167. */
  25168. static fromEncryptedJsonSync(json, password) {
  25169. let account = null;
  25170. if (isKeystoreJson(json)) {
  25171. account = decryptKeystoreJsonSync(json, password);
  25172. }
  25173. else if (isCrowdsaleJson(json)) {
  25174. account = decryptCrowdsaleJson(json, password);
  25175. }
  25176. else {
  25177. assertArgument(false, "invalid JSON wallet", "json", "[ REDACTED ]");
  25178. }
  25179. return Wallet.#fromAccount(account);
  25180. }
  25181. /**
  25182. * Creates a new random [[HDNodeWallet]] using the available
  25183. * [cryptographic random source](randomBytes).
  25184. *
  25185. * If there is no crytographic random source, this will throw.
  25186. */
  25187. static createRandom(provider) {
  25188. const wallet = HDNodeWallet.createRandom();
  25189. if (provider) {
  25190. return wallet.connect(provider);
  25191. }
  25192. return wallet;
  25193. }
  25194. /**
  25195. * Creates a [[HDNodeWallet]] for %%phrase%%.
  25196. */
  25197. static fromPhrase(phrase, provider) {
  25198. const wallet = HDNodeWallet.fromPhrase(phrase);
  25199. if (provider) {
  25200. return wallet.connect(provider);
  25201. }
  25202. return wallet;
  25203. }
  25204. }
  25205. const Base64 = ")!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_";
  25206. /**
  25207. * @_ignore
  25208. */
  25209. function decodeBits(width, data) {
  25210. const maxValue = (1 << width) - 1;
  25211. const result = [];
  25212. let accum = 0, bits = 0, flood = 0;
  25213. for (let i = 0; i < data.length; i++) {
  25214. // Accumulate 6 bits of data
  25215. accum = ((accum << 6) | Base64.indexOf(data[i]));
  25216. bits += 6;
  25217. // While we have enough for a word...
  25218. while (bits >= width) {
  25219. // ...read the word
  25220. const value = (accum >> (bits - width));
  25221. accum &= (1 << (bits - width)) - 1;
  25222. bits -= width;
  25223. // A value of 0 indicates we exceeded maxValue, it
  25224. // floods over into the next value
  25225. if (value === 0) {
  25226. flood += maxValue;
  25227. }
  25228. else {
  25229. result.push(value + flood);
  25230. flood = 0;
  25231. }
  25232. }
  25233. }
  25234. return result;
  25235. }
  25236. /**
  25237. * @_ignore
  25238. */
  25239. function decodeOwlA(data, accents) {
  25240. let words = decodeOwl(data).join(",");
  25241. // Inject the accents
  25242. accents.split(/,/g).forEach((accent) => {
  25243. const match = accent.match(/^([a-z]*)([0-9]+)([0-9])(.*)$/);
  25244. assertArgument(match !== null, "internal error parsing accents", "accents", accents);
  25245. let posOffset = 0;
  25246. const positions = decodeBits(parseInt(match[3]), match[4]);
  25247. const charCode = parseInt(match[2]);
  25248. const regex = new RegExp(`([${match[1]}])`, "g");
  25249. words = words.replace(regex, (all, letter) => {
  25250. const rem = --positions[posOffset];
  25251. if (rem === 0) {
  25252. letter = String.fromCharCode(letter.charCodeAt(0), charCode);
  25253. posOffset++;
  25254. }
  25255. return letter;
  25256. });
  25257. });
  25258. return words.split(",");
  25259. }
  25260. /**
  25261. * An OWL-A format Wordlist extends the OWL format to add an
  25262. * overlay onto an OWL format Wordlist to support diacritic
  25263. * marks.
  25264. *
  25265. * This class is generally not useful to most developers as
  25266. * it is used mainly internally to keep Wordlists for languages
  25267. * based on latin-1 small.
  25268. *
  25269. * If necessary, there are tools within the ``generation/`` folder
  25270. * to create the necessary data.
  25271. */
  25272. class WordlistOwlA extends WordlistOwl {
  25273. #accent;
  25274. /**
  25275. * Creates a new Wordlist for %%locale%% using the OWLA %%data%%
  25276. * and %%accent%% data and validated against the %%checksum%%.
  25277. */
  25278. constructor(locale, data, accent, checksum) {
  25279. super(locale, data, checksum);
  25280. this.#accent = accent;
  25281. }
  25282. /**
  25283. * The OWLA-encoded accent data.
  25284. */
  25285. get _accent() { return this.#accent; }
  25286. /**
  25287. * Decode all the words for the wordlist.
  25288. */
  25289. _decodeWords() {
  25290. return decodeOwlA(this._data, this._accent);
  25291. }
  25292. }
  25293. const wordlists = {
  25294. en: LangEn.wordlist(),
  25295. };
  25296. /////////////////////////////
  25297. //
  25298. // dummy change; to pick-up ws security issue changes
  25299. var ethers = /*#__PURE__*/Object.freeze({
  25300. __proto__: null,
  25301. AbiCoder: AbiCoder,
  25302. AbstractProvider: AbstractProvider,
  25303. AbstractSigner: AbstractSigner,
  25304. AlchemyProvider: AlchemyProvider,
  25305. AnkrProvider: AnkrProvider,
  25306. BaseContract: BaseContract,
  25307. BaseWallet: BaseWallet,
  25308. Block: Block,
  25309. BrowserProvider: BrowserProvider,
  25310. ChainstackProvider: ChainstackProvider,
  25311. CloudflareProvider: CloudflareProvider,
  25312. ConstructorFragment: ConstructorFragment,
  25313. Contract: Contract,
  25314. ContractEventPayload: ContractEventPayload,
  25315. ContractFactory: ContractFactory,
  25316. ContractTransactionReceipt: ContractTransactionReceipt,
  25317. ContractTransactionResponse: ContractTransactionResponse,
  25318. ContractUnknownEventPayload: ContractUnknownEventPayload,
  25319. EnsPlugin: EnsPlugin,
  25320. EnsResolver: EnsResolver,
  25321. ErrorDescription: ErrorDescription,
  25322. ErrorFragment: ErrorFragment,
  25323. EtherSymbol: EtherSymbol,
  25324. EtherscanPlugin: EtherscanPlugin,
  25325. EtherscanProvider: EtherscanProvider,
  25326. EventFragment: EventFragment,
  25327. EventLog: EventLog,
  25328. EventPayload: EventPayload,
  25329. FallbackFragment: FallbackFragment,
  25330. FallbackProvider: FallbackProvider,
  25331. FeeData: FeeData,
  25332. FeeDataNetworkPlugin: FeeDataNetworkPlugin,
  25333. FetchCancelSignal: FetchCancelSignal,
  25334. FetchRequest: FetchRequest,
  25335. FetchResponse: FetchResponse,
  25336. FetchUrlFeeDataNetworkPlugin: FetchUrlFeeDataNetworkPlugin,
  25337. FixedNumber: FixedNumber,
  25338. Fragment: Fragment,
  25339. FunctionFragment: FunctionFragment,
  25340. GasCostPlugin: GasCostPlugin,
  25341. HDNodeVoidWallet: HDNodeVoidWallet,
  25342. HDNodeWallet: HDNodeWallet,
  25343. Indexed: Indexed,
  25344. InfuraProvider: InfuraProvider,
  25345. InfuraWebSocketProvider: InfuraWebSocketProvider,
  25346. Interface: Interface,
  25347. IpcSocketProvider: IpcSocketProvider,
  25348. JsonRpcApiProvider: JsonRpcApiProvider,
  25349. JsonRpcProvider: JsonRpcProvider,
  25350. JsonRpcSigner: JsonRpcSigner,
  25351. LangEn: LangEn,
  25352. Log: Log,
  25353. LogDescription: LogDescription,
  25354. MaxInt256: MaxInt256,
  25355. MaxUint256: MaxUint256,
  25356. MessagePrefix: MessagePrefix,
  25357. MinInt256: MinInt256,
  25358. Mnemonic: Mnemonic,
  25359. MulticoinProviderPlugin: MulticoinProviderPlugin,
  25360. N: N$1,
  25361. NamedFragment: NamedFragment,
  25362. Network: Network,
  25363. NetworkPlugin: NetworkPlugin,
  25364. NonceManager: NonceManager,
  25365. ParamType: ParamType,
  25366. PocketProvider: PocketProvider,
  25367. QuickNodeProvider: QuickNodeProvider,
  25368. Result: Result,
  25369. Signature: Signature,
  25370. SigningKey: SigningKey,
  25371. SocketBlockSubscriber: SocketBlockSubscriber,
  25372. SocketEventSubscriber: SocketEventSubscriber,
  25373. SocketPendingSubscriber: SocketPendingSubscriber,
  25374. SocketProvider: SocketProvider,
  25375. SocketSubscriber: SocketSubscriber,
  25376. StructFragment: StructFragment,
  25377. Transaction: Transaction,
  25378. TransactionDescription: TransactionDescription,
  25379. TransactionReceipt: TransactionReceipt,
  25380. TransactionResponse: TransactionResponse,
  25381. Typed: Typed,
  25382. TypedDataEncoder: TypedDataEncoder,
  25383. UndecodedEventLog: UndecodedEventLog,
  25384. UnmanagedSubscriber: UnmanagedSubscriber,
  25385. Utf8ErrorFuncs: Utf8ErrorFuncs,
  25386. VoidSigner: VoidSigner,
  25387. Wallet: Wallet,
  25388. WebSocketProvider: WebSocketProvider,
  25389. WeiPerEther: WeiPerEther,
  25390. Wordlist: Wordlist,
  25391. WordlistOwl: WordlistOwl,
  25392. WordlistOwlA: WordlistOwlA,
  25393. ZeroAddress: ZeroAddress,
  25394. ZeroHash: ZeroHash,
  25395. accessListify: accessListify,
  25396. assert: assert,
  25397. assertArgument: assertArgument,
  25398. assertArgumentCount: assertArgumentCount,
  25399. assertNormalize: assertNormalize,
  25400. assertPrivate: assertPrivate,
  25401. checkResultErrors: checkResultErrors,
  25402. computeAddress: computeAddress,
  25403. computeHmac: computeHmac,
  25404. concat: concat,
  25405. copyRequest: copyRequest,
  25406. dataLength: dataLength,
  25407. dataSlice: dataSlice,
  25408. decodeBase58: decodeBase58,
  25409. decodeBase64: decodeBase64,
  25410. decodeBytes32String: decodeBytes32String,
  25411. decodeRlp: decodeRlp,
  25412. decryptCrowdsaleJson: decryptCrowdsaleJson,
  25413. decryptKeystoreJson: decryptKeystoreJson,
  25414. decryptKeystoreJsonSync: decryptKeystoreJsonSync,
  25415. defaultPath: defaultPath,
  25416. defineProperties: defineProperties,
  25417. dnsEncode: dnsEncode,
  25418. encodeBase58: encodeBase58,
  25419. encodeBase64: encodeBase64,
  25420. encodeBytes32String: encodeBytes32String,
  25421. encodeRlp: encodeRlp,
  25422. encryptKeystoreJson: encryptKeystoreJson,
  25423. encryptKeystoreJsonSync: encryptKeystoreJsonSync,
  25424. ensNormalize: ensNormalize,
  25425. formatEther: formatEther,
  25426. formatUnits: formatUnits,
  25427. fromTwos: fromTwos,
  25428. getAccountPath: getAccountPath,
  25429. getAddress: getAddress,
  25430. getBigInt: getBigInt,
  25431. getBytes: getBytes,
  25432. getBytesCopy: getBytesCopy,
  25433. getCreate2Address: getCreate2Address,
  25434. getCreateAddress: getCreateAddress,
  25435. getDefaultProvider: getDefaultProvider,
  25436. getIcapAddress: getIcapAddress,
  25437. getIndexedAccountPath: getIndexedAccountPath,
  25438. getNumber: getNumber,
  25439. getUint: getUint,
  25440. hashMessage: hashMessage,
  25441. hexlify: hexlify,
  25442. id: id,
  25443. isAddress: isAddress,
  25444. isAddressable: isAddressable,
  25445. isBytesLike: isBytesLike,
  25446. isCallException: isCallException,
  25447. isCrowdsaleJson: isCrowdsaleJson,
  25448. isError: isError,
  25449. isHexString: isHexString,
  25450. isKeystoreJson: isKeystoreJson,
  25451. isValidName: isValidName,
  25452. keccak256: keccak256,
  25453. lock: lock,
  25454. makeError: makeError,
  25455. mask: mask,
  25456. namehash: namehash,
  25457. parseEther: parseEther,
  25458. parseUnits: parseUnits$1,
  25459. pbkdf2: pbkdf2,
  25460. randomBytes: randomBytes,
  25461. recoverAddress: recoverAddress,
  25462. resolveAddress: resolveAddress,
  25463. resolveProperties: resolveProperties,
  25464. ripemd160: ripemd160,
  25465. scrypt: scrypt,
  25466. scryptSync: scryptSync,
  25467. sha256: sha256,
  25468. sha512: sha512,
  25469. showThrottleMessage: showThrottleMessage,
  25470. solidityPacked: solidityPacked,
  25471. solidityPackedKeccak256: solidityPackedKeccak256,
  25472. solidityPackedSha256: solidityPackedSha256,
  25473. stripZerosLeft: stripZerosLeft,
  25474. toBeArray: toBeArray,
  25475. toBeHex: toBeHex,
  25476. toBigInt: toBigInt,
  25477. toNumber: toNumber,
  25478. toQuantity: toQuantity,
  25479. toTwos: toTwos,
  25480. toUtf8Bytes: toUtf8Bytes,
  25481. toUtf8CodePoints: toUtf8CodePoints,
  25482. toUtf8String: toUtf8String,
  25483. uuidV4: uuidV4,
  25484. verifyMessage: verifyMessage,
  25485. verifyTypedData: verifyTypedData,
  25486. version: version,
  25487. wordlists: wordlists,
  25488. zeroPadBytes: zeroPadBytes,
  25489. zeroPadValue: zeroPadValue
  25490. });
  25491. exports.AbiCoder = AbiCoder;
  25492. exports.AbstractProvider = AbstractProvider;
  25493. exports.AbstractSigner = AbstractSigner;
  25494. exports.AlchemyProvider = AlchemyProvider;
  25495. exports.AnkrProvider = AnkrProvider;
  25496. exports.BaseContract = BaseContract;
  25497. exports.BaseWallet = BaseWallet;
  25498. exports.Block = Block;
  25499. exports.BrowserProvider = BrowserProvider;
  25500. exports.ChainstackProvider = ChainstackProvider;
  25501. exports.CloudflareProvider = CloudflareProvider;
  25502. exports.ConstructorFragment = ConstructorFragment;
  25503. exports.Contract = Contract;
  25504. exports.ContractEventPayload = ContractEventPayload;
  25505. exports.ContractFactory = ContractFactory;
  25506. exports.ContractTransactionReceipt = ContractTransactionReceipt;
  25507. exports.ContractTransactionResponse = ContractTransactionResponse;
  25508. exports.ContractUnknownEventPayload = ContractUnknownEventPayload;
  25509. exports.EnsPlugin = EnsPlugin;
  25510. exports.EnsResolver = EnsResolver;
  25511. exports.ErrorDescription = ErrorDescription;
  25512. exports.ErrorFragment = ErrorFragment;
  25513. exports.EtherSymbol = EtherSymbol;
  25514. exports.EtherscanPlugin = EtherscanPlugin;
  25515. exports.EtherscanProvider = EtherscanProvider;
  25516. exports.EventFragment = EventFragment;
  25517. exports.EventLog = EventLog;
  25518. exports.EventPayload = EventPayload;
  25519. exports.FallbackFragment = FallbackFragment;
  25520. exports.FallbackProvider = FallbackProvider;
  25521. exports.FeeData = FeeData;
  25522. exports.FeeDataNetworkPlugin = FeeDataNetworkPlugin;
  25523. exports.FetchCancelSignal = FetchCancelSignal;
  25524. exports.FetchRequest = FetchRequest;
  25525. exports.FetchResponse = FetchResponse;
  25526. exports.FetchUrlFeeDataNetworkPlugin = FetchUrlFeeDataNetworkPlugin;
  25527. exports.FixedNumber = FixedNumber;
  25528. exports.Fragment = Fragment;
  25529. exports.FunctionFragment = FunctionFragment;
  25530. exports.GasCostPlugin = GasCostPlugin;
  25531. exports.HDNodeVoidWallet = HDNodeVoidWallet;
  25532. exports.HDNodeWallet = HDNodeWallet;
  25533. exports.Indexed = Indexed;
  25534. exports.InfuraProvider = InfuraProvider;
  25535. exports.InfuraWebSocketProvider = InfuraWebSocketProvider;
  25536. exports.Interface = Interface;
  25537. exports.IpcSocketProvider = IpcSocketProvider;
  25538. exports.JsonRpcApiProvider = JsonRpcApiProvider;
  25539. exports.JsonRpcProvider = JsonRpcProvider;
  25540. exports.JsonRpcSigner = JsonRpcSigner;
  25541. exports.LangEn = LangEn;
  25542. exports.Log = Log;
  25543. exports.LogDescription = LogDescription;
  25544. exports.MaxInt256 = MaxInt256;
  25545. exports.MaxUint256 = MaxUint256;
  25546. exports.MessagePrefix = MessagePrefix;
  25547. exports.MinInt256 = MinInt256;
  25548. exports.Mnemonic = Mnemonic;
  25549. exports.MulticoinProviderPlugin = MulticoinProviderPlugin;
  25550. exports.N = N$1;
  25551. exports.NamedFragment = NamedFragment;
  25552. exports.Network = Network;
  25553. exports.NetworkPlugin = NetworkPlugin;
  25554. exports.NonceManager = NonceManager;
  25555. exports.ParamType = ParamType;
  25556. exports.PocketProvider = PocketProvider;
  25557. exports.QuickNodeProvider = QuickNodeProvider;
  25558. exports.Result = Result;
  25559. exports.Signature = Signature;
  25560. exports.SigningKey = SigningKey;
  25561. exports.SocketBlockSubscriber = SocketBlockSubscriber;
  25562. exports.SocketEventSubscriber = SocketEventSubscriber;
  25563. exports.SocketPendingSubscriber = SocketPendingSubscriber;
  25564. exports.SocketProvider = SocketProvider;
  25565. exports.SocketSubscriber = SocketSubscriber;
  25566. exports.StructFragment = StructFragment;
  25567. exports.Transaction = Transaction;
  25568. exports.TransactionDescription = TransactionDescription;
  25569. exports.TransactionReceipt = TransactionReceipt;
  25570. exports.TransactionResponse = TransactionResponse;
  25571. exports.Typed = Typed;
  25572. exports.TypedDataEncoder = TypedDataEncoder;
  25573. exports.UndecodedEventLog = UndecodedEventLog;
  25574. exports.UnmanagedSubscriber = UnmanagedSubscriber;
  25575. exports.Utf8ErrorFuncs = Utf8ErrorFuncs;
  25576. exports.VoidSigner = VoidSigner;
  25577. exports.Wallet = Wallet;
  25578. exports.WebSocketProvider = WebSocketProvider;
  25579. exports.WeiPerEther = WeiPerEther;
  25580. exports.Wordlist = Wordlist;
  25581. exports.WordlistOwl = WordlistOwl;
  25582. exports.WordlistOwlA = WordlistOwlA;
  25583. exports.ZeroAddress = ZeroAddress;
  25584. exports.ZeroHash = ZeroHash;
  25585. exports.accessListify = accessListify;
  25586. exports.assert = assert;
  25587. exports.assertArgument = assertArgument;
  25588. exports.assertArgumentCount = assertArgumentCount;
  25589. exports.assertNormalize = assertNormalize;
  25590. exports.assertPrivate = assertPrivate;
  25591. exports.checkResultErrors = checkResultErrors;
  25592. exports.computeAddress = computeAddress;
  25593. exports.computeHmac = computeHmac;
  25594. exports.concat = concat;
  25595. exports.copyRequest = copyRequest;
  25596. exports.dataLength = dataLength;
  25597. exports.dataSlice = dataSlice;
  25598. exports.decodeBase58 = decodeBase58;
  25599. exports.decodeBase64 = decodeBase64;
  25600. exports.decodeBytes32String = decodeBytes32String;
  25601. exports.decodeRlp = decodeRlp;
  25602. exports.decryptCrowdsaleJson = decryptCrowdsaleJson;
  25603. exports.decryptKeystoreJson = decryptKeystoreJson;
  25604. exports.decryptKeystoreJsonSync = decryptKeystoreJsonSync;
  25605. exports.defaultPath = defaultPath;
  25606. exports.defineProperties = defineProperties;
  25607. exports.dnsEncode = dnsEncode;
  25608. exports.encodeBase58 = encodeBase58;
  25609. exports.encodeBase64 = encodeBase64;
  25610. exports.encodeBytes32String = encodeBytes32String;
  25611. exports.encodeRlp = encodeRlp;
  25612. exports.encryptKeystoreJson = encryptKeystoreJson;
  25613. exports.encryptKeystoreJsonSync = encryptKeystoreJsonSync;
  25614. exports.ensNormalize = ensNormalize;
  25615. exports.ethers = ethers;
  25616. exports.formatEther = formatEther;
  25617. exports.formatUnits = formatUnits;
  25618. exports.fromTwos = fromTwos;
  25619. exports.getAccountPath = getAccountPath;
  25620. exports.getAddress = getAddress;
  25621. exports.getBigInt = getBigInt;
  25622. exports.getBytes = getBytes;
  25623. exports.getBytesCopy = getBytesCopy;
  25624. exports.getCreate2Address = getCreate2Address;
  25625. exports.getCreateAddress = getCreateAddress;
  25626. exports.getDefaultProvider = getDefaultProvider;
  25627. exports.getIcapAddress = getIcapAddress;
  25628. exports.getIndexedAccountPath = getIndexedAccountPath;
  25629. exports.getNumber = getNumber;
  25630. exports.getUint = getUint;
  25631. exports.hashMessage = hashMessage;
  25632. exports.hexlify = hexlify;
  25633. exports.id = id;
  25634. exports.isAddress = isAddress;
  25635. exports.isAddressable = isAddressable;
  25636. exports.isBytesLike = isBytesLike;
  25637. exports.isCallException = isCallException;
  25638. exports.isCrowdsaleJson = isCrowdsaleJson;
  25639. exports.isError = isError;
  25640. exports.isHexString = isHexString;
  25641. exports.isKeystoreJson = isKeystoreJson;
  25642. exports.isValidName = isValidName;
  25643. exports.keccak256 = keccak256;
  25644. exports.lock = lock;
  25645. exports.makeError = makeError;
  25646. exports.mask = mask;
  25647. exports.namehash = namehash;
  25648. exports.parseEther = parseEther;
  25649. exports.parseUnits = parseUnits$1;
  25650. exports.pbkdf2 = pbkdf2;
  25651. exports.randomBytes = randomBytes;
  25652. exports.recoverAddress = recoverAddress;
  25653. exports.resolveAddress = resolveAddress;
  25654. exports.resolveProperties = resolveProperties;
  25655. exports.ripemd160 = ripemd160;
  25656. exports.scrypt = scrypt;
  25657. exports.scryptSync = scryptSync;
  25658. exports.sha256 = sha256;
  25659. exports.sha512 = sha512;
  25660. exports.showThrottleMessage = showThrottleMessage;
  25661. exports.solidityPacked = solidityPacked;
  25662. exports.solidityPackedKeccak256 = solidityPackedKeccak256;
  25663. exports.solidityPackedSha256 = solidityPackedSha256;
  25664. exports.stripZerosLeft = stripZerosLeft;
  25665. exports.toBeArray = toBeArray;
  25666. exports.toBeHex = toBeHex;
  25667. exports.toBigInt = toBigInt;
  25668. exports.toNumber = toNumber;
  25669. exports.toQuantity = toQuantity;
  25670. exports.toTwos = toTwos;
  25671. exports.toUtf8Bytes = toUtf8Bytes;
  25672. exports.toUtf8CodePoints = toUtf8CodePoints;
  25673. exports.toUtf8String = toUtf8String;
  25674. exports.uuidV4 = uuidV4;
  25675. exports.verifyMessage = verifyMessage;
  25676. exports.verifyTypedData = verifyTypedData;
  25677. exports.version = version;
  25678. exports.wordlists = wordlists;
  25679. exports.zeroPadBytes = zeroPadBytes;
  25680. exports.zeroPadValue = zeroPadValue;
  25681. }));
  25682. //# sourceMappingURL=ethers.umd.js.map