ethers.js 963 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725
  1. const __$G = (typeof globalThis !== 'undefined' ? globalThis: typeof window !== 'undefined' ? window: typeof global !== 'undefined' ? global: typeof self !== 'undefined' ? self: {});
  2. /* Do NOT modify this file; see /src.ts/_admin/update-version.ts */
  3. /**
  4. * The current version of Ethers.
  5. */
  6. const version = "6.13.5";
  7. /**
  8. * Property helper functions.
  9. *
  10. * @_subsection api/utils:Properties [about-properties]
  11. */
  12. function checkType(value, type, name) {
  13. const types = type.split("|").map(t => t.trim());
  14. for (let i = 0; i < types.length; i++) {
  15. switch (type) {
  16. case "any":
  17. return;
  18. case "bigint":
  19. case "boolean":
  20. case "number":
  21. case "string":
  22. if (typeof (value) === type) {
  23. return;
  24. }
  25. }
  26. }
  27. const error = new Error(`invalid value for type ${type}`);
  28. error.code = "INVALID_ARGUMENT";
  29. error.argument = `value.${name}`;
  30. error.value = value;
  31. throw error;
  32. }
  33. /**
  34. * Resolves to a new object that is a copy of %%value%%, but with all
  35. * values resolved.
  36. */
  37. async function resolveProperties(value) {
  38. const keys = Object.keys(value);
  39. const results = await Promise.all(keys.map((k) => Promise.resolve(value[k])));
  40. return results.reduce((accum, v, index) => {
  41. accum[keys[index]] = v;
  42. return accum;
  43. }, {});
  44. }
  45. /**
  46. * Assigns the %%values%% to %%target%% as read-only values.
  47. *
  48. * It %%types%% is specified, the values are checked.
  49. */
  50. function defineProperties(target, values, types) {
  51. for (let key in values) {
  52. let value = values[key];
  53. const type = (types ? types[key] : null);
  54. if (type) {
  55. checkType(value, type, key);
  56. }
  57. Object.defineProperty(target, key, { enumerable: true, value, writable: false });
  58. }
  59. }
  60. /**
  61. * All errors in ethers include properties to ensure they are both
  62. * human-readable (i.e. ``.message``) and machine-readable (i.e. ``.code``).
  63. *
  64. * The [[isError]] function can be used to check the error ``code`` and
  65. * provide a type guard for the properties present on that error interface.
  66. *
  67. * @_section: api/utils/errors:Errors [about-errors]
  68. */
  69. function stringify$1(value) {
  70. if (value == null) {
  71. return "null";
  72. }
  73. if (Array.isArray(value)) {
  74. return "[ " + (value.map(stringify$1)).join(", ") + " ]";
  75. }
  76. if (value instanceof Uint8Array) {
  77. const HEX = "0123456789abcdef";
  78. let result = "0x";
  79. for (let i = 0; i < value.length; i++) {
  80. result += HEX[value[i] >> 4];
  81. result += HEX[value[i] & 0xf];
  82. }
  83. return result;
  84. }
  85. if (typeof (value) === "object" && typeof (value.toJSON) === "function") {
  86. return stringify$1(value.toJSON());
  87. }
  88. switch (typeof (value)) {
  89. case "boolean":
  90. case "symbol":
  91. return value.toString();
  92. case "bigint":
  93. return BigInt(value).toString();
  94. case "number":
  95. return (value).toString();
  96. case "string":
  97. return JSON.stringify(value);
  98. case "object": {
  99. const keys = Object.keys(value);
  100. keys.sort();
  101. return "{ " + keys.map((k) => `${stringify$1(k)}: ${stringify$1(value[k])}`).join(", ") + " }";
  102. }
  103. }
  104. return `[ COULD NOT SERIALIZE ]`;
  105. }
  106. /**
  107. * Returns true if the %%error%% matches an error thrown by ethers
  108. * that matches the error %%code%%.
  109. *
  110. * In TypeScript environments, this can be used to check that %%error%%
  111. * matches an EthersError type, which means the expected properties will
  112. * be set.
  113. *
  114. * @See [ErrorCodes](api:ErrorCode)
  115. * @example
  116. * try {
  117. * // code....
  118. * } catch (e) {
  119. * if (isError(e, "CALL_EXCEPTION")) {
  120. * // The Type Guard has validated this object
  121. * console.log(e.data);
  122. * }
  123. * }
  124. */
  125. function isError(error, code) {
  126. return (error && error.code === code);
  127. }
  128. /**
  129. * Returns true if %%error%% is a [[CallExceptionError].
  130. */
  131. function isCallException(error) {
  132. return isError(error, "CALL_EXCEPTION");
  133. }
  134. /**
  135. * Returns a new Error configured to the format ethers emits errors, with
  136. * the %%message%%, [[api:ErrorCode]] %%code%% and additional properties
  137. * for the corresponding EthersError.
  138. *
  139. * Each error in ethers includes the version of ethers, a
  140. * machine-readable [[ErrorCode]], and depending on %%code%%, additional
  141. * required properties. The error message will also include the %%message%%,
  142. * ethers version, %%code%% and all additional properties, serialized.
  143. */
  144. function makeError(message, code, info) {
  145. let shortMessage = message;
  146. {
  147. const details = [];
  148. if (info) {
  149. if ("message" in info || "code" in info || "name" in info) {
  150. throw new Error(`value will overwrite populated values: ${stringify$1(info)}`);
  151. }
  152. for (const key in info) {
  153. if (key === "shortMessage") {
  154. continue;
  155. }
  156. const value = (info[key]);
  157. // try {
  158. details.push(key + "=" + stringify$1(value));
  159. // } catch (error: any) {
  160. // console.log("MMM", error.message);
  161. // details.push(key + "=[could not serialize object]");
  162. // }
  163. }
  164. }
  165. details.push(`code=${code}`);
  166. details.push(`version=${version}`);
  167. if (details.length) {
  168. message += " (" + details.join(", ") + ")";
  169. }
  170. }
  171. let error;
  172. switch (code) {
  173. case "INVALID_ARGUMENT":
  174. error = new TypeError(message);
  175. break;
  176. case "NUMERIC_FAULT":
  177. case "BUFFER_OVERRUN":
  178. error = new RangeError(message);
  179. break;
  180. default:
  181. error = new Error(message);
  182. }
  183. defineProperties(error, { code });
  184. if (info) {
  185. Object.assign(error, info);
  186. }
  187. if (error.shortMessage == null) {
  188. defineProperties(error, { shortMessage });
  189. }
  190. return error;
  191. }
  192. /**
  193. * Throws an EthersError with %%message%%, %%code%% and additional error
  194. * %%info%% when %%check%% is falsish..
  195. *
  196. * @see [[api:makeError]]
  197. */
  198. function assert(check, message, code, info) {
  199. if (!check) {
  200. throw makeError(message, code, info);
  201. }
  202. }
  203. /**
  204. * A simple helper to simply ensuring provided arguments match expected
  205. * constraints, throwing if not.
  206. *
  207. * In TypeScript environments, the %%check%% has been asserted true, so
  208. * any further code does not need additional compile-time checks.
  209. */
  210. function assertArgument(check, message, name, value) {
  211. assert(check, message, "INVALID_ARGUMENT", { argument: name, value: value });
  212. }
  213. function assertArgumentCount(count, expectedCount, message) {
  214. if (message == null) {
  215. message = "";
  216. }
  217. if (message) {
  218. message = ": " + message;
  219. }
  220. assert(count >= expectedCount, "missing argument" + message, "MISSING_ARGUMENT", {
  221. count: count,
  222. expectedCount: expectedCount
  223. });
  224. assert(count <= expectedCount, "too many arguments" + message, "UNEXPECTED_ARGUMENT", {
  225. count: count,
  226. expectedCount: expectedCount
  227. });
  228. }
  229. const _normalizeForms = ["NFD", "NFC", "NFKD", "NFKC"].reduce((accum, form) => {
  230. try {
  231. // General test for normalize
  232. /* c8 ignore start */
  233. if ("test".normalize(form) !== "test") {
  234. throw new Error("bad");
  235. }
  236. ;
  237. /* c8 ignore stop */
  238. if (form === "NFD") {
  239. const check = String.fromCharCode(0xe9).normalize("NFD");
  240. const expected = String.fromCharCode(0x65, 0x0301);
  241. /* c8 ignore start */
  242. if (check !== expected) {
  243. throw new Error("broken");
  244. }
  245. /* c8 ignore stop */
  246. }
  247. accum.push(form);
  248. }
  249. catch (error) { }
  250. return accum;
  251. }, []);
  252. /**
  253. * Throws if the normalization %%form%% is not supported.
  254. */
  255. function assertNormalize(form) {
  256. assert(_normalizeForms.indexOf(form) >= 0, "platform missing String.prototype.normalize", "UNSUPPORTED_OPERATION", {
  257. operation: "String.prototype.normalize", info: { form }
  258. });
  259. }
  260. /**
  261. * Many classes use file-scoped values to guard the constructor,
  262. * making it effectively private. This facilitates that pattern
  263. * by ensuring the %%givenGaurd%% matches the file-scoped %%guard%%,
  264. * throwing if not, indicating the %%className%% if provided.
  265. */
  266. function assertPrivate(givenGuard, guard, className) {
  267. if (className == null) {
  268. className = "";
  269. }
  270. if (givenGuard !== guard) {
  271. let method = className, operation = "new";
  272. if (className) {
  273. method += ".";
  274. operation += " " + className;
  275. }
  276. assert(false, `private constructor; use ${method}from* methods`, "UNSUPPORTED_OPERATION", {
  277. operation
  278. });
  279. }
  280. }
  281. /**
  282. * Some data helpers.
  283. *
  284. *
  285. * @_subsection api/utils:Data Helpers [about-data]
  286. */
  287. function _getBytes(value, name, copy) {
  288. if (value instanceof Uint8Array) {
  289. if (copy) {
  290. return new Uint8Array(value);
  291. }
  292. return value;
  293. }
  294. if (typeof (value) === "string" && value.match(/^0x(?:[0-9a-f][0-9a-f])*$/i)) {
  295. const result = new Uint8Array((value.length - 2) / 2);
  296. let offset = 2;
  297. for (let i = 0; i < result.length; i++) {
  298. result[i] = parseInt(value.substring(offset, offset + 2), 16);
  299. offset += 2;
  300. }
  301. return result;
  302. }
  303. assertArgument(false, "invalid BytesLike value", name || "value", value);
  304. }
  305. /**
  306. * Get a typed Uint8Array for %%value%%. If already a Uint8Array
  307. * the original %%value%% is returned; if a copy is required use
  308. * [[getBytesCopy]].
  309. *
  310. * @see: getBytesCopy
  311. */
  312. function getBytes(value, name) {
  313. return _getBytes(value, name, false);
  314. }
  315. /**
  316. * Get a typed Uint8Array for %%value%%, creating a copy if necessary
  317. * to prevent any modifications of the returned value from being
  318. * reflected elsewhere.
  319. *
  320. * @see: getBytes
  321. */
  322. function getBytesCopy(value, name) {
  323. return _getBytes(value, name, true);
  324. }
  325. /**
  326. * Returns true if %%value%% is a valid [[HexString]].
  327. *
  328. * If %%length%% is ``true`` or a //number//, it also checks that
  329. * %%value%% is a valid [[DataHexString]] of %%length%% (if a //number//)
  330. * bytes of data (e.g. ``0x1234`` is 2 bytes).
  331. */
  332. function isHexString(value, length) {
  333. if (typeof (value) !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) {
  334. return false;
  335. }
  336. if (typeof (length) === "number" && value.length !== 2 + 2 * length) {
  337. return false;
  338. }
  339. if (length === true && (value.length % 2) !== 0) {
  340. return false;
  341. }
  342. return true;
  343. }
  344. /**
  345. * Returns true if %%value%% is a valid representation of arbitrary
  346. * data (i.e. a valid [[DataHexString]] or a Uint8Array).
  347. */
  348. function isBytesLike(value) {
  349. return (isHexString(value, true) || (value instanceof Uint8Array));
  350. }
  351. const HexCharacters = "0123456789abcdef";
  352. /**
  353. * Returns a [[DataHexString]] representation of %%data%%.
  354. */
  355. function hexlify(data) {
  356. const bytes = getBytes(data);
  357. let result = "0x";
  358. for (let i = 0; i < bytes.length; i++) {
  359. const v = bytes[i];
  360. result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f];
  361. }
  362. return result;
  363. }
  364. /**
  365. * Returns a [[DataHexString]] by concatenating all values
  366. * within %%data%%.
  367. */
  368. function concat(datas) {
  369. return "0x" + datas.map((d) => hexlify(d).substring(2)).join("");
  370. }
  371. /**
  372. * Returns the length of %%data%%, in bytes.
  373. */
  374. function dataLength(data) {
  375. if (isHexString(data, true)) {
  376. return (data.length - 2) / 2;
  377. }
  378. return getBytes(data).length;
  379. }
  380. /**
  381. * Returns a [[DataHexString]] by slicing %%data%% from the %%start%%
  382. * offset to the %%end%% offset.
  383. *
  384. * By default %%start%% is 0 and %%end%% is the length of %%data%%.
  385. */
  386. function dataSlice(data, start, end) {
  387. const bytes = getBytes(data);
  388. if (end != null && end > bytes.length) {
  389. assert(false, "cannot slice beyond data bounds", "BUFFER_OVERRUN", {
  390. buffer: bytes, length: bytes.length, offset: end
  391. });
  392. }
  393. return hexlify(bytes.slice((start == null) ? 0 : start, (end == null) ? bytes.length : end));
  394. }
  395. /**
  396. * Return the [[DataHexString]] result by stripping all **leading**
  397. ** zero bytes from %%data%%.
  398. */
  399. function stripZerosLeft(data) {
  400. let bytes = hexlify(data).substring(2);
  401. while (bytes.startsWith("00")) {
  402. bytes = bytes.substring(2);
  403. }
  404. return "0x" + bytes;
  405. }
  406. function zeroPad(data, length, left) {
  407. const bytes = getBytes(data);
  408. assert(length >= bytes.length, "padding exceeds data length", "BUFFER_OVERRUN", {
  409. buffer: new Uint8Array(bytes),
  410. length: length,
  411. offset: length + 1
  412. });
  413. const result = new Uint8Array(length);
  414. result.fill(0);
  415. if (left) {
  416. result.set(bytes, length - bytes.length);
  417. }
  418. else {
  419. result.set(bytes, 0);
  420. }
  421. return hexlify(result);
  422. }
  423. /**
  424. * Return the [[DataHexString]] of %%data%% padded on the **left**
  425. * to %%length%% bytes.
  426. *
  427. * If %%data%% already exceeds %%length%%, a [[BufferOverrunError]] is
  428. * thrown.
  429. *
  430. * This pads data the same as **values** are in Solidity
  431. * (e.g. ``uint128``).
  432. */
  433. function zeroPadValue(data, length) {
  434. return zeroPad(data, length, true);
  435. }
  436. /**
  437. * Return the [[DataHexString]] of %%data%% padded on the **right**
  438. * to %%length%% bytes.
  439. *
  440. * If %%data%% already exceeds %%length%%, a [[BufferOverrunError]] is
  441. * thrown.
  442. *
  443. * This pads data the same as **bytes** are in Solidity
  444. * (e.g. ``bytes16``).
  445. */
  446. function zeroPadBytes(data, length) {
  447. return zeroPad(data, length, false);
  448. }
  449. /**
  450. * Some mathematic operations.
  451. *
  452. * @_subsection: api/utils:Math Helpers [about-maths]
  453. */
  454. const BN_0$a = BigInt(0);
  455. const BN_1$5 = BigInt(1);
  456. //const BN_Max256 = (BN_1 << BigInt(256)) - BN_1;
  457. // IEEE 754 support 53-bits of mantissa
  458. const maxValue = 0x1fffffffffffff;
  459. /**
  460. * Convert %%value%% from a twos-compliment representation of %%width%%
  461. * bits to its value.
  462. *
  463. * If the highest bit is ``1``, the result will be negative.
  464. */
  465. function fromTwos(_value, _width) {
  466. const value = getUint(_value, "value");
  467. const width = BigInt(getNumber(_width, "width"));
  468. assert((value >> width) === BN_0$a, "overflow", "NUMERIC_FAULT", {
  469. operation: "fromTwos", fault: "overflow", value: _value
  470. });
  471. // Top bit set; treat as a negative value
  472. if (value >> (width - BN_1$5)) {
  473. const mask = (BN_1$5 << width) - BN_1$5;
  474. return -(((~value) & mask) + BN_1$5);
  475. }
  476. return value;
  477. }
  478. /**
  479. * Convert %%value%% to a twos-compliment representation of
  480. * %%width%% bits.
  481. *
  482. * The result will always be positive.
  483. */
  484. function toTwos(_value, _width) {
  485. let value = getBigInt(_value, "value");
  486. const width = BigInt(getNumber(_width, "width"));
  487. const limit = (BN_1$5 << (width - BN_1$5));
  488. if (value < BN_0$a) {
  489. value = -value;
  490. assert(value <= limit, "too low", "NUMERIC_FAULT", {
  491. operation: "toTwos", fault: "overflow", value: _value
  492. });
  493. const mask = (BN_1$5 << width) - BN_1$5;
  494. return ((~value) & mask) + BN_1$5;
  495. }
  496. else {
  497. assert(value < limit, "too high", "NUMERIC_FAULT", {
  498. operation: "toTwos", fault: "overflow", value: _value
  499. });
  500. }
  501. return value;
  502. }
  503. /**
  504. * Mask %%value%% with a bitmask of %%bits%% ones.
  505. */
  506. function mask(_value, _bits) {
  507. const value = getUint(_value, "value");
  508. const bits = BigInt(getNumber(_bits, "bits"));
  509. return value & ((BN_1$5 << bits) - BN_1$5);
  510. }
  511. /**
  512. * Gets a BigInt from %%value%%. If it is an invalid value for
  513. * a BigInt, then an ArgumentError will be thrown for %%name%%.
  514. */
  515. function getBigInt(value, name) {
  516. switch (typeof (value)) {
  517. case "bigint": return value;
  518. case "number":
  519. assertArgument(Number.isInteger(value), "underflow", name || "value", value);
  520. assertArgument(value >= -maxValue && value <= maxValue, "overflow", name || "value", value);
  521. return BigInt(value);
  522. case "string":
  523. try {
  524. if (value === "") {
  525. throw new Error("empty string");
  526. }
  527. if (value[0] === "-" && value[1] !== "-") {
  528. return -BigInt(value.substring(1));
  529. }
  530. return BigInt(value);
  531. }
  532. catch (e) {
  533. assertArgument(false, `invalid BigNumberish string: ${e.message}`, name || "value", value);
  534. }
  535. }
  536. assertArgument(false, "invalid BigNumberish value", name || "value", value);
  537. }
  538. /**
  539. * Returns %%value%% as a bigint, validating it is valid as a bigint
  540. * value and that it is positive.
  541. */
  542. function getUint(value, name) {
  543. const result = getBigInt(value, name);
  544. assert(result >= BN_0$a, "unsigned value cannot be negative", "NUMERIC_FAULT", {
  545. fault: "overflow", operation: "getUint", value
  546. });
  547. return result;
  548. }
  549. const Nibbles$1 = "0123456789abcdef";
  550. /*
  551. * Converts %%value%% to a BigInt. If %%value%% is a Uint8Array, it
  552. * is treated as Big Endian data.
  553. */
  554. function toBigInt(value) {
  555. if (value instanceof Uint8Array) {
  556. let result = "0x0";
  557. for (const v of value) {
  558. result += Nibbles$1[v >> 4];
  559. result += Nibbles$1[v & 0x0f];
  560. }
  561. return BigInt(result);
  562. }
  563. return getBigInt(value);
  564. }
  565. /**
  566. * Gets a //number// from %%value%%. If it is an invalid value for
  567. * a //number//, then an ArgumentError will be thrown for %%name%%.
  568. */
  569. function getNumber(value, name) {
  570. switch (typeof (value)) {
  571. case "bigint":
  572. assertArgument(value >= -maxValue && value <= maxValue, "overflow", name || "value", value);
  573. return Number(value);
  574. case "number":
  575. assertArgument(Number.isInteger(value), "underflow", name || "value", value);
  576. assertArgument(value >= -maxValue && value <= maxValue, "overflow", name || "value", value);
  577. return value;
  578. case "string":
  579. try {
  580. if (value === "") {
  581. throw new Error("empty string");
  582. }
  583. return getNumber(BigInt(value), name);
  584. }
  585. catch (e) {
  586. assertArgument(false, `invalid numeric string: ${e.message}`, name || "value", value);
  587. }
  588. }
  589. assertArgument(false, "invalid numeric value", name || "value", value);
  590. }
  591. /**
  592. * Converts %%value%% to a number. If %%value%% is a Uint8Array, it
  593. * is treated as Big Endian data. Throws if the value is not safe.
  594. */
  595. function toNumber(value) {
  596. return getNumber(toBigInt(value));
  597. }
  598. /**
  599. * Converts %%value%% to a Big Endian hexstring, optionally padded to
  600. * %%width%% bytes.
  601. */
  602. function toBeHex(_value, _width) {
  603. const value = getUint(_value, "value");
  604. let result = value.toString(16);
  605. if (_width == null) {
  606. // Ensure the value is of even length
  607. if (result.length % 2) {
  608. result = "0" + result;
  609. }
  610. }
  611. else {
  612. const width = getNumber(_width, "width");
  613. assert(width * 2 >= result.length, `value exceeds width (${width} bytes)`, "NUMERIC_FAULT", {
  614. operation: "toBeHex",
  615. fault: "overflow",
  616. value: _value
  617. });
  618. // Pad the value to the required width
  619. while (result.length < (width * 2)) {
  620. result = "0" + result;
  621. }
  622. }
  623. return "0x" + result;
  624. }
  625. /**
  626. * Converts %%value%% to a Big Endian Uint8Array.
  627. */
  628. function toBeArray(_value) {
  629. const value = getUint(_value, "value");
  630. if (value === BN_0$a) {
  631. return new Uint8Array([]);
  632. }
  633. let hex = value.toString(16);
  634. if (hex.length % 2) {
  635. hex = "0" + hex;
  636. }
  637. const result = new Uint8Array(hex.length / 2);
  638. for (let i = 0; i < result.length; i++) {
  639. const offset = i * 2;
  640. result[i] = parseInt(hex.substring(offset, offset + 2), 16);
  641. }
  642. return result;
  643. }
  644. /**
  645. * Returns a [[HexString]] for %%value%% safe to use as a //Quantity//.
  646. *
  647. * A //Quantity// does not have and leading 0 values unless the value is
  648. * the literal value `0x0`. This is most commonly used for JSSON-RPC
  649. * numeric values.
  650. */
  651. function toQuantity(value) {
  652. let result = hexlify(isBytesLike(value) ? value : toBeArray(value)).substring(2);
  653. while (result.startsWith("0")) {
  654. result = result.substring(1);
  655. }
  656. if (result === "") {
  657. result = "0";
  658. }
  659. return "0x" + result;
  660. }
  661. /**
  662. * The [Base58 Encoding](link-base58) scheme allows a **numeric** value
  663. * to be encoded as a compact string using a radix of 58 using only
  664. * alpha-numeric characters. Confusingly similar characters are omitted
  665. * (i.e. ``"l0O"``).
  666. *
  667. * Note that Base58 encodes a **numeric** value, not arbitrary bytes,
  668. * since any zero-bytes on the left would get removed. To mitigate this
  669. * issue most schemes that use Base58 choose specific high-order values
  670. * to ensure non-zero prefixes.
  671. *
  672. * @_subsection: api/utils:Base58 Encoding [about-base58]
  673. */
  674. const Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
  675. let Lookup = null;
  676. function getAlpha(letter) {
  677. if (Lookup == null) {
  678. Lookup = {};
  679. for (let i = 0; i < Alphabet.length; i++) {
  680. Lookup[Alphabet[i]] = BigInt(i);
  681. }
  682. }
  683. const result = Lookup[letter];
  684. assertArgument(result != null, `invalid base58 value`, "letter", letter);
  685. return result;
  686. }
  687. const BN_0$9 = BigInt(0);
  688. const BN_58 = BigInt(58);
  689. /**
  690. * Encode %%value%% as a Base58-encoded string.
  691. */
  692. function encodeBase58(_value) {
  693. const bytes = getBytes(_value);
  694. let value = toBigInt(bytes);
  695. let result = "";
  696. while (value) {
  697. result = Alphabet[Number(value % BN_58)] + result;
  698. value /= BN_58;
  699. }
  700. // Account for leading padding zeros
  701. for (let i = 0; i < bytes.length; i++) {
  702. if (bytes[i]) {
  703. break;
  704. }
  705. result = Alphabet[0] + result;
  706. }
  707. return result;
  708. }
  709. /**
  710. * Decode the Base58-encoded %%value%%.
  711. */
  712. function decodeBase58(value) {
  713. let result = BN_0$9;
  714. for (let i = 0; i < value.length; i++) {
  715. result *= BN_58;
  716. result += getAlpha(value[i]);
  717. }
  718. return result;
  719. }
  720. // utils/base64-browser
  721. function decodeBase64(textData) {
  722. textData = atob(textData);
  723. const data = new Uint8Array(textData.length);
  724. for (let i = 0; i < textData.length; i++) {
  725. data[i] = textData.charCodeAt(i);
  726. }
  727. return getBytes(data);
  728. }
  729. function encodeBase64(_data) {
  730. const data = getBytes(_data);
  731. let textData = "";
  732. for (let i = 0; i < data.length; i++) {
  733. textData += String.fromCharCode(data[i]);
  734. }
  735. return btoa(textData);
  736. }
  737. /**
  738. * Events allow for applications to use the observer pattern, which
  739. * allows subscribing and publishing events, outside the normal
  740. * execution paths.
  741. *
  742. * @_section api/utils/events:Events [about-events]
  743. */
  744. /**
  745. * When an [[EventEmitterable]] triggers a [[Listener]], the
  746. * callback always ahas one additional argument passed, which is
  747. * an **EventPayload**.
  748. */
  749. class EventPayload {
  750. /**
  751. * The event filter.
  752. */
  753. filter;
  754. /**
  755. * The **EventEmitterable**.
  756. */
  757. emitter;
  758. #listener;
  759. /**
  760. * Create a new **EventPayload** for %%emitter%% with
  761. * the %%listener%% and for %%filter%%.
  762. */
  763. constructor(emitter, listener, filter) {
  764. this.#listener = listener;
  765. defineProperties(this, { emitter, filter });
  766. }
  767. /**
  768. * Unregister the triggered listener for future events.
  769. */
  770. async removeListener() {
  771. if (this.#listener == null) {
  772. return;
  773. }
  774. await this.emitter.off(this.filter, this.#listener);
  775. }
  776. }
  777. /**
  778. * Using strings in Ethereum (or any security-basd system) requires
  779. * additional care. These utilities attempt to mitigate some of the
  780. * safety issues as well as provide the ability to recover and analyse
  781. * strings.
  782. *
  783. * @_subsection api/utils:Strings and UTF-8 [about-strings]
  784. */
  785. function errorFunc(reason, offset, bytes, output, badCodepoint) {
  786. assertArgument(false, `invalid codepoint at offset ${offset}; ${reason}`, "bytes", bytes);
  787. }
  788. function ignoreFunc(reason, offset, bytes, output, badCodepoint) {
  789. // If there is an invalid prefix (including stray continuation), skip any additional continuation bytes
  790. if (reason === "BAD_PREFIX" || reason === "UNEXPECTED_CONTINUE") {
  791. let i = 0;
  792. for (let o = offset + 1; o < bytes.length; o++) {
  793. if (bytes[o] >> 6 !== 0x02) {
  794. break;
  795. }
  796. i++;
  797. }
  798. return i;
  799. }
  800. // This byte runs us past the end of the string, so just jump to the end
  801. // (but the first byte was read already read and therefore skipped)
  802. if (reason === "OVERRUN") {
  803. return bytes.length - offset - 1;
  804. }
  805. // Nothing to skip
  806. return 0;
  807. }
  808. function replaceFunc(reason, offset, bytes, output, badCodepoint) {
  809. // Overlong representations are otherwise "valid" code points; just non-deistingtished
  810. if (reason === "OVERLONG") {
  811. assertArgument(typeof (badCodepoint) === "number", "invalid bad code point for replacement", "badCodepoint", badCodepoint);
  812. output.push(badCodepoint);
  813. return 0;
  814. }
  815. // Put the replacement character into the output
  816. output.push(0xfffd);
  817. // Otherwise, process as if ignoring errors
  818. return ignoreFunc(reason, offset, bytes);
  819. }
  820. /**
  821. * A handful of popular, built-in UTF-8 error handling strategies.
  822. *
  823. * **``"error"``** - throws on ANY illegal UTF-8 sequence or
  824. * non-canonical (overlong) codepoints (this is the default)
  825. *
  826. * **``"ignore"``** - silently drops any illegal UTF-8 sequence
  827. * and accepts non-canonical (overlong) codepoints
  828. *
  829. * **``"replace"``** - replace any illegal UTF-8 sequence with the
  830. * UTF-8 replacement character (i.e. ``"\\ufffd"``) and accepts
  831. * non-canonical (overlong) codepoints
  832. *
  833. * @returns: Record<"error" | "ignore" | "replace", Utf8ErrorFunc>
  834. */
  835. const Utf8ErrorFuncs = Object.freeze({
  836. error: errorFunc,
  837. ignore: ignoreFunc,
  838. replace: replaceFunc
  839. });
  840. // http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499
  841. function getUtf8CodePoints(_bytes, onError) {
  842. if (onError == null) {
  843. onError = Utf8ErrorFuncs.error;
  844. }
  845. const bytes = getBytes(_bytes, "bytes");
  846. const result = [];
  847. let i = 0;
  848. // Invalid bytes are ignored
  849. while (i < bytes.length) {
  850. const c = bytes[i++];
  851. // 0xxx xxxx
  852. if (c >> 7 === 0) {
  853. result.push(c);
  854. continue;
  855. }
  856. // Multibyte; how many bytes left for this character?
  857. let extraLength = null;
  858. let overlongMask = null;
  859. // 110x xxxx 10xx xxxx
  860. if ((c & 0xe0) === 0xc0) {
  861. extraLength = 1;
  862. overlongMask = 0x7f;
  863. // 1110 xxxx 10xx xxxx 10xx xxxx
  864. }
  865. else if ((c & 0xf0) === 0xe0) {
  866. extraLength = 2;
  867. overlongMask = 0x7ff;
  868. // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx
  869. }
  870. else if ((c & 0xf8) === 0xf0) {
  871. extraLength = 3;
  872. overlongMask = 0xffff;
  873. }
  874. else {
  875. if ((c & 0xc0) === 0x80) {
  876. i += onError("UNEXPECTED_CONTINUE", i - 1, bytes, result);
  877. }
  878. else {
  879. i += onError("BAD_PREFIX", i - 1, bytes, result);
  880. }
  881. continue;
  882. }
  883. // Do we have enough bytes in our data?
  884. if (i - 1 + extraLength >= bytes.length) {
  885. i += onError("OVERRUN", i - 1, bytes, result);
  886. continue;
  887. }
  888. // Remove the length prefix from the char
  889. let res = c & ((1 << (8 - extraLength - 1)) - 1);
  890. for (let j = 0; j < extraLength; j++) {
  891. let nextChar = bytes[i];
  892. // Invalid continuation byte
  893. if ((nextChar & 0xc0) != 0x80) {
  894. i += onError("MISSING_CONTINUE", i, bytes, result);
  895. res = null;
  896. break;
  897. }
  898. res = (res << 6) | (nextChar & 0x3f);
  899. i++;
  900. }
  901. // See above loop for invalid continuation byte
  902. if (res === null) {
  903. continue;
  904. }
  905. // Maximum code point
  906. if (res > 0x10ffff) {
  907. i += onError("OUT_OF_RANGE", i - 1 - extraLength, bytes, result, res);
  908. continue;
  909. }
  910. // Reserved for UTF-16 surrogate halves
  911. if (res >= 0xd800 && res <= 0xdfff) {
  912. i += onError("UTF16_SURROGATE", i - 1 - extraLength, bytes, result, res);
  913. continue;
  914. }
  915. // Check for overlong sequences (more bytes than needed)
  916. if (res <= overlongMask) {
  917. i += onError("OVERLONG", i - 1 - extraLength, bytes, result, res);
  918. continue;
  919. }
  920. result.push(res);
  921. }
  922. return result;
  923. }
  924. // http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array
  925. /**
  926. * Returns the UTF-8 byte representation of %%str%%.
  927. *
  928. * If %%form%% is specified, the string is normalized.
  929. */
  930. function toUtf8Bytes(str, form) {
  931. assertArgument(typeof (str) === "string", "invalid string value", "str", str);
  932. if (form != null) {
  933. assertNormalize(form);
  934. str = str.normalize(form);
  935. }
  936. let result = [];
  937. for (let i = 0; i < str.length; i++) {
  938. const c = str.charCodeAt(i);
  939. if (c < 0x80) {
  940. result.push(c);
  941. }
  942. else if (c < 0x800) {
  943. result.push((c >> 6) | 0xc0);
  944. result.push((c & 0x3f) | 0x80);
  945. }
  946. else if ((c & 0xfc00) == 0xd800) {
  947. i++;
  948. const c2 = str.charCodeAt(i);
  949. assertArgument(i < str.length && ((c2 & 0xfc00) === 0xdc00), "invalid surrogate pair", "str", str);
  950. // Surrogate Pair
  951. const pair = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff);
  952. result.push((pair >> 18) | 0xf0);
  953. result.push(((pair >> 12) & 0x3f) | 0x80);
  954. result.push(((pair >> 6) & 0x3f) | 0x80);
  955. result.push((pair & 0x3f) | 0x80);
  956. }
  957. else {
  958. result.push((c >> 12) | 0xe0);
  959. result.push(((c >> 6) & 0x3f) | 0x80);
  960. result.push((c & 0x3f) | 0x80);
  961. }
  962. }
  963. return new Uint8Array(result);
  964. }
  965. //export
  966. function _toUtf8String(codePoints) {
  967. return codePoints.map((codePoint) => {
  968. if (codePoint <= 0xffff) {
  969. return String.fromCharCode(codePoint);
  970. }
  971. codePoint -= 0x10000;
  972. return String.fromCharCode((((codePoint >> 10) & 0x3ff) + 0xd800), ((codePoint & 0x3ff) + 0xdc00));
  973. }).join("");
  974. }
  975. /**
  976. * Returns the string represented by the UTF-8 data %%bytes%%.
  977. *
  978. * When %%onError%% function is specified, it is called on UTF-8
  979. * errors allowing recovery using the [[Utf8ErrorFunc]] API.
  980. * (default: [error](Utf8ErrorFuncs))
  981. */
  982. function toUtf8String(bytes, onError) {
  983. return _toUtf8String(getUtf8CodePoints(bytes, onError));
  984. }
  985. /**
  986. * Returns the UTF-8 code-points for %%str%%.
  987. *
  988. * If %%form%% is specified, the string is normalized.
  989. */
  990. function toUtf8CodePoints(str, form) {
  991. return getUtf8CodePoints(toUtf8Bytes(str, form));
  992. }
  993. function createGetUrl(options) {
  994. async function getUrl(req, _signal) {
  995. assert(_signal == null || !_signal.cancelled, "request cancelled before sending", "CANCELLED");
  996. const protocol = req.url.split(":")[0].toLowerCase();
  997. assert(protocol === "http" || protocol === "https", `unsupported protocol ${protocol}`, "UNSUPPORTED_OPERATION", {
  998. info: { protocol },
  999. operation: "request"
  1000. });
  1001. assert(protocol === "https" || !req.credentials || req.allowInsecureAuthentication, "insecure authorized connections unsupported", "UNSUPPORTED_OPERATION", {
  1002. operation: "request"
  1003. });
  1004. let error = null;
  1005. const controller = new AbortController();
  1006. const timer = setTimeout(() => {
  1007. error = makeError("request timeout", "TIMEOUT");
  1008. controller.abort();
  1009. }, req.timeout);
  1010. if (_signal) {
  1011. _signal.addListener(() => {
  1012. error = makeError("request cancelled", "CANCELLED");
  1013. controller.abort();
  1014. });
  1015. }
  1016. const init = {
  1017. method: req.method,
  1018. headers: new Headers(Array.from(req)),
  1019. body: req.body || undefined,
  1020. signal: controller.signal
  1021. };
  1022. let resp;
  1023. try {
  1024. resp = await fetch(req.url, init);
  1025. }
  1026. catch (_error) {
  1027. clearTimeout(timer);
  1028. if (error) {
  1029. throw error;
  1030. }
  1031. throw _error;
  1032. }
  1033. clearTimeout(timer);
  1034. const headers = {};
  1035. resp.headers.forEach((value, key) => {
  1036. headers[key.toLowerCase()] = value;
  1037. });
  1038. const respBody = await resp.arrayBuffer();
  1039. const body = (respBody == null) ? null : new Uint8Array(respBody);
  1040. return {
  1041. statusCode: resp.status,
  1042. statusMessage: resp.statusText,
  1043. headers, body
  1044. };
  1045. }
  1046. return getUrl;
  1047. }
  1048. /**
  1049. * Fetching content from the web is environment-specific, so Ethers
  1050. * provides an abstraction that each environment can implement to provide
  1051. * this service.
  1052. *
  1053. * On [Node.js](link-node), the ``http`` and ``https`` libs are used to
  1054. * create a request object, register event listeners and process data
  1055. * and populate the [[FetchResponse]].
  1056. *
  1057. * In a browser, the [DOM fetch](link-js-fetch) is used, and the resulting
  1058. * ``Promise`` is waited on to retrieve the payload.
  1059. *
  1060. * The [[FetchRequest]] is responsible for handling many common situations,
  1061. * such as redirects, server throttling, authentication, etc.
  1062. *
  1063. * It also handles common gateways, such as IPFS and data URIs.
  1064. *
  1065. * @_section api/utils/fetching:Fetching Web Content [about-fetch]
  1066. */
  1067. const MAX_ATTEMPTS = 12;
  1068. const SLOT_INTERVAL = 250;
  1069. // The global FetchGetUrlFunc implementation.
  1070. let defaultGetUrlFunc = createGetUrl();
  1071. const reData = new RegExp("^data:([^;:]*)?(;base64)?,(.*)$", "i");
  1072. const reIpfs = new RegExp("^ipfs:/\/(ipfs/)?(.*)$", "i");
  1073. // If locked, new Gateways cannot be added
  1074. let locked$5 = false;
  1075. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs
  1076. async function dataGatewayFunc(url, signal) {
  1077. try {
  1078. const match = url.match(reData);
  1079. if (!match) {
  1080. throw new Error("invalid data");
  1081. }
  1082. return new FetchResponse(200, "OK", {
  1083. "content-type": (match[1] || "text/plain"),
  1084. }, (match[2] ? decodeBase64(match[3]) : unpercent(match[3])));
  1085. }
  1086. catch (error) {
  1087. return new FetchResponse(599, "BAD REQUEST (invalid data: URI)", {}, null, new FetchRequest(url));
  1088. }
  1089. }
  1090. /**
  1091. * Returns a [[FetchGatewayFunc]] for fetching content from a standard
  1092. * IPFS gateway hosted at %%baseUrl%%.
  1093. */
  1094. function getIpfsGatewayFunc(baseUrl) {
  1095. async function gatewayIpfs(url, signal) {
  1096. try {
  1097. const match = url.match(reIpfs);
  1098. if (!match) {
  1099. throw new Error("invalid link");
  1100. }
  1101. return new FetchRequest(`${baseUrl}${match[2]}`);
  1102. }
  1103. catch (error) {
  1104. return new FetchResponse(599, "BAD REQUEST (invalid IPFS URI)", {}, null, new FetchRequest(url));
  1105. }
  1106. }
  1107. return gatewayIpfs;
  1108. }
  1109. const Gateways = {
  1110. "data": dataGatewayFunc,
  1111. "ipfs": getIpfsGatewayFunc("https:/\/gateway.ipfs.io/ipfs/")
  1112. };
  1113. const fetchSignals = new WeakMap();
  1114. /**
  1115. * @_ignore
  1116. */
  1117. class FetchCancelSignal {
  1118. #listeners;
  1119. #cancelled;
  1120. constructor(request) {
  1121. this.#listeners = [];
  1122. this.#cancelled = false;
  1123. fetchSignals.set(request, () => {
  1124. if (this.#cancelled) {
  1125. return;
  1126. }
  1127. this.#cancelled = true;
  1128. for (const listener of this.#listeners) {
  1129. setTimeout(() => { listener(); }, 0);
  1130. }
  1131. this.#listeners = [];
  1132. });
  1133. }
  1134. addListener(listener) {
  1135. assert(!this.#cancelled, "singal already cancelled", "UNSUPPORTED_OPERATION", {
  1136. operation: "fetchCancelSignal.addCancelListener"
  1137. });
  1138. this.#listeners.push(listener);
  1139. }
  1140. get cancelled() { return this.#cancelled; }
  1141. checkSignal() {
  1142. assert(!this.cancelled, "cancelled", "CANCELLED", {});
  1143. }
  1144. }
  1145. // Check the signal, throwing if it is cancelled
  1146. function checkSignal(signal) {
  1147. if (signal == null) {
  1148. throw new Error("missing signal; should not happen");
  1149. }
  1150. signal.checkSignal();
  1151. return signal;
  1152. }
  1153. /**
  1154. * Represents a request for a resource using a URI.
  1155. *
  1156. * By default, the supported schemes are ``HTTP``, ``HTTPS``, ``data:``,
  1157. * and ``IPFS:``.
  1158. *
  1159. * Additional schemes can be added globally using [[registerGateway]].
  1160. *
  1161. * @example:
  1162. * req = new FetchRequest("https://www.ricmoo.com")
  1163. * resp = await req.send()
  1164. * resp.body.length
  1165. * //_result:
  1166. */
  1167. class FetchRequest {
  1168. #allowInsecure;
  1169. #gzip;
  1170. #headers;
  1171. #method;
  1172. #timeout;
  1173. #url;
  1174. #body;
  1175. #bodyType;
  1176. #creds;
  1177. // Hooks
  1178. #preflight;
  1179. #process;
  1180. #retry;
  1181. #signal;
  1182. #throttle;
  1183. #getUrlFunc;
  1184. /**
  1185. * The fetch URL to request.
  1186. */
  1187. get url() { return this.#url; }
  1188. set url(url) {
  1189. this.#url = String(url);
  1190. }
  1191. /**
  1192. * The fetch body, if any, to send as the request body. //(default: null)//
  1193. *
  1194. * When setting a body, the intrinsic ``Content-Type`` is automatically
  1195. * set and will be used if **not overridden** by setting a custom
  1196. * header.
  1197. *
  1198. * If %%body%% is null, the body is cleared (along with the
  1199. * intrinsic ``Content-Type``).
  1200. *
  1201. * If %%body%% is a string, the intrinsic ``Content-Type`` is set to
  1202. * ``text/plain``.
  1203. *
  1204. * If %%body%% is a Uint8Array, the intrinsic ``Content-Type`` is set to
  1205. * ``application/octet-stream``.
  1206. *
  1207. * If %%body%% is any other object, the intrinsic ``Content-Type`` is
  1208. * set to ``application/json``.
  1209. */
  1210. get body() {
  1211. if (this.#body == null) {
  1212. return null;
  1213. }
  1214. return new Uint8Array(this.#body);
  1215. }
  1216. set body(body) {
  1217. if (body == null) {
  1218. this.#body = undefined;
  1219. this.#bodyType = undefined;
  1220. }
  1221. else if (typeof (body) === "string") {
  1222. this.#body = toUtf8Bytes(body);
  1223. this.#bodyType = "text/plain";
  1224. }
  1225. else if (body instanceof Uint8Array) {
  1226. this.#body = body;
  1227. this.#bodyType = "application/octet-stream";
  1228. }
  1229. else if (typeof (body) === "object") {
  1230. this.#body = toUtf8Bytes(JSON.stringify(body));
  1231. this.#bodyType = "application/json";
  1232. }
  1233. else {
  1234. throw new Error("invalid body");
  1235. }
  1236. }
  1237. /**
  1238. * Returns true if the request has a body.
  1239. */
  1240. hasBody() {
  1241. return (this.#body != null);
  1242. }
  1243. /**
  1244. * The HTTP method to use when requesting the URI. If no method
  1245. * has been explicitly set, then ``GET`` is used if the body is
  1246. * null and ``POST`` otherwise.
  1247. */
  1248. get method() {
  1249. if (this.#method) {
  1250. return this.#method;
  1251. }
  1252. if (this.hasBody()) {
  1253. return "POST";
  1254. }
  1255. return "GET";
  1256. }
  1257. set method(method) {
  1258. if (method == null) {
  1259. method = "";
  1260. }
  1261. this.#method = String(method).toUpperCase();
  1262. }
  1263. /**
  1264. * The headers that will be used when requesting the URI. All
  1265. * keys are lower-case.
  1266. *
  1267. * This object is a copy, so any changes will **NOT** be reflected
  1268. * in the ``FetchRequest``.
  1269. *
  1270. * To set a header entry, use the ``setHeader`` method.
  1271. */
  1272. get headers() {
  1273. const headers = Object.assign({}, this.#headers);
  1274. if (this.#creds) {
  1275. headers["authorization"] = `Basic ${encodeBase64(toUtf8Bytes(this.#creds))}`;
  1276. }
  1277. if (this.allowGzip) {
  1278. headers["accept-encoding"] = "gzip";
  1279. }
  1280. if (headers["content-type"] == null && this.#bodyType) {
  1281. headers["content-type"] = this.#bodyType;
  1282. }
  1283. if (this.body) {
  1284. headers["content-length"] = String(this.body.length);
  1285. }
  1286. return headers;
  1287. }
  1288. /**
  1289. * Get the header for %%key%%, ignoring case.
  1290. */
  1291. getHeader(key) {
  1292. return this.headers[key.toLowerCase()];
  1293. }
  1294. /**
  1295. * Set the header for %%key%% to %%value%%. All values are coerced
  1296. * to a string.
  1297. */
  1298. setHeader(key, value) {
  1299. this.#headers[String(key).toLowerCase()] = String(value);
  1300. }
  1301. /**
  1302. * Clear all headers, resetting all intrinsic headers.
  1303. */
  1304. clearHeaders() {
  1305. this.#headers = {};
  1306. }
  1307. [Symbol.iterator]() {
  1308. const headers = this.headers;
  1309. const keys = Object.keys(headers);
  1310. let index = 0;
  1311. return {
  1312. next: () => {
  1313. if (index < keys.length) {
  1314. const key = keys[index++];
  1315. return {
  1316. value: [key, headers[key]], done: false
  1317. };
  1318. }
  1319. return { value: undefined, done: true };
  1320. }
  1321. };
  1322. }
  1323. /**
  1324. * The value that will be sent for the ``Authorization`` header.
  1325. *
  1326. * To set the credentials, use the ``setCredentials`` method.
  1327. */
  1328. get credentials() {
  1329. return this.#creds || null;
  1330. }
  1331. /**
  1332. * Sets an ``Authorization`` for %%username%% with %%password%%.
  1333. */
  1334. setCredentials(username, password) {
  1335. assertArgument(!username.match(/:/), "invalid basic authentication username", "username", "[REDACTED]");
  1336. this.#creds = `${username}:${password}`;
  1337. }
  1338. /**
  1339. * Enable and request gzip-encoded responses. The response will
  1340. * automatically be decompressed. //(default: true)//
  1341. */
  1342. get allowGzip() {
  1343. return this.#gzip;
  1344. }
  1345. set allowGzip(value) {
  1346. this.#gzip = !!value;
  1347. }
  1348. /**
  1349. * Allow ``Authentication`` credentials to be sent over insecure
  1350. * channels. //(default: false)//
  1351. */
  1352. get allowInsecureAuthentication() {
  1353. return !!this.#allowInsecure;
  1354. }
  1355. set allowInsecureAuthentication(value) {
  1356. this.#allowInsecure = !!value;
  1357. }
  1358. /**
  1359. * The timeout (in milliseconds) to wait for a complete response.
  1360. * //(default: 5 minutes)//
  1361. */
  1362. get timeout() { return this.#timeout; }
  1363. set timeout(timeout) {
  1364. assertArgument(timeout >= 0, "timeout must be non-zero", "timeout", timeout);
  1365. this.#timeout = timeout;
  1366. }
  1367. /**
  1368. * This function is called prior to each request, for example
  1369. * during a redirection or retry in case of server throttling.
  1370. *
  1371. * This offers an opportunity to populate headers or update
  1372. * content before sending a request.
  1373. */
  1374. get preflightFunc() {
  1375. return this.#preflight || null;
  1376. }
  1377. set preflightFunc(preflight) {
  1378. this.#preflight = preflight;
  1379. }
  1380. /**
  1381. * This function is called after each response, offering an
  1382. * opportunity to provide client-level throttling or updating
  1383. * response data.
  1384. *
  1385. * Any error thrown in this causes the ``send()`` to throw.
  1386. *
  1387. * To schedule a retry attempt (assuming the maximum retry limit
  1388. * has not been reached), use [[response.throwThrottleError]].
  1389. */
  1390. get processFunc() {
  1391. return this.#process || null;
  1392. }
  1393. set processFunc(process) {
  1394. this.#process = process;
  1395. }
  1396. /**
  1397. * This function is called on each retry attempt.
  1398. */
  1399. get retryFunc() {
  1400. return this.#retry || null;
  1401. }
  1402. set retryFunc(retry) {
  1403. this.#retry = retry;
  1404. }
  1405. /**
  1406. * This function is called to fetch content from HTTP and
  1407. * HTTPS URLs and is platform specific (e.g. nodejs vs
  1408. * browsers).
  1409. *
  1410. * This is by default the currently registered global getUrl
  1411. * function, which can be changed using [[registerGetUrl]].
  1412. * If this has been set, setting is to ``null`` will cause
  1413. * this FetchRequest (and any future clones) to revert back to
  1414. * using the currently registered global getUrl function.
  1415. *
  1416. * Setting this is generally not necessary, but may be useful
  1417. * for developers that wish to intercept requests or to
  1418. * configurege a proxy or other agent.
  1419. */
  1420. get getUrlFunc() {
  1421. return this.#getUrlFunc || defaultGetUrlFunc;
  1422. }
  1423. set getUrlFunc(value) {
  1424. this.#getUrlFunc = value;
  1425. }
  1426. /**
  1427. * Create a new FetchRequest instance with default values.
  1428. *
  1429. * Once created, each property may be set before issuing a
  1430. * ``.send()`` to make the request.
  1431. */
  1432. constructor(url) {
  1433. this.#url = String(url);
  1434. this.#allowInsecure = false;
  1435. this.#gzip = true;
  1436. this.#headers = {};
  1437. this.#method = "";
  1438. this.#timeout = 300000;
  1439. this.#throttle = {
  1440. slotInterval: SLOT_INTERVAL,
  1441. maxAttempts: MAX_ATTEMPTS
  1442. };
  1443. this.#getUrlFunc = null;
  1444. }
  1445. toString() {
  1446. return `<FetchRequest method=${JSON.stringify(this.method)} url=${JSON.stringify(this.url)} headers=${JSON.stringify(this.headers)} body=${this.#body ? hexlify(this.#body) : "null"}>`;
  1447. }
  1448. /**
  1449. * Update the throttle parameters used to determine maximum
  1450. * attempts and exponential-backoff properties.
  1451. */
  1452. setThrottleParams(params) {
  1453. if (params.slotInterval != null) {
  1454. this.#throttle.slotInterval = params.slotInterval;
  1455. }
  1456. if (params.maxAttempts != null) {
  1457. this.#throttle.maxAttempts = params.maxAttempts;
  1458. }
  1459. }
  1460. async #send(attempt, expires, delay, _request, _response) {
  1461. if (attempt >= this.#throttle.maxAttempts) {
  1462. return _response.makeServerError("exceeded maximum retry limit");
  1463. }
  1464. assert(getTime$2() <= expires, "timeout", "TIMEOUT", {
  1465. operation: "request.send", reason: "timeout", request: _request
  1466. });
  1467. if (delay > 0) {
  1468. await wait(delay);
  1469. }
  1470. let req = this.clone();
  1471. const scheme = (req.url.split(":")[0] || "").toLowerCase();
  1472. // Process any Gateways
  1473. if (scheme in Gateways) {
  1474. const result = await Gateways[scheme](req.url, checkSignal(_request.#signal));
  1475. if (result instanceof FetchResponse) {
  1476. let response = result;
  1477. if (this.processFunc) {
  1478. checkSignal(_request.#signal);
  1479. try {
  1480. response = await this.processFunc(req, response);
  1481. }
  1482. catch (error) {
  1483. // Something went wrong during processing; throw a 5xx server error
  1484. if (error.throttle == null || typeof (error.stall) !== "number") {
  1485. response.makeServerError("error in post-processing function", error).assertOk();
  1486. }
  1487. // Ignore throttling
  1488. }
  1489. }
  1490. return response;
  1491. }
  1492. req = result;
  1493. }
  1494. // We have a preflight function; update the request
  1495. if (this.preflightFunc) {
  1496. req = await this.preflightFunc(req);
  1497. }
  1498. const resp = await this.getUrlFunc(req, checkSignal(_request.#signal));
  1499. let response = new FetchResponse(resp.statusCode, resp.statusMessage, resp.headers, resp.body, _request);
  1500. if (response.statusCode === 301 || response.statusCode === 302) {
  1501. // Redirect
  1502. try {
  1503. const location = response.headers.location || "";
  1504. return req.redirect(location).#send(attempt + 1, expires, 0, _request, response);
  1505. }
  1506. catch (error) { }
  1507. // Things won't get any better on another attempt; abort
  1508. return response;
  1509. }
  1510. else if (response.statusCode === 429) {
  1511. // Throttle
  1512. if (this.retryFunc == null || (await this.retryFunc(req, response, attempt))) {
  1513. const retryAfter = response.headers["retry-after"];
  1514. let delay = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt));
  1515. if (typeof (retryAfter) === "string" && retryAfter.match(/^[1-9][0-9]*$/)) {
  1516. delay = parseInt(retryAfter);
  1517. }
  1518. return req.clone().#send(attempt + 1, expires, delay, _request, response);
  1519. }
  1520. }
  1521. if (this.processFunc) {
  1522. checkSignal(_request.#signal);
  1523. try {
  1524. response = await this.processFunc(req, response);
  1525. }
  1526. catch (error) {
  1527. // Something went wrong during processing; throw a 5xx server error
  1528. if (error.throttle == null || typeof (error.stall) !== "number") {
  1529. response.makeServerError("error in post-processing function", error).assertOk();
  1530. }
  1531. // Throttle
  1532. let delay = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt));
  1533. if (error.stall >= 0) {
  1534. delay = error.stall;
  1535. }
  1536. return req.clone().#send(attempt + 1, expires, delay, _request, response);
  1537. }
  1538. }
  1539. return response;
  1540. }
  1541. /**
  1542. * Resolves to the response by sending the request.
  1543. */
  1544. send() {
  1545. assert(this.#signal == null, "request already sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.send" });
  1546. this.#signal = new FetchCancelSignal(this);
  1547. return this.#send(0, getTime$2() + this.timeout, 0, this, new FetchResponse(0, "", {}, null, this));
  1548. }
  1549. /**
  1550. * Cancels the inflight response, causing a ``CANCELLED``
  1551. * error to be rejected from the [[send]].
  1552. */
  1553. cancel() {
  1554. assert(this.#signal != null, "request has not been sent", "UNSUPPORTED_OPERATION", { operation: "fetchRequest.cancel" });
  1555. const signal = fetchSignals.get(this);
  1556. if (!signal) {
  1557. throw new Error("missing signal; should not happen");
  1558. }
  1559. signal();
  1560. }
  1561. /**
  1562. * Returns a new [[FetchRequest]] that represents the redirection
  1563. * to %%location%%.
  1564. */
  1565. redirect(location) {
  1566. // Redirection; for now we only support absolute locations
  1567. const current = this.url.split(":")[0].toLowerCase();
  1568. const target = location.split(":")[0].toLowerCase();
  1569. // Don't allow redirecting:
  1570. // - non-GET requests
  1571. // - downgrading the security (e.g. https => http)
  1572. // - to non-HTTP (or non-HTTPS) protocols [this could be relaxed?]
  1573. assert(this.method === "GET" && (current !== "https" || target !== "http") && location.match(/^https?:/), `unsupported redirect`, "UNSUPPORTED_OPERATION", {
  1574. operation: `redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(location)})`
  1575. });
  1576. // Create a copy of this request, with a new URL
  1577. const req = new FetchRequest(location);
  1578. req.method = "GET";
  1579. req.allowGzip = this.allowGzip;
  1580. req.timeout = this.timeout;
  1581. req.#headers = Object.assign({}, this.#headers);
  1582. if (this.#body) {
  1583. req.#body = new Uint8Array(this.#body);
  1584. }
  1585. req.#bodyType = this.#bodyType;
  1586. // Do not forward credentials unless on the same domain; only absolute
  1587. //req.allowInsecure = false;
  1588. // paths are currently supported; may want a way to specify to forward?
  1589. //setStore(req.#props, "creds", getStore(this.#pros, "creds"));
  1590. return req;
  1591. }
  1592. /**
  1593. * Create a new copy of this request.
  1594. */
  1595. clone() {
  1596. const clone = new FetchRequest(this.url);
  1597. // Preserve "default method" (i.e. null)
  1598. clone.#method = this.#method;
  1599. // Preserve "default body" with type, copying the Uint8Array is present
  1600. if (this.#body) {
  1601. clone.#body = this.#body;
  1602. }
  1603. clone.#bodyType = this.#bodyType;
  1604. // Preserve "default headers"
  1605. clone.#headers = Object.assign({}, this.#headers);
  1606. // Credentials is readonly, so we copy internally
  1607. clone.#creds = this.#creds;
  1608. if (this.allowGzip) {
  1609. clone.allowGzip = true;
  1610. }
  1611. clone.timeout = this.timeout;
  1612. if (this.allowInsecureAuthentication) {
  1613. clone.allowInsecureAuthentication = true;
  1614. }
  1615. clone.#preflight = this.#preflight;
  1616. clone.#process = this.#process;
  1617. clone.#retry = this.#retry;
  1618. clone.#throttle = Object.assign({}, this.#throttle);
  1619. clone.#getUrlFunc = this.#getUrlFunc;
  1620. return clone;
  1621. }
  1622. /**
  1623. * Locks all static configuration for gateways and FetchGetUrlFunc
  1624. * registration.
  1625. */
  1626. static lockConfig() {
  1627. locked$5 = true;
  1628. }
  1629. /**
  1630. * Get the current Gateway function for %%scheme%%.
  1631. */
  1632. static getGateway(scheme) {
  1633. return Gateways[scheme.toLowerCase()] || null;
  1634. }
  1635. /**
  1636. * Use the %%func%% when fetching URIs using %%scheme%%.
  1637. *
  1638. * This method affects all requests globally.
  1639. *
  1640. * If [[lockConfig]] has been called, no change is made and this
  1641. * throws.
  1642. */
  1643. static registerGateway(scheme, func) {
  1644. scheme = scheme.toLowerCase();
  1645. if (scheme === "http" || scheme === "https") {
  1646. throw new Error(`cannot intercept ${scheme}; use registerGetUrl`);
  1647. }
  1648. if (locked$5) {
  1649. throw new Error("gateways locked");
  1650. }
  1651. Gateways[scheme] = func;
  1652. }
  1653. /**
  1654. * Use %%getUrl%% when fetching URIs over HTTP and HTTPS requests.
  1655. *
  1656. * This method affects all requests globally.
  1657. *
  1658. * If [[lockConfig]] has been called, no change is made and this
  1659. * throws.
  1660. */
  1661. static registerGetUrl(getUrl) {
  1662. if (locked$5) {
  1663. throw new Error("gateways locked");
  1664. }
  1665. defaultGetUrlFunc = getUrl;
  1666. }
  1667. /**
  1668. * Creates a getUrl function that fetches content from HTTP and
  1669. * HTTPS URLs.
  1670. *
  1671. * The available %%options%% are dependent on the platform
  1672. * implementation of the default getUrl function.
  1673. *
  1674. * This is not generally something that is needed, but is useful
  1675. * when trying to customize simple behaviour when fetching HTTP
  1676. * content.
  1677. */
  1678. static createGetUrlFunc(options) {
  1679. return createGetUrl();
  1680. }
  1681. /**
  1682. * Creates a function that can "fetch" data URIs.
  1683. *
  1684. * Note that this is automatically done internally to support
  1685. * data URIs, so it is not necessary to register it.
  1686. *
  1687. * This is not generally something that is needed, but may
  1688. * be useful in a wrapper to perfom custom data URI functionality.
  1689. */
  1690. static createDataGateway() {
  1691. return dataGatewayFunc;
  1692. }
  1693. /**
  1694. * Creates a function that will fetch IPFS (unvalidated) from
  1695. * a custom gateway baseUrl.
  1696. *
  1697. * The default IPFS gateway used internally is
  1698. * ``"https:/\/gateway.ipfs.io/ipfs/"``.
  1699. */
  1700. static createIpfsGatewayFunc(baseUrl) {
  1701. return getIpfsGatewayFunc(baseUrl);
  1702. }
  1703. }
  1704. /**
  1705. * The response for a FetchRequest.
  1706. */
  1707. class FetchResponse {
  1708. #statusCode;
  1709. #statusMessage;
  1710. #headers;
  1711. #body;
  1712. #request;
  1713. #error;
  1714. toString() {
  1715. return `<FetchResponse status=${this.statusCode} body=${this.#body ? hexlify(this.#body) : "null"}>`;
  1716. }
  1717. /**
  1718. * The response status code.
  1719. */
  1720. get statusCode() { return this.#statusCode; }
  1721. /**
  1722. * The response status message.
  1723. */
  1724. get statusMessage() { return this.#statusMessage; }
  1725. /**
  1726. * The response headers. All keys are lower-case.
  1727. */
  1728. get headers() { return Object.assign({}, this.#headers); }
  1729. /**
  1730. * The response body, or ``null`` if there was no body.
  1731. */
  1732. get body() {
  1733. return (this.#body == null) ? null : new Uint8Array(this.#body);
  1734. }
  1735. /**
  1736. * The response body as a UTF-8 encoded string, or the empty
  1737. * string (i.e. ``""``) if there was no body.
  1738. *
  1739. * An error is thrown if the body is invalid UTF-8 data.
  1740. */
  1741. get bodyText() {
  1742. try {
  1743. return (this.#body == null) ? "" : toUtf8String(this.#body);
  1744. }
  1745. catch (error) {
  1746. assert(false, "response body is not valid UTF-8 data", "UNSUPPORTED_OPERATION", {
  1747. operation: "bodyText", info: { response: this }
  1748. });
  1749. }
  1750. }
  1751. /**
  1752. * The response body, decoded as JSON.
  1753. *
  1754. * An error is thrown if the body is invalid JSON-encoded data
  1755. * or if there was no body.
  1756. */
  1757. get bodyJson() {
  1758. try {
  1759. return JSON.parse(this.bodyText);
  1760. }
  1761. catch (error) {
  1762. assert(false, "response body is not valid JSON", "UNSUPPORTED_OPERATION", {
  1763. operation: "bodyJson", info: { response: this }
  1764. });
  1765. }
  1766. }
  1767. [Symbol.iterator]() {
  1768. const headers = this.headers;
  1769. const keys = Object.keys(headers);
  1770. let index = 0;
  1771. return {
  1772. next: () => {
  1773. if (index < keys.length) {
  1774. const key = keys[index++];
  1775. return {
  1776. value: [key, headers[key]], done: false
  1777. };
  1778. }
  1779. return { value: undefined, done: true };
  1780. }
  1781. };
  1782. }
  1783. constructor(statusCode, statusMessage, headers, body, request) {
  1784. this.#statusCode = statusCode;
  1785. this.#statusMessage = statusMessage;
  1786. this.#headers = Object.keys(headers).reduce((accum, k) => {
  1787. accum[k.toLowerCase()] = String(headers[k]);
  1788. return accum;
  1789. }, {});
  1790. this.#body = ((body == null) ? null : new Uint8Array(body));
  1791. this.#request = (request || null);
  1792. this.#error = { message: "" };
  1793. }
  1794. /**
  1795. * Return a Response with matching headers and body, but with
  1796. * an error status code (i.e. 599) and %%message%% with an
  1797. * optional %%error%%.
  1798. */
  1799. makeServerError(message, error) {
  1800. let statusMessage;
  1801. if (!message) {
  1802. message = `${this.statusCode} ${this.statusMessage}`;
  1803. statusMessage = `CLIENT ESCALATED SERVER ERROR (${message})`;
  1804. }
  1805. else {
  1806. statusMessage = `CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${message})`;
  1807. }
  1808. const response = new FetchResponse(599, statusMessage, this.headers, this.body, this.#request || undefined);
  1809. response.#error = { message, error };
  1810. return response;
  1811. }
  1812. /**
  1813. * If called within a [request.processFunc](FetchRequest-processFunc)
  1814. * call, causes the request to retry as if throttled for %%stall%%
  1815. * milliseconds.
  1816. */
  1817. throwThrottleError(message, stall) {
  1818. if (stall == null) {
  1819. stall = -1;
  1820. }
  1821. else {
  1822. assertArgument(Number.isInteger(stall) && stall >= 0, "invalid stall timeout", "stall", stall);
  1823. }
  1824. const error = new Error(message || "throttling requests");
  1825. defineProperties(error, { stall, throttle: true });
  1826. throw error;
  1827. }
  1828. /**
  1829. * Get the header value for %%key%%, ignoring case.
  1830. */
  1831. getHeader(key) {
  1832. return this.headers[key.toLowerCase()];
  1833. }
  1834. /**
  1835. * Returns true if the response has a body.
  1836. */
  1837. hasBody() {
  1838. return (this.#body != null);
  1839. }
  1840. /**
  1841. * The request made for this response.
  1842. */
  1843. get request() { return this.#request; }
  1844. /**
  1845. * Returns true if this response was a success statusCode.
  1846. */
  1847. ok() {
  1848. return (this.#error.message === "" && this.statusCode >= 200 && this.statusCode < 300);
  1849. }
  1850. /**
  1851. * Throws a ``SERVER_ERROR`` if this response is not ok.
  1852. */
  1853. assertOk() {
  1854. if (this.ok()) {
  1855. return;
  1856. }
  1857. let { message, error } = this.#error;
  1858. if (message === "") {
  1859. message = `server response ${this.statusCode} ${this.statusMessage}`;
  1860. }
  1861. let requestUrl = null;
  1862. if (this.request) {
  1863. requestUrl = this.request.url;
  1864. }
  1865. let responseBody = null;
  1866. try {
  1867. if (this.#body) {
  1868. responseBody = toUtf8String(this.#body);
  1869. }
  1870. }
  1871. catch (e) { }
  1872. assert(false, message, "SERVER_ERROR", {
  1873. request: (this.request || "unknown request"), response: this, error,
  1874. info: {
  1875. requestUrl, responseBody,
  1876. responseStatus: `${this.statusCode} ${this.statusMessage}`
  1877. }
  1878. });
  1879. }
  1880. }
  1881. function getTime$2() { return (new Date()).getTime(); }
  1882. function unpercent(value) {
  1883. return toUtf8Bytes(value.replace(/%([0-9a-f][0-9a-f])/gi, (all, code) => {
  1884. return String.fromCharCode(parseInt(code, 16));
  1885. }));
  1886. }
  1887. function wait(delay) {
  1888. return new Promise((resolve) => setTimeout(resolve, delay));
  1889. }
  1890. /**
  1891. * The **FixedNumber** class permits using values with decimal places,
  1892. * using fixed-pont math.
  1893. *
  1894. * Fixed-point math is still based on integers under-the-hood, but uses an
  1895. * internal offset to store fractional components below, and each operation
  1896. * corrects for this after each operation.
  1897. *
  1898. * @_section: api/utils/fixed-point-math:Fixed-Point Maths [about-fixed-point-math]
  1899. */
  1900. const BN_N1 = BigInt(-1);
  1901. const BN_0$8 = BigInt(0);
  1902. const BN_1$4 = BigInt(1);
  1903. const BN_5 = BigInt(5);
  1904. const _guard$5 = {};
  1905. // Constant to pull zeros from for multipliers
  1906. let Zeros$1 = "0000";
  1907. while (Zeros$1.length < 80) {
  1908. Zeros$1 += Zeros$1;
  1909. }
  1910. // Returns a string "1" followed by decimal "0"s
  1911. function getTens(decimals) {
  1912. let result = Zeros$1;
  1913. while (result.length < decimals) {
  1914. result += result;
  1915. }
  1916. return BigInt("1" + result.substring(0, decimals));
  1917. }
  1918. function checkValue(val, format, safeOp) {
  1919. const width = BigInt(format.width);
  1920. if (format.signed) {
  1921. const limit = (BN_1$4 << (width - BN_1$4));
  1922. assert(safeOp == null || (val >= -limit && val < limit), "overflow", "NUMERIC_FAULT", {
  1923. operation: safeOp, fault: "overflow", value: val
  1924. });
  1925. if (val > BN_0$8) {
  1926. val = fromTwos(mask(val, width), width);
  1927. }
  1928. else {
  1929. val = -fromTwos(mask(-val, width), width);
  1930. }
  1931. }
  1932. else {
  1933. const limit = (BN_1$4 << width);
  1934. assert(safeOp == null || (val >= 0 && val < limit), "overflow", "NUMERIC_FAULT", {
  1935. operation: safeOp, fault: "overflow", value: val
  1936. });
  1937. val = (((val % limit) + limit) % limit) & (limit - BN_1$4);
  1938. }
  1939. return val;
  1940. }
  1941. function getFormat(value) {
  1942. if (typeof (value) === "number") {
  1943. value = `fixed128x${value}`;
  1944. }
  1945. let signed = true;
  1946. let width = 128;
  1947. let decimals = 18;
  1948. if (typeof (value) === "string") {
  1949. // Parse the format string
  1950. if (value === "fixed") ;
  1951. else if (value === "ufixed") {
  1952. signed = false;
  1953. }
  1954. else {
  1955. const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);
  1956. assertArgument(match, "invalid fixed format", "format", value);
  1957. signed = (match[1] !== "u");
  1958. width = parseInt(match[2]);
  1959. decimals = parseInt(match[3]);
  1960. }
  1961. }
  1962. else if (value) {
  1963. // Extract the values from the object
  1964. const v = value;
  1965. const check = (key, type, defaultValue) => {
  1966. if (v[key] == null) {
  1967. return defaultValue;
  1968. }
  1969. assertArgument(typeof (v[key]) === type, "invalid fixed format (" + key + " not " + type + ")", "format." + key, v[key]);
  1970. return v[key];
  1971. };
  1972. signed = check("signed", "boolean", signed);
  1973. width = check("width", "number", width);
  1974. decimals = check("decimals", "number", decimals);
  1975. }
  1976. assertArgument((width % 8) === 0, "invalid FixedNumber width (not byte aligned)", "format.width", width);
  1977. assertArgument(decimals <= 80, "invalid FixedNumber decimals (too large)", "format.decimals", decimals);
  1978. const name = (signed ? "" : "u") + "fixed" + String(width) + "x" + String(decimals);
  1979. return { signed, width, decimals, name };
  1980. }
  1981. function toString(val, decimals) {
  1982. let negative = "";
  1983. if (val < BN_0$8) {
  1984. negative = "-";
  1985. val *= BN_N1;
  1986. }
  1987. let str = val.toString();
  1988. // No decimal point for whole values
  1989. if (decimals === 0) {
  1990. return (negative + str);
  1991. }
  1992. // Pad out to the whole component (including a whole digit)
  1993. while (str.length <= decimals) {
  1994. str = Zeros$1 + str;
  1995. }
  1996. // Insert the decimal point
  1997. const index = str.length - decimals;
  1998. str = str.substring(0, index) + "." + str.substring(index);
  1999. // Trim the whole component (leaving at least one 0)
  2000. while (str[0] === "0" && str[1] !== ".") {
  2001. str = str.substring(1);
  2002. }
  2003. // Trim the decimal component (leaving at least one 0)
  2004. while (str[str.length - 1] === "0" && str[str.length - 2] !== ".") {
  2005. str = str.substring(0, str.length - 1);
  2006. }
  2007. return (negative + str);
  2008. }
  2009. /**
  2010. * A FixedNumber represents a value over its [[FixedFormat]]
  2011. * arithmetic field.
  2012. *
  2013. * A FixedNumber can be used to perform math, losslessly, on
  2014. * values which have decmial places.
  2015. *
  2016. * A FixedNumber has a fixed bit-width to store values in, and stores all
  2017. * values internally by multiplying the value by 10 raised to the power of
  2018. * %%decimals%%.
  2019. *
  2020. * If operations are performed that cause a value to grow too high (close to
  2021. * positive infinity) or too low (close to negative infinity), the value
  2022. * is said to //overflow//.
  2023. *
  2024. * For example, an 8-bit signed value, with 0 decimals may only be within
  2025. * the range ``-128`` to ``127``; so ``-128 - 1`` will overflow and become
  2026. * ``127``. Likewise, ``127 + 1`` will overflow and become ``-127``.
  2027. *
  2028. * Many operation have a normal and //unsafe// variant. The normal variant
  2029. * will throw a [[NumericFaultError]] on any overflow, while the //unsafe//
  2030. * variant will silently allow overflow, corrupting its value value.
  2031. *
  2032. * If operations are performed that cause a value to become too small
  2033. * (close to zero), the value loses precison and is said to //underflow//.
  2034. *
  2035. * For example, an value with 1 decimal place may store a number as small
  2036. * as ``0.1``, but the value of ``0.1 / 2`` is ``0.05``, which cannot fit
  2037. * into 1 decimal place, so underflow occurs which means precision is lost
  2038. * and the value becomes ``0``.
  2039. *
  2040. * Some operations have a normal and //signalling// variant. The normal
  2041. * variant will silently ignore underflow, while the //signalling// variant
  2042. * will thow a [[NumericFaultError]] on underflow.
  2043. */
  2044. class FixedNumber {
  2045. /**
  2046. * The specific fixed-point arithmetic field for this value.
  2047. */
  2048. format;
  2049. #format;
  2050. // The actual value (accounting for decimals)
  2051. #val;
  2052. // A base-10 value to multiple values by to maintain the magnitude
  2053. #tens;
  2054. /**
  2055. * This is a property so console.log shows a human-meaningful value.
  2056. *
  2057. * @private
  2058. */
  2059. _value;
  2060. // Use this when changing this file to get some typing info,
  2061. // but then switch to any to mask the internal type
  2062. //constructor(guard: any, value: bigint, format: _FixedFormat) {
  2063. /**
  2064. * @private
  2065. */
  2066. constructor(guard, value, format) {
  2067. assertPrivate(guard, _guard$5, "FixedNumber");
  2068. this.#val = value;
  2069. this.#format = format;
  2070. const _value = toString(value, format.decimals);
  2071. defineProperties(this, { format: format.name, _value });
  2072. this.#tens = getTens(format.decimals);
  2073. }
  2074. /**
  2075. * If true, negative values are permitted, otherwise only
  2076. * positive values and zero are allowed.
  2077. */
  2078. get signed() { return this.#format.signed; }
  2079. /**
  2080. * The number of bits available to store the value.
  2081. */
  2082. get width() { return this.#format.width; }
  2083. /**
  2084. * The number of decimal places in the fixed-point arithment field.
  2085. */
  2086. get decimals() { return this.#format.decimals; }
  2087. /**
  2088. * The value as an integer, based on the smallest unit the
  2089. * [[decimals]] allow.
  2090. */
  2091. get value() { return this.#val; }
  2092. #checkFormat(other) {
  2093. assertArgument(this.format === other.format, "incompatible format; use fixedNumber.toFormat", "other", other);
  2094. }
  2095. #checkValue(val, safeOp) {
  2096. /*
  2097. const width = BigInt(this.width);
  2098. if (this.signed) {
  2099. const limit = (BN_1 << (width - BN_1));
  2100. assert(safeOp == null || (val >= -limit && val < limit), "overflow", "NUMERIC_FAULT", {
  2101. operation: <string>safeOp, fault: "overflow", value: val
  2102. });
  2103. if (val > BN_0) {
  2104. val = fromTwos(mask(val, width), width);
  2105. } else {
  2106. val = -fromTwos(mask(-val, width), width);
  2107. }
  2108. } else {
  2109. const masked = mask(val, width);
  2110. assert(safeOp == null || (val >= 0 && val === masked), "overflow", "NUMERIC_FAULT", {
  2111. operation: <string>safeOp, fault: "overflow", value: val
  2112. });
  2113. val = masked;
  2114. }
  2115. */
  2116. val = checkValue(val, this.#format, safeOp);
  2117. return new FixedNumber(_guard$5, val, this.#format);
  2118. }
  2119. #add(o, safeOp) {
  2120. this.#checkFormat(o);
  2121. return this.#checkValue(this.#val + o.#val, safeOp);
  2122. }
  2123. /**
  2124. * Returns a new [[FixedNumber]] with the result of %%this%% added
  2125. * to %%other%%, ignoring overflow.
  2126. */
  2127. addUnsafe(other) { return this.#add(other); }
  2128. /**
  2129. * Returns a new [[FixedNumber]] with the result of %%this%% added
  2130. * to %%other%%. A [[NumericFaultError]] is thrown if overflow
  2131. * occurs.
  2132. */
  2133. add(other) { return this.#add(other, "add"); }
  2134. #sub(o, safeOp) {
  2135. this.#checkFormat(o);
  2136. return this.#checkValue(this.#val - o.#val, safeOp);
  2137. }
  2138. /**
  2139. * Returns a new [[FixedNumber]] with the result of %%other%% subtracted
  2140. * from %%this%%, ignoring overflow.
  2141. */
  2142. subUnsafe(other) { return this.#sub(other); }
  2143. /**
  2144. * Returns a new [[FixedNumber]] with the result of %%other%% subtracted
  2145. * from %%this%%. A [[NumericFaultError]] is thrown if overflow
  2146. * occurs.
  2147. */
  2148. sub(other) { return this.#sub(other, "sub"); }
  2149. #mul(o, safeOp) {
  2150. this.#checkFormat(o);
  2151. return this.#checkValue((this.#val * o.#val) / this.#tens, safeOp);
  2152. }
  2153. /**
  2154. * Returns a new [[FixedNumber]] with the result of %%this%% multiplied
  2155. * by %%other%%, ignoring overflow and underflow (precision loss).
  2156. */
  2157. mulUnsafe(other) { return this.#mul(other); }
  2158. /**
  2159. * Returns a new [[FixedNumber]] with the result of %%this%% multiplied
  2160. * by %%other%%. A [[NumericFaultError]] is thrown if overflow
  2161. * occurs.
  2162. */
  2163. mul(other) { return this.#mul(other, "mul"); }
  2164. /**
  2165. * Returns a new [[FixedNumber]] with the result of %%this%% multiplied
  2166. * by %%other%%. A [[NumericFaultError]] is thrown if overflow
  2167. * occurs or if underflow (precision loss) occurs.
  2168. */
  2169. mulSignal(other) {
  2170. this.#checkFormat(other);
  2171. const value = this.#val * other.#val;
  2172. assert((value % this.#tens) === BN_0$8, "precision lost during signalling mul", "NUMERIC_FAULT", {
  2173. operation: "mulSignal", fault: "underflow", value: this
  2174. });
  2175. return this.#checkValue(value / this.#tens, "mulSignal");
  2176. }
  2177. #div(o, safeOp) {
  2178. assert(o.#val !== BN_0$8, "division by zero", "NUMERIC_FAULT", {
  2179. operation: "div", fault: "divide-by-zero", value: this
  2180. });
  2181. this.#checkFormat(o);
  2182. return this.#checkValue((this.#val * this.#tens) / o.#val, safeOp);
  2183. }
  2184. /**
  2185. * Returns a new [[FixedNumber]] with the result of %%this%% divided
  2186. * by %%other%%, ignoring underflow (precision loss). A
  2187. * [[NumericFaultError]] is thrown if overflow occurs.
  2188. */
  2189. divUnsafe(other) { return this.#div(other); }
  2190. /**
  2191. * Returns a new [[FixedNumber]] with the result of %%this%% divided
  2192. * by %%other%%, ignoring underflow (precision loss). A
  2193. * [[NumericFaultError]] is thrown if overflow occurs.
  2194. */
  2195. div(other) { return this.#div(other, "div"); }
  2196. /**
  2197. * Returns a new [[FixedNumber]] with the result of %%this%% divided
  2198. * by %%other%%. A [[NumericFaultError]] is thrown if underflow
  2199. * (precision loss) occurs.
  2200. */
  2201. divSignal(other) {
  2202. assert(other.#val !== BN_0$8, "division by zero", "NUMERIC_FAULT", {
  2203. operation: "div", fault: "divide-by-zero", value: this
  2204. });
  2205. this.#checkFormat(other);
  2206. const value = (this.#val * this.#tens);
  2207. assert((value % other.#val) === BN_0$8, "precision lost during signalling div", "NUMERIC_FAULT", {
  2208. operation: "divSignal", fault: "underflow", value: this
  2209. });
  2210. return this.#checkValue(value / other.#val, "divSignal");
  2211. }
  2212. /**
  2213. * Returns a comparison result between %%this%% and %%other%%.
  2214. *
  2215. * This is suitable for use in sorting, where ``-1`` implies %%this%%
  2216. * is smaller, ``1`` implies %%this%% is larger and ``0`` implies
  2217. * both are equal.
  2218. */
  2219. cmp(other) {
  2220. let a = this.value, b = other.value;
  2221. // Coerce a and b to the same magnitude
  2222. const delta = this.decimals - other.decimals;
  2223. if (delta > 0) {
  2224. b *= getTens(delta);
  2225. }
  2226. else if (delta < 0) {
  2227. a *= getTens(-delta);
  2228. }
  2229. // Comnpare
  2230. if (a < b) {
  2231. return -1;
  2232. }
  2233. if (a > b) {
  2234. return 1;
  2235. }
  2236. return 0;
  2237. }
  2238. /**
  2239. * Returns true if %%other%% is equal to %%this%%.
  2240. */
  2241. eq(other) { return this.cmp(other) === 0; }
  2242. /**
  2243. * Returns true if %%other%% is less than to %%this%%.
  2244. */
  2245. lt(other) { return this.cmp(other) < 0; }
  2246. /**
  2247. * Returns true if %%other%% is less than or equal to %%this%%.
  2248. */
  2249. lte(other) { return this.cmp(other) <= 0; }
  2250. /**
  2251. * Returns true if %%other%% is greater than to %%this%%.
  2252. */
  2253. gt(other) { return this.cmp(other) > 0; }
  2254. /**
  2255. * Returns true if %%other%% is greater than or equal to %%this%%.
  2256. */
  2257. gte(other) { return this.cmp(other) >= 0; }
  2258. /**
  2259. * Returns a new [[FixedNumber]] which is the largest **integer**
  2260. * that is less than or equal to %%this%%.
  2261. *
  2262. * The decimal component of the result will always be ``0``.
  2263. */
  2264. floor() {
  2265. let val = this.#val;
  2266. if (this.#val < BN_0$8) {
  2267. val -= this.#tens - BN_1$4;
  2268. }
  2269. val = (this.#val / this.#tens) * this.#tens;
  2270. return this.#checkValue(val, "floor");
  2271. }
  2272. /**
  2273. * Returns a new [[FixedNumber]] which is the smallest **integer**
  2274. * that is greater than or equal to %%this%%.
  2275. *
  2276. * The decimal component of the result will always be ``0``.
  2277. */
  2278. ceiling() {
  2279. let val = this.#val;
  2280. if (this.#val > BN_0$8) {
  2281. val += this.#tens - BN_1$4;
  2282. }
  2283. val = (this.#val / this.#tens) * this.#tens;
  2284. return this.#checkValue(val, "ceiling");
  2285. }
  2286. /**
  2287. * Returns a new [[FixedNumber]] with the decimal component
  2288. * rounded up on ties at %%decimals%% places.
  2289. */
  2290. round(decimals) {
  2291. if (decimals == null) {
  2292. decimals = 0;
  2293. }
  2294. // Not enough precision to not already be rounded
  2295. if (decimals >= this.decimals) {
  2296. return this;
  2297. }
  2298. const delta = this.decimals - decimals;
  2299. const bump = BN_5 * getTens(delta - 1);
  2300. let value = this.value + bump;
  2301. const tens = getTens(delta);
  2302. value = (value / tens) * tens;
  2303. checkValue(value, this.#format, "round");
  2304. return new FixedNumber(_guard$5, value, this.#format);
  2305. }
  2306. /**
  2307. * Returns true if %%this%% is equal to ``0``.
  2308. */
  2309. isZero() { return (this.#val === BN_0$8); }
  2310. /**
  2311. * Returns true if %%this%% is less than ``0``.
  2312. */
  2313. isNegative() { return (this.#val < BN_0$8); }
  2314. /**
  2315. * Returns the string representation of %%this%%.
  2316. */
  2317. toString() { return this._value; }
  2318. /**
  2319. * Returns a float approximation.
  2320. *
  2321. * Due to IEEE 754 precission (or lack thereof), this function
  2322. * can only return an approximation and most values will contain
  2323. * rounding errors.
  2324. */
  2325. toUnsafeFloat() { return parseFloat(this.toString()); }
  2326. /**
  2327. * Return a new [[FixedNumber]] with the same value but has had
  2328. * its field set to %%format%%.
  2329. *
  2330. * This will throw if the value cannot fit into %%format%%.
  2331. */
  2332. toFormat(format) {
  2333. return FixedNumber.fromString(this.toString(), format);
  2334. }
  2335. /**
  2336. * Creates a new [[FixedNumber]] for %%value%% divided by
  2337. * %%decimal%% places with %%format%%.
  2338. *
  2339. * This will throw a [[NumericFaultError]] if %%value%% (once adjusted
  2340. * for %%decimals%%) cannot fit in %%format%%, either due to overflow
  2341. * or underflow (precision loss).
  2342. */
  2343. static fromValue(_value, _decimals, _format) {
  2344. const decimals = (_decimals == null) ? 0 : getNumber(_decimals);
  2345. const format = getFormat(_format);
  2346. let value = getBigInt(_value, "value");
  2347. const delta = decimals - format.decimals;
  2348. if (delta > 0) {
  2349. const tens = getTens(delta);
  2350. assert((value % tens) === BN_0$8, "value loses precision for format", "NUMERIC_FAULT", {
  2351. operation: "fromValue", fault: "underflow", value: _value
  2352. });
  2353. value /= tens;
  2354. }
  2355. else if (delta < 0) {
  2356. value *= getTens(-delta);
  2357. }
  2358. checkValue(value, format, "fromValue");
  2359. return new FixedNumber(_guard$5, value, format);
  2360. }
  2361. /**
  2362. * Creates a new [[FixedNumber]] for %%value%% with %%format%%.
  2363. *
  2364. * This will throw a [[NumericFaultError]] if %%value%% cannot fit
  2365. * in %%format%%, either due to overflow or underflow (precision loss).
  2366. */
  2367. static fromString(_value, _format) {
  2368. const match = _value.match(/^(-?)([0-9]*)\.?([0-9]*)$/);
  2369. assertArgument(match && (match[2].length + match[3].length) > 0, "invalid FixedNumber string value", "value", _value);
  2370. const format = getFormat(_format);
  2371. let whole = (match[2] || "0"), decimal = (match[3] || "");
  2372. // Pad out the decimals
  2373. while (decimal.length < format.decimals) {
  2374. decimal += Zeros$1;
  2375. }
  2376. // Check precision is safe
  2377. assert(decimal.substring(format.decimals).match(/^0*$/), "too many decimals for format", "NUMERIC_FAULT", {
  2378. operation: "fromString", fault: "underflow", value: _value
  2379. });
  2380. // Remove extra padding
  2381. decimal = decimal.substring(0, format.decimals);
  2382. const value = BigInt(match[1] + whole + decimal);
  2383. checkValue(value, format, "fromString");
  2384. return new FixedNumber(_guard$5, value, format);
  2385. }
  2386. /**
  2387. * Creates a new [[FixedNumber]] with the big-endian representation
  2388. * %%value%% with %%format%%.
  2389. *
  2390. * This will throw a [[NumericFaultError]] if %%value%% cannot fit
  2391. * in %%format%% due to overflow.
  2392. */
  2393. static fromBytes(_value, _format) {
  2394. let value = toBigInt(getBytes(_value, "value"));
  2395. const format = getFormat(_format);
  2396. if (format.signed) {
  2397. value = fromTwos(value, format.width);
  2398. }
  2399. checkValue(value, format, "fromBytes");
  2400. return new FixedNumber(_guard$5, value, format);
  2401. }
  2402. }
  2403. //const f1 = FixedNumber.fromString("12.56", "fixed16x2");
  2404. //const f2 = FixedNumber.fromString("0.3", "fixed16x2");
  2405. //console.log(f1.divSignal(f2));
  2406. //const BUMP = FixedNumber.from("0.5");
  2407. //See: https://github.com/ethereum/wiki/wiki/RLP
  2408. function hexlifyByte(value) {
  2409. let result = value.toString(16);
  2410. while (result.length < 2) {
  2411. result = "0" + result;
  2412. }
  2413. return "0x" + result;
  2414. }
  2415. function unarrayifyInteger(data, offset, length) {
  2416. let result = 0;
  2417. for (let i = 0; i < length; i++) {
  2418. result = (result * 256) + data[offset + i];
  2419. }
  2420. return result;
  2421. }
  2422. function _decodeChildren(data, offset, childOffset, length) {
  2423. const result = [];
  2424. while (childOffset < offset + 1 + length) {
  2425. const decoded = _decode(data, childOffset);
  2426. result.push(decoded.result);
  2427. childOffset += decoded.consumed;
  2428. assert(childOffset <= offset + 1 + length, "child data too short", "BUFFER_OVERRUN", {
  2429. buffer: data, length, offset
  2430. });
  2431. }
  2432. return { consumed: (1 + length), result: result };
  2433. }
  2434. // returns { consumed: number, result: Object }
  2435. function _decode(data, offset) {
  2436. assert(data.length !== 0, "data too short", "BUFFER_OVERRUN", {
  2437. buffer: data, length: 0, offset: 1
  2438. });
  2439. const checkOffset = (offset) => {
  2440. assert(offset <= data.length, "data short segment too short", "BUFFER_OVERRUN", {
  2441. buffer: data, length: data.length, offset
  2442. });
  2443. };
  2444. // Array with extra length prefix
  2445. if (data[offset] >= 0xf8) {
  2446. const lengthLength = data[offset] - 0xf7;
  2447. checkOffset(offset + 1 + lengthLength);
  2448. const length = unarrayifyInteger(data, offset + 1, lengthLength);
  2449. checkOffset(offset + 1 + lengthLength + length);
  2450. return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length);
  2451. }
  2452. else if (data[offset] >= 0xc0) {
  2453. const length = data[offset] - 0xc0;
  2454. checkOffset(offset + 1 + length);
  2455. return _decodeChildren(data, offset, offset + 1, length);
  2456. }
  2457. else if (data[offset] >= 0xb8) {
  2458. const lengthLength = data[offset] - 0xb7;
  2459. checkOffset(offset + 1 + lengthLength);
  2460. const length = unarrayifyInteger(data, offset + 1, lengthLength);
  2461. checkOffset(offset + 1 + lengthLength + length);
  2462. const result = hexlify(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length));
  2463. return { consumed: (1 + lengthLength + length), result: result };
  2464. }
  2465. else if (data[offset] >= 0x80) {
  2466. const length = data[offset] - 0x80;
  2467. checkOffset(offset + 1 + length);
  2468. const result = hexlify(data.slice(offset + 1, offset + 1 + length));
  2469. return { consumed: (1 + length), result: result };
  2470. }
  2471. return { consumed: 1, result: hexlifyByte(data[offset]) };
  2472. }
  2473. /**
  2474. * Decodes %%data%% into the structured data it represents.
  2475. */
  2476. function decodeRlp(_data) {
  2477. const data = getBytes(_data, "data");
  2478. const decoded = _decode(data, 0);
  2479. assertArgument(decoded.consumed === data.length, "unexpected junk after rlp payload", "data", _data);
  2480. return decoded.result;
  2481. }
  2482. //See: https://github.com/ethereum/wiki/wiki/RLP
  2483. function arrayifyInteger(value) {
  2484. const result = [];
  2485. while (value) {
  2486. result.unshift(value & 0xff);
  2487. value >>= 8;
  2488. }
  2489. return result;
  2490. }
  2491. function _encode(object) {
  2492. if (Array.isArray(object)) {
  2493. let payload = [];
  2494. object.forEach(function (child) {
  2495. payload = payload.concat(_encode(child));
  2496. });
  2497. if (payload.length <= 55) {
  2498. payload.unshift(0xc0 + payload.length);
  2499. return payload;
  2500. }
  2501. const length = arrayifyInteger(payload.length);
  2502. length.unshift(0xf7 + length.length);
  2503. return length.concat(payload);
  2504. }
  2505. const data = Array.prototype.slice.call(getBytes(object, "object"));
  2506. if (data.length === 1 && data[0] <= 0x7f) {
  2507. return data;
  2508. }
  2509. else if (data.length <= 55) {
  2510. data.unshift(0x80 + data.length);
  2511. return data;
  2512. }
  2513. const length = arrayifyInteger(data.length);
  2514. length.unshift(0xb7 + length.length);
  2515. return length.concat(data);
  2516. }
  2517. const nibbles = "0123456789abcdef";
  2518. /**
  2519. * Encodes %%object%% as an RLP-encoded [[DataHexString]].
  2520. */
  2521. function encodeRlp(object) {
  2522. let result = "0x";
  2523. for (const v of _encode(object)) {
  2524. result += nibbles[v >> 4];
  2525. result += nibbles[v & 0xf];
  2526. }
  2527. return result;
  2528. }
  2529. /**
  2530. * Most interactions with Ethereum requires integer values, which use
  2531. * the smallest magnitude unit.
  2532. *
  2533. * For example, imagine dealing with dollars and cents. Since dollars
  2534. * are divisible, non-integer values are possible, such as ``$10.77``.
  2535. * By using the smallest indivisible unit (i.e. cents), the value can
  2536. * be kept as the integer ``1077``.
  2537. *
  2538. * When receiving decimal input from the user (as a decimal string),
  2539. * the value should be converted to an integer and when showing a user
  2540. * a value, the integer value should be converted to a decimal string.
  2541. *
  2542. * This creates a clear distinction, between values to be used by code
  2543. * (integers) and values used for display logic to users (decimals).
  2544. *
  2545. * The native unit in Ethereum, //ether// is divisible to 18 decimal places,
  2546. * where each individual unit is called a //wei//.
  2547. *
  2548. * @_subsection api/utils:Unit Conversion [about-units]
  2549. */
  2550. const names = [
  2551. "wei",
  2552. "kwei",
  2553. "mwei",
  2554. "gwei",
  2555. "szabo",
  2556. "finney",
  2557. "ether",
  2558. ];
  2559. /**
  2560. * Converts %%value%% into a //decimal string//, assuming %%unit%% decimal
  2561. * places. The %%unit%% may be the number of decimal places or the name of
  2562. * a unit (e.g. ``"gwei"`` for 9 decimal places).
  2563. *
  2564. */
  2565. function formatUnits(value, unit) {
  2566. let decimals = 18;
  2567. if (typeof (unit) === "string") {
  2568. const index = names.indexOf(unit);
  2569. assertArgument(index >= 0, "invalid unit", "unit", unit);
  2570. decimals = 3 * index;
  2571. }
  2572. else if (unit != null) {
  2573. decimals = getNumber(unit, "unit");
  2574. }
  2575. return FixedNumber.fromValue(value, decimals, { decimals, width: 512 }).toString();
  2576. }
  2577. /**
  2578. * Converts the //decimal string// %%value%% to a BigInt, assuming
  2579. * %%unit%% decimal places. The %%unit%% may the number of decimal places
  2580. * or the name of a unit (e.g. ``"gwei"`` for 9 decimal places).
  2581. */
  2582. function parseUnits$1(value, unit) {
  2583. assertArgument(typeof (value) === "string", "value must be a string", "value", value);
  2584. let decimals = 18;
  2585. if (typeof (unit) === "string") {
  2586. const index = names.indexOf(unit);
  2587. assertArgument(index >= 0, "invalid unit", "unit", unit);
  2588. decimals = 3 * index;
  2589. }
  2590. else if (unit != null) {
  2591. decimals = getNumber(unit, "unit");
  2592. }
  2593. return FixedNumber.fromString(value, { decimals, width: 512 }).value;
  2594. }
  2595. /**
  2596. * Converts %%value%% into a //decimal string// using 18 decimal places.
  2597. */
  2598. function formatEther(wei) {
  2599. return formatUnits(wei, 18);
  2600. }
  2601. /**
  2602. * Converts the //decimal string// %%ether%% to a BigInt, using 18
  2603. * decimal places.
  2604. */
  2605. function parseEther(ether) {
  2606. return parseUnits$1(ether, 18);
  2607. }
  2608. /**
  2609. * Explain UUID and link to RFC here.
  2610. *
  2611. * @_subsection: api/utils:UUID [about-uuid]
  2612. */
  2613. /**
  2614. * Returns the version 4 [[link-uuid]] for the %%randomBytes%%.
  2615. *
  2616. * @see: https://www.ietf.org/rfc/rfc4122.txt (Section 4.4)
  2617. */
  2618. function uuidV4(randomBytes) {
  2619. const bytes = getBytes(randomBytes, "randomBytes");
  2620. // Section: 4.1.3:
  2621. // - time_hi_and_version[12:16] = 0b0100
  2622. bytes[6] = (bytes[6] & 0x0f) | 0x40;
  2623. // Section 4.4
  2624. // - clock_seq_hi_and_reserved[6] = 0b0
  2625. // - clock_seq_hi_and_reserved[7] = 0b1
  2626. bytes[8] = (bytes[8] & 0x3f) | 0x80;
  2627. const value = hexlify(bytes);
  2628. return [
  2629. value.substring(2, 10),
  2630. value.substring(10, 14),
  2631. value.substring(14, 18),
  2632. value.substring(18, 22),
  2633. value.substring(22, 34),
  2634. ].join("-");
  2635. }
  2636. /**
  2637. * @_ignore:
  2638. */
  2639. const WordSize = 32;
  2640. const Padding = new Uint8Array(WordSize);
  2641. // Properties used to immediate pass through to the underlying object
  2642. // - `then` is used to detect if an object is a Promise for await
  2643. const passProperties$1 = ["then"];
  2644. const _guard$4 = {};
  2645. const resultNames = new WeakMap();
  2646. function getNames(result) {
  2647. return resultNames.get(result);
  2648. }
  2649. function setNames(result, names) {
  2650. resultNames.set(result, names);
  2651. }
  2652. function throwError(name, error) {
  2653. const wrapped = new Error(`deferred error during ABI decoding triggered accessing ${name}`);
  2654. wrapped.error = error;
  2655. throw wrapped;
  2656. }
  2657. function toObject(names, items, deep) {
  2658. if (names.indexOf(null) >= 0) {
  2659. return items.map((item, index) => {
  2660. if (item instanceof Result) {
  2661. return toObject(getNames(item), item, deep);
  2662. }
  2663. return item;
  2664. });
  2665. }
  2666. return names.reduce((accum, name, index) => {
  2667. let item = items.getValue(name);
  2668. if (!(name in accum)) {
  2669. if (deep && item instanceof Result) {
  2670. item = toObject(getNames(item), item, deep);
  2671. }
  2672. accum[name] = item;
  2673. }
  2674. return accum;
  2675. }, {});
  2676. }
  2677. /**
  2678. * A [[Result]] is a sub-class of Array, which allows accessing any
  2679. * of its values either positionally by its index or, if keys are
  2680. * provided by its name.
  2681. *
  2682. * @_docloc: api/abi
  2683. */
  2684. class Result extends Array {
  2685. // No longer used; but cannot be removed as it will remove the
  2686. // #private field from the .d.ts which may break backwards
  2687. // compatibility
  2688. #names;
  2689. /**
  2690. * @private
  2691. */
  2692. constructor(...args) {
  2693. // To properly sub-class Array so the other built-in
  2694. // functions work, the constructor has to behave fairly
  2695. // well. So, in the event we are created via fromItems()
  2696. // we build the read-only Result object we want, but on
  2697. // any other input, we use the default constructor
  2698. // constructor(guard: any, items: Array<any>, keys?: Array<null | string>);
  2699. const guard = args[0];
  2700. let items = args[1];
  2701. let names = (args[2] || []).slice();
  2702. let wrap = true;
  2703. if (guard !== _guard$4) {
  2704. items = args;
  2705. names = [];
  2706. wrap = false;
  2707. }
  2708. // Can't just pass in ...items since an array of length 1
  2709. // is a special case in the super.
  2710. super(items.length);
  2711. items.forEach((item, index) => { this[index] = item; });
  2712. // Find all unique keys
  2713. const nameCounts = names.reduce((accum, name) => {
  2714. if (typeof (name) === "string") {
  2715. accum.set(name, (accum.get(name) || 0) + 1);
  2716. }
  2717. return accum;
  2718. }, (new Map()));
  2719. // Remove any key thats not unique
  2720. setNames(this, Object.freeze(items.map((item, index) => {
  2721. const name = names[index];
  2722. if (name != null && nameCounts.get(name) === 1) {
  2723. return name;
  2724. }
  2725. return null;
  2726. })));
  2727. // Dummy operations to prevent TypeScript from complaining
  2728. this.#names = [];
  2729. if (this.#names == null) {
  2730. void (this.#names);
  2731. }
  2732. if (!wrap) {
  2733. return;
  2734. }
  2735. // A wrapped Result is immutable
  2736. Object.freeze(this);
  2737. // Proxy indices and names so we can trap deferred errors
  2738. const proxy = new Proxy(this, {
  2739. get: (target, prop, receiver) => {
  2740. if (typeof (prop) === "string") {
  2741. // Index accessor
  2742. if (prop.match(/^[0-9]+$/)) {
  2743. const index = getNumber(prop, "%index");
  2744. if (index < 0 || index >= this.length) {
  2745. throw new RangeError("out of result range");
  2746. }
  2747. const item = target[index];
  2748. if (item instanceof Error) {
  2749. throwError(`index ${index}`, item);
  2750. }
  2751. return item;
  2752. }
  2753. // Pass important checks (like `then` for Promise) through
  2754. if (passProperties$1.indexOf(prop) >= 0) {
  2755. return Reflect.get(target, prop, receiver);
  2756. }
  2757. const value = target[prop];
  2758. if (value instanceof Function) {
  2759. // Make sure functions work with private variables
  2760. // See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#no_private_property_forwarding
  2761. return function (...args) {
  2762. return value.apply((this === receiver) ? target : this, args);
  2763. };
  2764. }
  2765. else if (!(prop in target)) {
  2766. // Possible name accessor
  2767. return target.getValue.apply((this === receiver) ? target : this, [prop]);
  2768. }
  2769. }
  2770. return Reflect.get(target, prop, receiver);
  2771. }
  2772. });
  2773. setNames(proxy, getNames(this));
  2774. return proxy;
  2775. }
  2776. /**
  2777. * Returns the Result as a normal Array. If %%deep%%, any children
  2778. * which are Result objects are also converted to a normal Array.
  2779. *
  2780. * This will throw if there are any outstanding deferred
  2781. * errors.
  2782. */
  2783. toArray(deep) {
  2784. const result = [];
  2785. this.forEach((item, index) => {
  2786. if (item instanceof Error) {
  2787. throwError(`index ${index}`, item);
  2788. }
  2789. if (deep && item instanceof Result) {
  2790. item = item.toArray(deep);
  2791. }
  2792. result.push(item);
  2793. });
  2794. return result;
  2795. }
  2796. /**
  2797. * Returns the Result as an Object with each name-value pair. If
  2798. * %%deep%%, any children which are Result objects are also
  2799. * converted to an Object.
  2800. *
  2801. * This will throw if any value is unnamed, or if there are
  2802. * any outstanding deferred errors.
  2803. */
  2804. toObject(deep) {
  2805. const names = getNames(this);
  2806. return names.reduce((accum, name, index) => {
  2807. assert(name != null, `value at index ${index} unnamed`, "UNSUPPORTED_OPERATION", {
  2808. operation: "toObject()"
  2809. });
  2810. return toObject(names, this, deep);
  2811. }, {});
  2812. }
  2813. /**
  2814. * @_ignore
  2815. */
  2816. slice(start, end) {
  2817. if (start == null) {
  2818. start = 0;
  2819. }
  2820. if (start < 0) {
  2821. start += this.length;
  2822. if (start < 0) {
  2823. start = 0;
  2824. }
  2825. }
  2826. if (end == null) {
  2827. end = this.length;
  2828. }
  2829. if (end < 0) {
  2830. end += this.length;
  2831. if (end < 0) {
  2832. end = 0;
  2833. }
  2834. }
  2835. if (end > this.length) {
  2836. end = this.length;
  2837. }
  2838. const _names = getNames(this);
  2839. const result = [], names = [];
  2840. for (let i = start; i < end; i++) {
  2841. result.push(this[i]);
  2842. names.push(_names[i]);
  2843. }
  2844. return new Result(_guard$4, result, names);
  2845. }
  2846. /**
  2847. * @_ignore
  2848. */
  2849. filter(callback, thisArg) {
  2850. const _names = getNames(this);
  2851. const result = [], names = [];
  2852. for (let i = 0; i < this.length; i++) {
  2853. const item = this[i];
  2854. if (item instanceof Error) {
  2855. throwError(`index ${i}`, item);
  2856. }
  2857. if (callback.call(thisArg, item, i, this)) {
  2858. result.push(item);
  2859. names.push(_names[i]);
  2860. }
  2861. }
  2862. return new Result(_guard$4, result, names);
  2863. }
  2864. /**
  2865. * @_ignore
  2866. */
  2867. map(callback, thisArg) {
  2868. const result = [];
  2869. for (let i = 0; i < this.length; i++) {
  2870. const item = this[i];
  2871. if (item instanceof Error) {
  2872. throwError(`index ${i}`, item);
  2873. }
  2874. result.push(callback.call(thisArg, item, i, this));
  2875. }
  2876. return result;
  2877. }
  2878. /**
  2879. * Returns the value for %%name%%.
  2880. *
  2881. * Since it is possible to have a key whose name conflicts with
  2882. * a method on a [[Result]] or its superclass Array, or any
  2883. * JavaScript keyword, this ensures all named values are still
  2884. * accessible by name.
  2885. */
  2886. getValue(name) {
  2887. const index = getNames(this).indexOf(name);
  2888. if (index === -1) {
  2889. return undefined;
  2890. }
  2891. const value = this[index];
  2892. if (value instanceof Error) {
  2893. throwError(`property ${JSON.stringify(name)}`, value.error);
  2894. }
  2895. return value;
  2896. }
  2897. /**
  2898. * Creates a new [[Result]] for %%items%% with each entry
  2899. * also accessible by its corresponding name in %%keys%%.
  2900. */
  2901. static fromItems(items, keys) {
  2902. return new Result(_guard$4, items, keys);
  2903. }
  2904. }
  2905. /**
  2906. * Returns all errors found in a [[Result]].
  2907. *
  2908. * Since certain errors encountered when creating a [[Result]] do
  2909. * not impact the ability to continue parsing data, they are
  2910. * deferred until they are actually accessed. Hence a faulty string
  2911. * in an Event that is never used does not impact the program flow.
  2912. *
  2913. * However, sometimes it may be useful to access, identify or
  2914. * validate correctness of a [[Result]].
  2915. *
  2916. * @_docloc api/abi
  2917. */
  2918. function checkResultErrors(result) {
  2919. // Find the first error (if any)
  2920. const errors = [];
  2921. const checkErrors = function (path, object) {
  2922. if (!Array.isArray(object)) {
  2923. return;
  2924. }
  2925. for (let key in object) {
  2926. const childPath = path.slice();
  2927. childPath.push(key);
  2928. try {
  2929. checkErrors(childPath, object[key]);
  2930. }
  2931. catch (error) {
  2932. errors.push({ path: childPath, error: error });
  2933. }
  2934. }
  2935. };
  2936. checkErrors([], result);
  2937. return errors;
  2938. }
  2939. function getValue$1(value) {
  2940. let bytes = toBeArray(value);
  2941. assert(bytes.length <= WordSize, "value out-of-bounds", "BUFFER_OVERRUN", { buffer: bytes, length: WordSize, offset: bytes.length });
  2942. if (bytes.length !== WordSize) {
  2943. bytes = getBytesCopy(concat([Padding.slice(bytes.length % WordSize), bytes]));
  2944. }
  2945. return bytes;
  2946. }
  2947. /**
  2948. * @_ignore
  2949. */
  2950. class Coder {
  2951. // The coder name:
  2952. // - address, uint256, tuple, array, etc.
  2953. name;
  2954. // The fully expanded type, including composite types:
  2955. // - address, uint256, tuple(address,bytes), uint256[3][4][], etc.
  2956. type;
  2957. // The localName bound in the signature, in this example it is "baz":
  2958. // - tuple(address foo, uint bar) baz
  2959. localName;
  2960. // Whether this type is dynamic:
  2961. // - Dynamic: bytes, string, address[], tuple(boolean[]), etc.
  2962. // - Not Dynamic: address, uint256, boolean[3], tuple(address, uint8)
  2963. dynamic;
  2964. constructor(name, type, localName, dynamic) {
  2965. defineProperties(this, { name, type, localName, dynamic }, {
  2966. name: "string", type: "string", localName: "string", dynamic: "boolean"
  2967. });
  2968. }
  2969. _throwError(message, value) {
  2970. assertArgument(false, message, this.localName, value);
  2971. }
  2972. }
  2973. /**
  2974. * @_ignore
  2975. */
  2976. class Writer {
  2977. // An array of WordSize lengthed objects to concatenation
  2978. #data;
  2979. #dataLength;
  2980. constructor() {
  2981. this.#data = [];
  2982. this.#dataLength = 0;
  2983. }
  2984. get data() {
  2985. return concat(this.#data);
  2986. }
  2987. get length() { return this.#dataLength; }
  2988. #writeData(data) {
  2989. this.#data.push(data);
  2990. this.#dataLength += data.length;
  2991. return data.length;
  2992. }
  2993. appendWriter(writer) {
  2994. return this.#writeData(getBytesCopy(writer.data));
  2995. }
  2996. // Arrayish item; pad on the right to *nearest* WordSize
  2997. writeBytes(value) {
  2998. let bytes = getBytesCopy(value);
  2999. const paddingOffset = bytes.length % WordSize;
  3000. if (paddingOffset) {
  3001. bytes = getBytesCopy(concat([bytes, Padding.slice(paddingOffset)]));
  3002. }
  3003. return this.#writeData(bytes);
  3004. }
  3005. // Numeric item; pad on the left *to* WordSize
  3006. writeValue(value) {
  3007. return this.#writeData(getValue$1(value));
  3008. }
  3009. // Inserts a numeric place-holder, returning a callback that can
  3010. // be used to asjust the value later
  3011. writeUpdatableValue() {
  3012. const offset = this.#data.length;
  3013. this.#data.push(Padding);
  3014. this.#dataLength += WordSize;
  3015. return (value) => {
  3016. this.#data[offset] = getValue$1(value);
  3017. };
  3018. }
  3019. }
  3020. /**
  3021. * @_ignore
  3022. */
  3023. class Reader {
  3024. // Allows incomplete unpadded data to be read; otherwise an error
  3025. // is raised if attempting to overrun the buffer. This is required
  3026. // to deal with an old Solidity bug, in which event data for
  3027. // external (not public thoguh) was tightly packed.
  3028. allowLoose;
  3029. #data;
  3030. #offset;
  3031. #bytesRead;
  3032. #parent;
  3033. #maxInflation;
  3034. constructor(data, allowLoose, maxInflation) {
  3035. defineProperties(this, { allowLoose: !!allowLoose });
  3036. this.#data = getBytesCopy(data);
  3037. this.#bytesRead = 0;
  3038. this.#parent = null;
  3039. this.#maxInflation = (maxInflation != null) ? maxInflation : 1024;
  3040. this.#offset = 0;
  3041. }
  3042. get data() { return hexlify(this.#data); }
  3043. get dataLength() { return this.#data.length; }
  3044. get consumed() { return this.#offset; }
  3045. get bytes() { return new Uint8Array(this.#data); }
  3046. #incrementBytesRead(count) {
  3047. if (this.#parent) {
  3048. return this.#parent.#incrementBytesRead(count);
  3049. }
  3050. this.#bytesRead += count;
  3051. // Check for excessive inflation (see: #4537)
  3052. 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", {
  3053. buffer: getBytesCopy(this.#data), offset: this.#offset,
  3054. length: count, info: {
  3055. bytesRead: this.#bytesRead,
  3056. dataLength: this.dataLength
  3057. }
  3058. });
  3059. }
  3060. #peekBytes(offset, length, loose) {
  3061. let alignedLength = Math.ceil(length / WordSize) * WordSize;
  3062. if (this.#offset + alignedLength > this.#data.length) {
  3063. if (this.allowLoose && loose && this.#offset + length <= this.#data.length) {
  3064. alignedLength = length;
  3065. }
  3066. else {
  3067. assert(false, "data out-of-bounds", "BUFFER_OVERRUN", {
  3068. buffer: getBytesCopy(this.#data),
  3069. length: this.#data.length,
  3070. offset: this.#offset + alignedLength
  3071. });
  3072. }
  3073. }
  3074. return this.#data.slice(this.#offset, this.#offset + alignedLength);
  3075. }
  3076. // Create a sub-reader with the same underlying data, but offset
  3077. subReader(offset) {
  3078. const reader = new Reader(this.#data.slice(this.#offset + offset), this.allowLoose, this.#maxInflation);
  3079. reader.#parent = this;
  3080. return reader;
  3081. }
  3082. // Read bytes
  3083. readBytes(length, loose) {
  3084. let bytes = this.#peekBytes(0, length, !!loose);
  3085. this.#incrementBytesRead(length);
  3086. this.#offset += bytes.length;
  3087. // @TODO: Make sure the length..end bytes are all 0?
  3088. return bytes.slice(0, length);
  3089. }
  3090. // Read a numeric values
  3091. readValue() {
  3092. return toBigInt(this.readBytes(WordSize));
  3093. }
  3094. readIndex() {
  3095. return toNumber(this.readBytes(WordSize));
  3096. }
  3097. }
  3098. function number(n) {
  3099. if (!Number.isSafeInteger(n) || n < 0)
  3100. throw new Error(`Wrong positive integer: ${n}`);
  3101. }
  3102. function bytes(b, ...lengths) {
  3103. if (!(b instanceof Uint8Array))
  3104. throw new Error('Expected Uint8Array');
  3105. if (lengths.length > 0 && !lengths.includes(b.length))
  3106. throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
  3107. }
  3108. function hash(hash) {
  3109. if (typeof hash !== 'function' || typeof hash.create !== 'function')
  3110. throw new Error('Hash should be wrapped by utils.wrapConstructor');
  3111. number(hash.outputLen);
  3112. number(hash.blockLen);
  3113. }
  3114. function exists(instance, checkFinished = true) {
  3115. if (instance.destroyed)
  3116. throw new Error('Hash instance has been destroyed');
  3117. if (checkFinished && instance.finished)
  3118. throw new Error('Hash#digest() has already been called');
  3119. }
  3120. function output(out, instance) {
  3121. bytes(out);
  3122. const min = instance.outputLen;
  3123. if (out.length < min) {
  3124. throw new Error(`digestInto() expects output buffer of length at least ${min}`);
  3125. }
  3126. }
  3127. const crypto$1 = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
  3128. /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
  3129. // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
  3130. // node.js versions earlier than v19 don't declare it in global scope.
  3131. // For node.js, package.json#exports field mapping rewrites import
  3132. // from `crypto` to `cryptoNode`, which imports native module.
  3133. // Makes the utils un-importable in browsers without a bundler.
  3134. // Once node.js 18 is deprecated, we can just drop the import.
  3135. const u8a$1 = (a) => a instanceof Uint8Array;
  3136. const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
  3137. // Cast array to view
  3138. const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
  3139. // The rotate right (circular right shift) operation for uint32
  3140. const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
  3141. // big-endian hardware is rare. Just in case someone still decides to run hashes:
  3142. // early-throw an error because we don't support BE yet.
  3143. const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
  3144. if (!isLE)
  3145. throw new Error('Non little-endian hardware is not supported');
  3146. // There is no setImmediate in browser and setTimeout is slow.
  3147. // call of async fn will return Promise, which will be fullfiled only on
  3148. // next scheduler queue processing step and this is exactly what we need.
  3149. const nextTick = async () => { };
  3150. // Returns control to thread each 'tick' ms to avoid blocking
  3151. async function asyncLoop(iters, tick, cb) {
  3152. let ts = Date.now();
  3153. for (let i = 0; i < iters; i++) {
  3154. cb(i);
  3155. // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
  3156. const diff = Date.now() - ts;
  3157. if (diff >= 0 && diff < tick)
  3158. continue;
  3159. await nextTick();
  3160. ts += diff;
  3161. }
  3162. }
  3163. /**
  3164. * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
  3165. */
  3166. function utf8ToBytes$1(str) {
  3167. if (typeof str !== 'string')
  3168. throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
  3169. return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
  3170. }
  3171. /**
  3172. * Normalizes (non-hex) string or Uint8Array to Uint8Array.
  3173. * Warning: when Uint8Array is passed, it would NOT get copied.
  3174. * Keep in mind for future mutable operations.
  3175. */
  3176. function toBytes(data) {
  3177. if (typeof data === 'string')
  3178. data = utf8ToBytes$1(data);
  3179. if (!u8a$1(data))
  3180. throw new Error(`expected Uint8Array, got ${typeof data}`);
  3181. return data;
  3182. }
  3183. /**
  3184. * Copies several Uint8Arrays into one.
  3185. */
  3186. function concatBytes$1(...arrays) {
  3187. const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));
  3188. let pad = 0; // walk through each item, ensure they have proper type
  3189. arrays.forEach((a) => {
  3190. if (!u8a$1(a))
  3191. throw new Error('Uint8Array expected');
  3192. r.set(a, pad);
  3193. pad += a.length;
  3194. });
  3195. return r;
  3196. }
  3197. // For runtime check if class implements interface
  3198. class Hash {
  3199. // Safe version that clones internal state
  3200. clone() {
  3201. return this._cloneInto();
  3202. }
  3203. }
  3204. const toStr = {}.toString;
  3205. function checkOpts(defaults, opts) {
  3206. if (opts !== undefined && toStr.call(opts) !== '[object Object]')
  3207. throw new Error('Options should be object or undefined');
  3208. const merged = Object.assign(defaults, opts);
  3209. return merged;
  3210. }
  3211. function wrapConstructor(hashCons) {
  3212. const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
  3213. const tmp = hashCons();
  3214. hashC.outputLen = tmp.outputLen;
  3215. hashC.blockLen = tmp.blockLen;
  3216. hashC.create = () => hashCons();
  3217. return hashC;
  3218. }
  3219. /**
  3220. * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
  3221. */
  3222. function randomBytes$2(bytesLength = 32) {
  3223. if (crypto$1 && typeof crypto$1.getRandomValues === 'function') {
  3224. return crypto$1.getRandomValues(new Uint8Array(bytesLength));
  3225. }
  3226. throw new Error('crypto.getRandomValues must be defined');
  3227. }
  3228. // HMAC (RFC 2104)
  3229. class HMAC extends Hash {
  3230. constructor(hash$1, _key) {
  3231. super();
  3232. this.finished = false;
  3233. this.destroyed = false;
  3234. hash(hash$1);
  3235. const key = toBytes(_key);
  3236. this.iHash = hash$1.create();
  3237. if (typeof this.iHash.update !== 'function')
  3238. throw new Error('Expected instance of class which extends utils.Hash');
  3239. this.blockLen = this.iHash.blockLen;
  3240. this.outputLen = this.iHash.outputLen;
  3241. const blockLen = this.blockLen;
  3242. const pad = new Uint8Array(blockLen);
  3243. // blockLen can be bigger than outputLen
  3244. pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key);
  3245. for (let i = 0; i < pad.length; i++)
  3246. pad[i] ^= 0x36;
  3247. this.iHash.update(pad);
  3248. // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
  3249. this.oHash = hash$1.create();
  3250. // Undo internal XOR && apply outer XOR
  3251. for (let i = 0; i < pad.length; i++)
  3252. pad[i] ^= 0x36 ^ 0x5c;
  3253. this.oHash.update(pad);
  3254. pad.fill(0);
  3255. }
  3256. update(buf) {
  3257. exists(this);
  3258. this.iHash.update(buf);
  3259. return this;
  3260. }
  3261. digestInto(out) {
  3262. exists(this);
  3263. bytes(out, this.outputLen);
  3264. this.finished = true;
  3265. this.iHash.digestInto(out);
  3266. this.oHash.update(out);
  3267. this.oHash.digestInto(out);
  3268. this.destroy();
  3269. }
  3270. digest() {
  3271. const out = new Uint8Array(this.oHash.outputLen);
  3272. this.digestInto(out);
  3273. return out;
  3274. }
  3275. _cloneInto(to) {
  3276. // Create new instance without calling constructor since key already in state and we don't know it.
  3277. to || (to = Object.create(Object.getPrototypeOf(this), {}));
  3278. const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
  3279. to = to;
  3280. to.finished = finished;
  3281. to.destroyed = destroyed;
  3282. to.blockLen = blockLen;
  3283. to.outputLen = outputLen;
  3284. to.oHash = oHash._cloneInto(to.oHash);
  3285. to.iHash = iHash._cloneInto(to.iHash);
  3286. return to;
  3287. }
  3288. destroy() {
  3289. this.destroyed = true;
  3290. this.oHash.destroy();
  3291. this.iHash.destroy();
  3292. }
  3293. }
  3294. /**
  3295. * HMAC: RFC2104 message authentication code.
  3296. * @param hash - function that would be used e.g. sha256
  3297. * @param key - message key
  3298. * @param message - message data
  3299. */
  3300. const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
  3301. hmac.create = (hash, key) => new HMAC(hash, key);
  3302. // Common prologue and epilogue for sync/async functions
  3303. function pbkdf2Init(hash$1, _password, _salt, _opts) {
  3304. hash(hash$1);
  3305. const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
  3306. const { c, dkLen, asyncTick } = opts;
  3307. number(c);
  3308. number(dkLen);
  3309. number(asyncTick);
  3310. if (c < 1)
  3311. throw new Error('PBKDF2: iterations (c) should be >= 1');
  3312. const password = toBytes(_password);
  3313. const salt = toBytes(_salt);
  3314. // DK = PBKDF2(PRF, Password, Salt, c, dkLen);
  3315. const DK = new Uint8Array(dkLen);
  3316. // U1 = PRF(Password, Salt + INT_32_BE(i))
  3317. const PRF = hmac.create(hash$1, password);
  3318. const PRFSalt = PRF._cloneInto().update(salt);
  3319. return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
  3320. }
  3321. function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
  3322. PRF.destroy();
  3323. PRFSalt.destroy();
  3324. if (prfW)
  3325. prfW.destroy();
  3326. u.fill(0);
  3327. return DK;
  3328. }
  3329. /**
  3330. * PBKDF2-HMAC: RFC 2898 key derivation function
  3331. * @param hash - hash function that would be used e.g. sha256
  3332. * @param password - password from which a derived key is generated
  3333. * @param salt - cryptographic salt
  3334. * @param opts - {c, dkLen} where c is work factor and dkLen is output message size
  3335. */
  3336. function pbkdf2$1(hash, password, salt, opts) {
  3337. const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
  3338. let prfW; // Working copy
  3339. const arr = new Uint8Array(4);
  3340. const view = createView(arr);
  3341. const u = new Uint8Array(PRF.outputLen);
  3342. // DK = T1 + T2 + ⋯ + Tdklen/hlen
  3343. for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
  3344. // Ti = F(Password, Salt, c, i)
  3345. const Ti = DK.subarray(pos, pos + PRF.outputLen);
  3346. view.setInt32(0, ti, false);
  3347. // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc
  3348. // U1 = PRF(Password, Salt + INT_32_BE(i))
  3349. (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
  3350. Ti.set(u.subarray(0, Ti.length));
  3351. for (let ui = 1; ui < c; ui++) {
  3352. // Uc = PRF(Password, Uc−1)
  3353. PRF._cloneInto(prfW).update(u).digestInto(u);
  3354. for (let i = 0; i < Ti.length; i++)
  3355. Ti[i] ^= u[i];
  3356. }
  3357. }
  3358. return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
  3359. }
  3360. // Polyfill for Safari 14
  3361. function setBigUint64(view, byteOffset, value, isLE) {
  3362. if (typeof view.setBigUint64 === 'function')
  3363. return view.setBigUint64(byteOffset, value, isLE);
  3364. const _32n = BigInt(32);
  3365. const _u32_max = BigInt(0xffffffff);
  3366. const wh = Number((value >> _32n) & _u32_max);
  3367. const wl = Number(value & _u32_max);
  3368. const h = isLE ? 4 : 0;
  3369. const l = isLE ? 0 : 4;
  3370. view.setUint32(byteOffset + h, wh, isLE);
  3371. view.setUint32(byteOffset + l, wl, isLE);
  3372. }
  3373. // Base SHA2 class (RFC 6234)
  3374. class SHA2 extends Hash {
  3375. constructor(blockLen, outputLen, padOffset, isLE) {
  3376. super();
  3377. this.blockLen = blockLen;
  3378. this.outputLen = outputLen;
  3379. this.padOffset = padOffset;
  3380. this.isLE = isLE;
  3381. this.finished = false;
  3382. this.length = 0;
  3383. this.pos = 0;
  3384. this.destroyed = false;
  3385. this.buffer = new Uint8Array(blockLen);
  3386. this.view = createView(this.buffer);
  3387. }
  3388. update(data) {
  3389. exists(this);
  3390. const { view, buffer, blockLen } = this;
  3391. data = toBytes(data);
  3392. const len = data.length;
  3393. for (let pos = 0; pos < len;) {
  3394. const take = Math.min(blockLen - this.pos, len - pos);
  3395. // Fast path: we have at least one block in input, cast it to view and process
  3396. if (take === blockLen) {
  3397. const dataView = createView(data);
  3398. for (; blockLen <= len - pos; pos += blockLen)
  3399. this.process(dataView, pos);
  3400. continue;
  3401. }
  3402. buffer.set(data.subarray(pos, pos + take), this.pos);
  3403. this.pos += take;
  3404. pos += take;
  3405. if (this.pos === blockLen) {
  3406. this.process(view, 0);
  3407. this.pos = 0;
  3408. }
  3409. }
  3410. this.length += data.length;
  3411. this.roundClean();
  3412. return this;
  3413. }
  3414. digestInto(out) {
  3415. exists(this);
  3416. output(out, this);
  3417. this.finished = true;
  3418. // Padding
  3419. // We can avoid allocation of buffer for padding completely if it
  3420. // was previously not allocated here. But it won't change performance.
  3421. const { buffer, view, blockLen, isLE } = this;
  3422. let { pos } = this;
  3423. // append the bit '1' to the message
  3424. buffer[pos++] = 0b10000000;
  3425. this.buffer.subarray(pos).fill(0);
  3426. // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again
  3427. if (this.padOffset > blockLen - pos) {
  3428. this.process(view, 0);
  3429. pos = 0;
  3430. }
  3431. // Pad until full block byte with zeros
  3432. for (let i = pos; i < blockLen; i++)
  3433. buffer[i] = 0;
  3434. // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
  3435. // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
  3436. // So we just write lowest 64 bits of that value.
  3437. setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
  3438. this.process(view, 0);
  3439. const oview = createView(out);
  3440. const len = this.outputLen;
  3441. // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
  3442. if (len % 4)
  3443. throw new Error('_sha2: outputLen should be aligned to 32bit');
  3444. const outLen = len / 4;
  3445. const state = this.get();
  3446. if (outLen > state.length)
  3447. throw new Error('_sha2: outputLen bigger than state');
  3448. for (let i = 0; i < outLen; i++)
  3449. oview.setUint32(4 * i, state[i], isLE);
  3450. }
  3451. digest() {
  3452. const { buffer, outputLen } = this;
  3453. this.digestInto(buffer);
  3454. const res = buffer.slice(0, outputLen);
  3455. this.destroy();
  3456. return res;
  3457. }
  3458. _cloneInto(to) {
  3459. to || (to = new this.constructor());
  3460. to.set(...this.get());
  3461. const { blockLen, buffer, length, finished, destroyed, pos } = this;
  3462. to.length = length;
  3463. to.pos = pos;
  3464. to.finished = finished;
  3465. to.destroyed = destroyed;
  3466. if (length % blockLen)
  3467. to.buffer.set(buffer);
  3468. return to;
  3469. }
  3470. }
  3471. // SHA2-256 need to try 2^128 hashes to execute birthday attack.
  3472. // BTC network is doing 2^67 hashes/sec as per early 2023.
  3473. // Choice: a ? b : c
  3474. const Chi = (a, b, c) => (a & b) ^ (~a & c);
  3475. // Majority function, true if any two inpust is true
  3476. const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);
  3477. // Round constants:
  3478. // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)
  3479. // prettier-ignore
  3480. const SHA256_K = /* @__PURE__ */ new Uint32Array([
  3481. 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
  3482. 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
  3483. 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  3484. 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
  3485. 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
  3486. 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  3487. 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
  3488. 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
  3489. ]);
  3490. // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
  3491. // prettier-ignore
  3492. const IV = /* @__PURE__ */ new Uint32Array([
  3493. 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
  3494. ]);
  3495. // Temporary buffer, not used to store anything between runs
  3496. // Named this way because it matches specification.
  3497. const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
  3498. class SHA256 extends SHA2 {
  3499. constructor() {
  3500. super(64, 32, 8, false);
  3501. // We cannot use array here since array allows indexing by variable
  3502. // which means optimizer/compiler cannot use registers.
  3503. this.A = IV[0] | 0;
  3504. this.B = IV[1] | 0;
  3505. this.C = IV[2] | 0;
  3506. this.D = IV[3] | 0;
  3507. this.E = IV[4] | 0;
  3508. this.F = IV[5] | 0;
  3509. this.G = IV[6] | 0;
  3510. this.H = IV[7] | 0;
  3511. }
  3512. get() {
  3513. const { A, B, C, D, E, F, G, H } = this;
  3514. return [A, B, C, D, E, F, G, H];
  3515. }
  3516. // prettier-ignore
  3517. set(A, B, C, D, E, F, G, H) {
  3518. this.A = A | 0;
  3519. this.B = B | 0;
  3520. this.C = C | 0;
  3521. this.D = D | 0;
  3522. this.E = E | 0;
  3523. this.F = F | 0;
  3524. this.G = G | 0;
  3525. this.H = H | 0;
  3526. }
  3527. process(view, offset) {
  3528. // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
  3529. for (let i = 0; i < 16; i++, offset += 4)
  3530. SHA256_W[i] = view.getUint32(offset, false);
  3531. for (let i = 16; i < 64; i++) {
  3532. const W15 = SHA256_W[i - 15];
  3533. const W2 = SHA256_W[i - 2];
  3534. const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
  3535. const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
  3536. SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
  3537. }
  3538. // Compression function main loop, 64 rounds
  3539. let { A, B, C, D, E, F, G, H } = this;
  3540. for (let i = 0; i < 64; i++) {
  3541. const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
  3542. const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
  3543. const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
  3544. const T2 = (sigma0 + Maj(A, B, C)) | 0;
  3545. H = G;
  3546. G = F;
  3547. F = E;
  3548. E = (D + T1) | 0;
  3549. D = C;
  3550. C = B;
  3551. B = A;
  3552. A = (T1 + T2) | 0;
  3553. }
  3554. // Add the compressed chunk to the current hash value
  3555. A = (A + this.A) | 0;
  3556. B = (B + this.B) | 0;
  3557. C = (C + this.C) | 0;
  3558. D = (D + this.D) | 0;
  3559. E = (E + this.E) | 0;
  3560. F = (F + this.F) | 0;
  3561. G = (G + this.G) | 0;
  3562. H = (H + this.H) | 0;
  3563. this.set(A, B, C, D, E, F, G, H);
  3564. }
  3565. roundClean() {
  3566. SHA256_W.fill(0);
  3567. }
  3568. destroy() {
  3569. this.set(0, 0, 0, 0, 0, 0, 0, 0);
  3570. this.buffer.fill(0);
  3571. }
  3572. }
  3573. /**
  3574. * SHA2-256 hash function
  3575. * @param message - data that would be hashed
  3576. */
  3577. const sha256$1 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
  3578. const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
  3579. const _32n = /* @__PURE__ */ BigInt(32);
  3580. // We are not using BigUint64Array, because they are extremely slow as per 2022
  3581. function fromBig(n, le = false) {
  3582. if (le)
  3583. return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
  3584. return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
  3585. }
  3586. function split$1(lst, le = false) {
  3587. let Ah = new Uint32Array(lst.length);
  3588. let Al = new Uint32Array(lst.length);
  3589. for (let i = 0; i < lst.length; i++) {
  3590. const { h, l } = fromBig(lst[i], le);
  3591. [Ah[i], Al[i]] = [h, l];
  3592. }
  3593. return [Ah, Al];
  3594. }
  3595. const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
  3596. // for Shift in [0, 32)
  3597. const shrSH = (h, _l, s) => h >>> s;
  3598. const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
  3599. // Right rotate for Shift in [1, 32)
  3600. const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
  3601. const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
  3602. // Right rotate for Shift in (32, 64), NOTE: 32 is special case.
  3603. const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
  3604. const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
  3605. // Right rotate for shift===32 (just swaps l&h)
  3606. const rotr32H = (_h, l) => l;
  3607. const rotr32L = (h, _l) => h;
  3608. // Left rotate for Shift in [1, 32)
  3609. const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
  3610. const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
  3611. // Left rotate for Shift in (32, 64), NOTE: 32 is special case.
  3612. const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
  3613. const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
  3614. // JS uses 32-bit signed integers for bitwise operations which means we cannot
  3615. // simple take carry out of low bit sum by shift, we need to use division.
  3616. function add(Ah, Al, Bh, Bl) {
  3617. const l = (Al >>> 0) + (Bl >>> 0);
  3618. return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
  3619. }
  3620. // Addition with more than 2 elements
  3621. const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
  3622. const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
  3623. const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
  3624. const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
  3625. const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
  3626. const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
  3627. // prettier-ignore
  3628. const u64 = {
  3629. fromBig, split: split$1, toBig,
  3630. shrSH, shrSL,
  3631. rotrSH, rotrSL, rotrBH, rotrBL,
  3632. rotr32H, rotr32L,
  3633. rotlSH, rotlSL, rotlBH, rotlBL,
  3634. add, add3L, add3H, add4L, add4H, add5H, add5L,
  3635. };
  3636. // Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):
  3637. // prettier-ignore
  3638. const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([
  3639. '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',
  3640. '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',
  3641. '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',
  3642. '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',
  3643. '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',
  3644. '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',
  3645. '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',
  3646. '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',
  3647. '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',
  3648. '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',
  3649. '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',
  3650. '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',
  3651. '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',
  3652. '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',
  3653. '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',
  3654. '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',
  3655. '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',
  3656. '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',
  3657. '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',
  3658. '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'
  3659. ].map(n => BigInt(n))))();
  3660. // Temporary buffer, not used to store anything between runs
  3661. const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
  3662. const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
  3663. class SHA512 extends SHA2 {
  3664. constructor() {
  3665. super(128, 64, 16, false);
  3666. // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.
  3667. // Also looks cleaner and easier to verify with spec.
  3668. // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
  3669. // h -- high 32 bits, l -- low 32 bits
  3670. this.Ah = 0x6a09e667 | 0;
  3671. this.Al = 0xf3bcc908 | 0;
  3672. this.Bh = 0xbb67ae85 | 0;
  3673. this.Bl = 0x84caa73b | 0;
  3674. this.Ch = 0x3c6ef372 | 0;
  3675. this.Cl = 0xfe94f82b | 0;
  3676. this.Dh = 0xa54ff53a | 0;
  3677. this.Dl = 0x5f1d36f1 | 0;
  3678. this.Eh = 0x510e527f | 0;
  3679. this.El = 0xade682d1 | 0;
  3680. this.Fh = 0x9b05688c | 0;
  3681. this.Fl = 0x2b3e6c1f | 0;
  3682. this.Gh = 0x1f83d9ab | 0;
  3683. this.Gl = 0xfb41bd6b | 0;
  3684. this.Hh = 0x5be0cd19 | 0;
  3685. this.Hl = 0x137e2179 | 0;
  3686. }
  3687. // prettier-ignore
  3688. get() {
  3689. const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
  3690. return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
  3691. }
  3692. // prettier-ignore
  3693. set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
  3694. this.Ah = Ah | 0;
  3695. this.Al = Al | 0;
  3696. this.Bh = Bh | 0;
  3697. this.Bl = Bl | 0;
  3698. this.Ch = Ch | 0;
  3699. this.Cl = Cl | 0;
  3700. this.Dh = Dh | 0;
  3701. this.Dl = Dl | 0;
  3702. this.Eh = Eh | 0;
  3703. this.El = El | 0;
  3704. this.Fh = Fh | 0;
  3705. this.Fl = Fl | 0;
  3706. this.Gh = Gh | 0;
  3707. this.Gl = Gl | 0;
  3708. this.Hh = Hh | 0;
  3709. this.Hl = Hl | 0;
  3710. }
  3711. process(view, offset) {
  3712. // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array
  3713. for (let i = 0; i < 16; i++, offset += 4) {
  3714. SHA512_W_H[i] = view.getUint32(offset);
  3715. SHA512_W_L[i] = view.getUint32((offset += 4));
  3716. }
  3717. for (let i = 16; i < 80; i++) {
  3718. // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)
  3719. const W15h = SHA512_W_H[i - 15] | 0;
  3720. const W15l = SHA512_W_L[i - 15] | 0;
  3721. const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);
  3722. const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);
  3723. // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)
  3724. const W2h = SHA512_W_H[i - 2] | 0;
  3725. const W2l = SHA512_W_L[i - 2] | 0;
  3726. const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);
  3727. const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);
  3728. // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];
  3729. const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
  3730. const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
  3731. SHA512_W_H[i] = SUMh | 0;
  3732. SHA512_W_L[i] = SUMl | 0;
  3733. }
  3734. let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
  3735. // Compression function main loop, 80 rounds
  3736. for (let i = 0; i < 80; i++) {
  3737. // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)
  3738. const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);
  3739. const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);
  3740. //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
  3741. const CHIh = (Eh & Fh) ^ (~Eh & Gh);
  3742. const CHIl = (El & Fl) ^ (~El & Gl);
  3743. // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]
  3744. // prettier-ignore
  3745. const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
  3746. const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
  3747. const T1l = T1ll | 0;
  3748. // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)
  3749. const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);
  3750. const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);
  3751. const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);
  3752. const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);
  3753. Hh = Gh | 0;
  3754. Hl = Gl | 0;
  3755. Gh = Fh | 0;
  3756. Gl = Fl | 0;
  3757. Fh = Eh | 0;
  3758. Fl = El | 0;
  3759. ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
  3760. Dh = Ch | 0;
  3761. Dl = Cl | 0;
  3762. Ch = Bh | 0;
  3763. Cl = Bl | 0;
  3764. Bh = Ah | 0;
  3765. Bl = Al | 0;
  3766. const All = u64.add3L(T1l, sigma0l, MAJl);
  3767. Ah = u64.add3H(All, T1h, sigma0h, MAJh);
  3768. Al = All | 0;
  3769. }
  3770. // Add the compressed chunk to the current hash value
  3771. ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
  3772. ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
  3773. ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
  3774. ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
  3775. ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
  3776. ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
  3777. ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
  3778. ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
  3779. this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
  3780. }
  3781. roundClean() {
  3782. SHA512_W_H.fill(0);
  3783. SHA512_W_L.fill(0);
  3784. }
  3785. destroy() {
  3786. this.buffer.fill(0);
  3787. this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  3788. }
  3789. }
  3790. const sha512$1 = /* @__PURE__ */ wrapConstructor(() => new SHA512());
  3791. /* Browser Crypto Shims */
  3792. function getGlobal$1() {
  3793. if (typeof self !== 'undefined') {
  3794. return self;
  3795. }
  3796. if (typeof window !== 'undefined') {
  3797. return window;
  3798. }
  3799. if (typeof global !== 'undefined') {
  3800. return global;
  3801. }
  3802. throw new Error('unable to locate global object');
  3803. }
  3804. const anyGlobal = getGlobal$1();
  3805. const crypto = anyGlobal.crypto || anyGlobal.msCrypto;
  3806. function createHash(algo) {
  3807. switch (algo) {
  3808. case "sha256": return sha256$1.create();
  3809. case "sha512": return sha512$1.create();
  3810. }
  3811. assertArgument(false, "invalid hashing algorithm name", "algorithm", algo);
  3812. }
  3813. function createHmac(_algo, key) {
  3814. const algo = ({ sha256: sha256$1, sha512: sha512$1 }[_algo]);
  3815. assertArgument(algo != null, "invalid hmac algorithm", "algorithm", _algo);
  3816. return hmac.create(algo, key);
  3817. }
  3818. function pbkdf2Sync(password, salt, iterations, keylen, _algo) {
  3819. const algo = ({ sha256: sha256$1, sha512: sha512$1 }[_algo]);
  3820. assertArgument(algo != null, "invalid pbkdf2 algorithm", "algorithm", _algo);
  3821. return pbkdf2$1(algo, password, salt, { c: iterations, dkLen: keylen });
  3822. }
  3823. function randomBytes$1(length) {
  3824. assert(crypto != null, "platform does not support secure random numbers", "UNSUPPORTED_OPERATION", {
  3825. operation: "randomBytes"
  3826. });
  3827. assertArgument(Number.isInteger(length) && length > 0 && length <= 1024, "invalid length", "length", length);
  3828. const result = new Uint8Array(length);
  3829. crypto.getRandomValues(result);
  3830. return result;
  3831. }
  3832. /**
  3833. * An **HMAC** enables verification that a given key was used
  3834. * to authenticate a payload.
  3835. *
  3836. * See: [[link-wiki-hmac]]
  3837. *
  3838. * @_subsection: api/crypto:HMAC [about-hmac]
  3839. */
  3840. let locked$4 = false;
  3841. const _computeHmac = function (algorithm, key, data) {
  3842. return createHmac(algorithm, key).update(data).digest();
  3843. };
  3844. let __computeHmac = _computeHmac;
  3845. /**
  3846. * Return the HMAC for %%data%% using the %%key%% key with the underlying
  3847. * %%algo%% used for compression.
  3848. *
  3849. * @example:
  3850. * key = id("some-secret")
  3851. *
  3852. * // Compute the HMAC
  3853. * computeHmac("sha256", key, "0x1337")
  3854. * //_result:
  3855. *
  3856. * // To compute the HMAC of UTF-8 data, the data must be
  3857. * // converted to UTF-8 bytes
  3858. * computeHmac("sha256", key, toUtf8Bytes("Hello World"))
  3859. * //_result:
  3860. *
  3861. */
  3862. function computeHmac(algorithm, _key, _data) {
  3863. const key = getBytes(_key, "key");
  3864. const data = getBytes(_data, "data");
  3865. return hexlify(__computeHmac(algorithm, key, data));
  3866. }
  3867. computeHmac._ = _computeHmac;
  3868. computeHmac.lock = function () { locked$4 = true; };
  3869. computeHmac.register = function (func) {
  3870. if (locked$4) {
  3871. throw new Error("computeHmac is locked");
  3872. }
  3873. __computeHmac = func;
  3874. };
  3875. Object.freeze(computeHmac);
  3876. // SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.
  3877. // It's called a sponge function.
  3878. // Various per round constants calculations
  3879. const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []];
  3880. const _0n$4 = /* @__PURE__ */ BigInt(0);
  3881. const _1n$5 = /* @__PURE__ */ BigInt(1);
  3882. const _2n$3 = /* @__PURE__ */ BigInt(2);
  3883. const _7n = /* @__PURE__ */ BigInt(7);
  3884. const _256n = /* @__PURE__ */ BigInt(256);
  3885. const _0x71n = /* @__PURE__ */ BigInt(0x71);
  3886. for (let round = 0, R = _1n$5, x = 1, y = 0; round < 24; round++) {
  3887. // Pi
  3888. [x, y] = [y, (2 * x + 3 * y) % 5];
  3889. SHA3_PI.push(2 * (5 * y + x));
  3890. // Rotational
  3891. SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);
  3892. // Iota
  3893. let t = _0n$4;
  3894. for (let j = 0; j < 7; j++) {
  3895. R = ((R << _1n$5) ^ ((R >> _7n) * _0x71n)) % _256n;
  3896. if (R & _2n$3)
  3897. t ^= _1n$5 << ((_1n$5 << /* @__PURE__ */ BigInt(j)) - _1n$5);
  3898. }
  3899. _SHA3_IOTA.push(t);
  3900. }
  3901. const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split$1(_SHA3_IOTA, true);
  3902. // Left rotation (without 0, 32, 64)
  3903. const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));
  3904. const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));
  3905. // Same as keccakf1600, but allows to skip some rounds
  3906. function keccakP(s, rounds = 24) {
  3907. const B = new Uint32Array(5 * 2);
  3908. // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
  3909. for (let round = 24 - rounds; round < 24; round++) {
  3910. // Theta θ
  3911. for (let x = 0; x < 10; x++)
  3912. B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
  3913. for (let x = 0; x < 10; x += 2) {
  3914. const idx1 = (x + 8) % 10;
  3915. const idx0 = (x + 2) % 10;
  3916. const B0 = B[idx0];
  3917. const B1 = B[idx0 + 1];
  3918. const Th = rotlH(B0, B1, 1) ^ B[idx1];
  3919. const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
  3920. for (let y = 0; y < 50; y += 10) {
  3921. s[x + y] ^= Th;
  3922. s[x + y + 1] ^= Tl;
  3923. }
  3924. }
  3925. // Rho (ρ) and Pi (π)
  3926. let curH = s[2];
  3927. let curL = s[3];
  3928. for (let t = 0; t < 24; t++) {
  3929. const shift = SHA3_ROTL[t];
  3930. const Th = rotlH(curH, curL, shift);
  3931. const Tl = rotlL(curH, curL, shift);
  3932. const PI = SHA3_PI[t];
  3933. curH = s[PI];
  3934. curL = s[PI + 1];
  3935. s[PI] = Th;
  3936. s[PI + 1] = Tl;
  3937. }
  3938. // Chi (χ)
  3939. for (let y = 0; y < 50; y += 10) {
  3940. for (let x = 0; x < 10; x++)
  3941. B[x] = s[y + x];
  3942. for (let x = 0; x < 10; x++)
  3943. s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
  3944. }
  3945. // Iota (ι)
  3946. s[0] ^= SHA3_IOTA_H[round];
  3947. s[1] ^= SHA3_IOTA_L[round];
  3948. }
  3949. B.fill(0);
  3950. }
  3951. class Keccak extends Hash {
  3952. // NOTE: we accept arguments in bytes instead of bits here.
  3953. constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
  3954. super();
  3955. this.blockLen = blockLen;
  3956. this.suffix = suffix;
  3957. this.outputLen = outputLen;
  3958. this.enableXOF = enableXOF;
  3959. this.rounds = rounds;
  3960. this.pos = 0;
  3961. this.posOut = 0;
  3962. this.finished = false;
  3963. this.destroyed = false;
  3964. // Can be passed from user as dkLen
  3965. number(outputLen);
  3966. // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes
  3967. if (0 >= this.blockLen || this.blockLen >= 200)
  3968. throw new Error('Sha3 supports only keccak-f1600 function');
  3969. this.state = new Uint8Array(200);
  3970. this.state32 = u32(this.state);
  3971. }
  3972. keccak() {
  3973. keccakP(this.state32, this.rounds);
  3974. this.posOut = 0;
  3975. this.pos = 0;
  3976. }
  3977. update(data) {
  3978. exists(this);
  3979. const { blockLen, state } = this;
  3980. data = toBytes(data);
  3981. const len = data.length;
  3982. for (let pos = 0; pos < len;) {
  3983. const take = Math.min(blockLen - this.pos, len - pos);
  3984. for (let i = 0; i < take; i++)
  3985. state[this.pos++] ^= data[pos++];
  3986. if (this.pos === blockLen)
  3987. this.keccak();
  3988. }
  3989. return this;
  3990. }
  3991. finish() {
  3992. if (this.finished)
  3993. return;
  3994. this.finished = true;
  3995. const { state, suffix, pos, blockLen } = this;
  3996. // Do the padding
  3997. state[pos] ^= suffix;
  3998. if ((suffix & 0x80) !== 0 && pos === blockLen - 1)
  3999. this.keccak();
  4000. state[blockLen - 1] ^= 0x80;
  4001. this.keccak();
  4002. }
  4003. writeInto(out) {
  4004. exists(this, false);
  4005. bytes(out);
  4006. this.finish();
  4007. const bufferOut = this.state;
  4008. const { blockLen } = this;
  4009. for (let pos = 0, len = out.length; pos < len;) {
  4010. if (this.posOut >= blockLen)
  4011. this.keccak();
  4012. const take = Math.min(blockLen - this.posOut, len - pos);
  4013. out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
  4014. this.posOut += take;
  4015. pos += take;
  4016. }
  4017. return out;
  4018. }
  4019. xofInto(out) {
  4020. // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF
  4021. if (!this.enableXOF)
  4022. throw new Error('XOF is not possible for this instance');
  4023. return this.writeInto(out);
  4024. }
  4025. xof(bytes) {
  4026. number(bytes);
  4027. return this.xofInto(new Uint8Array(bytes));
  4028. }
  4029. digestInto(out) {
  4030. output(out, this);
  4031. if (this.finished)
  4032. throw new Error('digest() was already called');
  4033. this.writeInto(out);
  4034. this.destroy();
  4035. return out;
  4036. }
  4037. digest() {
  4038. return this.digestInto(new Uint8Array(this.outputLen));
  4039. }
  4040. destroy() {
  4041. this.destroyed = true;
  4042. this.state.fill(0);
  4043. }
  4044. _cloneInto(to) {
  4045. const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
  4046. to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
  4047. to.state32.set(this.state32);
  4048. to.pos = this.pos;
  4049. to.posOut = this.posOut;
  4050. to.finished = this.finished;
  4051. to.rounds = rounds;
  4052. // Suffix can change in cSHAKE
  4053. to.suffix = suffix;
  4054. to.outputLen = outputLen;
  4055. to.enableXOF = enableXOF;
  4056. to.destroyed = this.destroyed;
  4057. return to;
  4058. }
  4059. }
  4060. const gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen));
  4061. /**
  4062. * keccak-256 hash function. Different from SHA3-256.
  4063. * @param message - that would be hashed
  4064. */
  4065. const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8);
  4066. /**
  4067. * Cryptographic hashing functions
  4068. *
  4069. * @_subsection: api/crypto:Hash Functions [about-crypto-hashing]
  4070. */
  4071. let locked$3 = false;
  4072. const _keccak256 = function (data) {
  4073. return keccak_256(data);
  4074. };
  4075. let __keccak256 = _keccak256;
  4076. /**
  4077. * Compute the cryptographic KECCAK256 hash of %%data%%.
  4078. *
  4079. * The %%data%% **must** be a data representation, to compute the
  4080. * hash of UTF-8 data use the [[id]] function.
  4081. *
  4082. * @returns DataHexstring
  4083. * @example:
  4084. * keccak256("0x")
  4085. * //_result:
  4086. *
  4087. * keccak256("0x1337")
  4088. * //_result:
  4089. *
  4090. * keccak256(new Uint8Array([ 0x13, 0x37 ]))
  4091. * //_result:
  4092. *
  4093. * // Strings are assumed to be DataHexString, otherwise it will
  4094. * // throw. To hash UTF-8 data, see the note above.
  4095. * keccak256("Hello World")
  4096. * //_error:
  4097. */
  4098. function keccak256(_data) {
  4099. const data = getBytes(_data, "data");
  4100. return hexlify(__keccak256(data));
  4101. }
  4102. keccak256._ = _keccak256;
  4103. keccak256.lock = function () { locked$3 = true; };
  4104. keccak256.register = function (func) {
  4105. if (locked$3) {
  4106. throw new TypeError("keccak256 is locked");
  4107. }
  4108. __keccak256 = func;
  4109. };
  4110. Object.freeze(keccak256);
  4111. // https://homes.esat.kuleuven.be/~bosselae/ripemd160.html
  4112. // https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf
  4113. const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]);
  4114. const Id = /* @__PURE__ */ Uint8Array.from({ length: 16 }, (_, i) => i);
  4115. const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16);
  4116. let idxL = [Id];
  4117. let idxR = [Pi];
  4118. for (let i = 0; i < 4; i++)
  4119. for (let j of [idxL, idxR])
  4120. j.push(j[i].map((k) => Rho[k]));
  4121. const shifts = /* @__PURE__ */ [
  4122. [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],
  4123. [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],
  4124. [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],
  4125. [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],
  4126. [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],
  4127. ].map((i) => new Uint8Array(i));
  4128. const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j]));
  4129. const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j]));
  4130. const Kl = /* @__PURE__ */ new Uint32Array([
  4131. 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,
  4132. ]);
  4133. const Kr = /* @__PURE__ */ new Uint32Array([
  4134. 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,
  4135. ]);
  4136. // The rotate left (circular left shift) operation for uint32
  4137. const rotl$1 = (word, shift) => (word << shift) | (word >>> (32 - shift));
  4138. // It's called f() in spec.
  4139. function f(group, x, y, z) {
  4140. if (group === 0)
  4141. return x ^ y ^ z;
  4142. else if (group === 1)
  4143. return (x & y) | (~x & z);
  4144. else if (group === 2)
  4145. return (x | ~y) ^ z;
  4146. else if (group === 3)
  4147. return (x & z) | (y & ~z);
  4148. else
  4149. return x ^ (y | ~z);
  4150. }
  4151. // Temporary buffer, not used to store anything between runs
  4152. const BUF = /* @__PURE__ */ new Uint32Array(16);
  4153. class RIPEMD160 extends SHA2 {
  4154. constructor() {
  4155. super(64, 20, 8, true);
  4156. this.h0 = 0x67452301 | 0;
  4157. this.h1 = 0xefcdab89 | 0;
  4158. this.h2 = 0x98badcfe | 0;
  4159. this.h3 = 0x10325476 | 0;
  4160. this.h4 = 0xc3d2e1f0 | 0;
  4161. }
  4162. get() {
  4163. const { h0, h1, h2, h3, h4 } = this;
  4164. return [h0, h1, h2, h3, h4];
  4165. }
  4166. set(h0, h1, h2, h3, h4) {
  4167. this.h0 = h0 | 0;
  4168. this.h1 = h1 | 0;
  4169. this.h2 = h2 | 0;
  4170. this.h3 = h3 | 0;
  4171. this.h4 = h4 | 0;
  4172. }
  4173. process(view, offset) {
  4174. for (let i = 0; i < 16; i++, offset += 4)
  4175. BUF[i] = view.getUint32(offset, true);
  4176. // prettier-ignore
  4177. 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;
  4178. // Instead of iterating 0 to 80, we split it into 5 groups
  4179. // And use the groups in constants, functions, etc. Much simpler
  4180. for (let group = 0; group < 5; group++) {
  4181. const rGroup = 4 - group;
  4182. const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore
  4183. const rl = idxL[group], rr = idxR[group]; // prettier-ignore
  4184. const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore
  4185. for (let i = 0; i < 16; i++) {
  4186. const tl = (rotl$1(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0;
  4187. al = el, el = dl, dl = rotl$1(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore
  4188. }
  4189. // 2 loops are 10% faster
  4190. for (let i = 0; i < 16; i++) {
  4191. const tr = (rotl$1(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0;
  4192. ar = er, er = dr, dr = rotl$1(cr, 10) | 0, cr = br, br = tr; // prettier-ignore
  4193. }
  4194. }
  4195. // Add the compressed chunk to the current hash value
  4196. 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);
  4197. }
  4198. roundClean() {
  4199. BUF.fill(0);
  4200. }
  4201. destroy() {
  4202. this.destroyed = true;
  4203. this.buffer.fill(0);
  4204. this.set(0, 0, 0, 0, 0);
  4205. }
  4206. }
  4207. /**
  4208. * RIPEMD-160 - a hash function from 1990s.
  4209. * @param message - msg that would be hashed
  4210. */
  4211. const ripemd160$1 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160());
  4212. let locked$2 = false;
  4213. const _ripemd160 = function (data) {
  4214. return ripemd160$1(data);
  4215. };
  4216. let __ripemd160 = _ripemd160;
  4217. /**
  4218. * Compute the cryptographic RIPEMD-160 hash of %%data%%.
  4219. *
  4220. * @_docloc: api/crypto:Hash Functions
  4221. * @returns DataHexstring
  4222. *
  4223. * @example:
  4224. * ripemd160("0x")
  4225. * //_result:
  4226. *
  4227. * ripemd160("0x1337")
  4228. * //_result:
  4229. *
  4230. * ripemd160(new Uint8Array([ 0x13, 0x37 ]))
  4231. * //_result:
  4232. *
  4233. */
  4234. function ripemd160(_data) {
  4235. const data = getBytes(_data, "data");
  4236. return hexlify(__ripemd160(data));
  4237. }
  4238. ripemd160._ = _ripemd160;
  4239. ripemd160.lock = function () { locked$2 = true; };
  4240. ripemd160.register = function (func) {
  4241. if (locked$2) {
  4242. throw new TypeError("ripemd160 is locked");
  4243. }
  4244. __ripemd160 = func;
  4245. };
  4246. Object.freeze(ripemd160);
  4247. /**
  4248. * A **Password-Based Key-Derivation Function** is designed to create
  4249. * a sequence of bytes suitible as a **key** from a human-rememberable
  4250. * password.
  4251. *
  4252. * @_subsection: api/crypto:Passwords [about-pbkdf]
  4253. */
  4254. let locked$1 = false;
  4255. const _pbkdf2 = function (password, salt, iterations, keylen, algo) {
  4256. return pbkdf2Sync(password, salt, iterations, keylen, algo);
  4257. };
  4258. let __pbkdf2 = _pbkdf2;
  4259. /**
  4260. * Return the [[link-pbkdf2]] for %%keylen%% bytes for %%password%% using
  4261. * the %%salt%% and using %%iterations%% of %%algo%%.
  4262. *
  4263. * This PBKDF is outdated and should not be used in new projects, but is
  4264. * required to decrypt older files.
  4265. *
  4266. * @example:
  4267. * // The password must be converted to bytes, and it is generally
  4268. * // best practices to ensure the string has been normalized. Many
  4269. * // formats explicitly indicate the normalization form to use.
  4270. * password = "hello"
  4271. * passwordBytes = toUtf8Bytes(password, "NFKC")
  4272. *
  4273. * salt = id("some-salt")
  4274. *
  4275. * // Compute the PBKDF2
  4276. * pbkdf2(passwordBytes, salt, 1024, 16, "sha256")
  4277. * //_result:
  4278. */
  4279. function pbkdf2(_password, _salt, iterations, keylen, algo) {
  4280. const password = getBytes(_password, "password");
  4281. const salt = getBytes(_salt, "salt");
  4282. return hexlify(__pbkdf2(password, salt, iterations, keylen, algo));
  4283. }
  4284. pbkdf2._ = _pbkdf2;
  4285. pbkdf2.lock = function () { locked$1 = true; };
  4286. pbkdf2.register = function (func) {
  4287. if (locked$1) {
  4288. throw new Error("pbkdf2 is locked");
  4289. }
  4290. __pbkdf2 = func;
  4291. };
  4292. Object.freeze(pbkdf2);
  4293. /**
  4294. * A **Cryptographically Secure Random Value** is one that has been
  4295. * generated with additional care take to prevent side-channels
  4296. * from allowing others to detect it and prevent others from through
  4297. * coincidence generate the same values.
  4298. *
  4299. * @_subsection: api/crypto:Random Values [about-crypto-random]
  4300. */
  4301. let locked = false;
  4302. const _randomBytes = function (length) {
  4303. return new Uint8Array(randomBytes$1(length));
  4304. };
  4305. let __randomBytes = _randomBytes;
  4306. /**
  4307. * Return %%length%% bytes of cryptographically secure random data.
  4308. *
  4309. * @example:
  4310. * randomBytes(8)
  4311. * //_result:
  4312. */
  4313. function randomBytes(length) {
  4314. return __randomBytes(length);
  4315. }
  4316. randomBytes._ = _randomBytes;
  4317. randomBytes.lock = function () { locked = true; };
  4318. randomBytes.register = function (func) {
  4319. if (locked) {
  4320. throw new Error("randomBytes is locked");
  4321. }
  4322. __randomBytes = func;
  4323. };
  4324. Object.freeze(randomBytes);
  4325. // RFC 7914 Scrypt KDF
  4326. // Left rotate for uint32
  4327. const rotl = (a, b) => (a << b) | (a >>> (32 - b));
  4328. // The main Scrypt loop: uses Salsa extensively.
  4329. // Six versions of the function were tried, this is the fastest one.
  4330. // prettier-ignore
  4331. function XorAndSalsa(prev, pi, input, ii, out, oi) {
  4332. // Based on https://cr.yp.to/salsa20.html
  4333. // Xor blocks
  4334. let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++];
  4335. let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++];
  4336. let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++];
  4337. let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++];
  4338. let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++];
  4339. let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++];
  4340. let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++];
  4341. let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++];
  4342. // Save state to temporary variables (salsa)
  4343. 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;
  4344. // Main loop (salsa)
  4345. for (let i = 0; i < 8; i += 2) {
  4346. x04 ^= rotl(x00 + x12 | 0, 7);
  4347. x08 ^= rotl(x04 + x00 | 0, 9);
  4348. x12 ^= rotl(x08 + x04 | 0, 13);
  4349. x00 ^= rotl(x12 + x08 | 0, 18);
  4350. x09 ^= rotl(x05 + x01 | 0, 7);
  4351. x13 ^= rotl(x09 + x05 | 0, 9);
  4352. x01 ^= rotl(x13 + x09 | 0, 13);
  4353. x05 ^= rotl(x01 + x13 | 0, 18);
  4354. x14 ^= rotl(x10 + x06 | 0, 7);
  4355. x02 ^= rotl(x14 + x10 | 0, 9);
  4356. x06 ^= rotl(x02 + x14 | 0, 13);
  4357. x10 ^= rotl(x06 + x02 | 0, 18);
  4358. x03 ^= rotl(x15 + x11 | 0, 7);
  4359. x07 ^= rotl(x03 + x15 | 0, 9);
  4360. x11 ^= rotl(x07 + x03 | 0, 13);
  4361. x15 ^= rotl(x11 + x07 | 0, 18);
  4362. x01 ^= rotl(x00 + x03 | 0, 7);
  4363. x02 ^= rotl(x01 + x00 | 0, 9);
  4364. x03 ^= rotl(x02 + x01 | 0, 13);
  4365. x00 ^= rotl(x03 + x02 | 0, 18);
  4366. x06 ^= rotl(x05 + x04 | 0, 7);
  4367. x07 ^= rotl(x06 + x05 | 0, 9);
  4368. x04 ^= rotl(x07 + x06 | 0, 13);
  4369. x05 ^= rotl(x04 + x07 | 0, 18);
  4370. x11 ^= rotl(x10 + x09 | 0, 7);
  4371. x08 ^= rotl(x11 + x10 | 0, 9);
  4372. x09 ^= rotl(x08 + x11 | 0, 13);
  4373. x10 ^= rotl(x09 + x08 | 0, 18);
  4374. x12 ^= rotl(x15 + x14 | 0, 7);
  4375. x13 ^= rotl(x12 + x15 | 0, 9);
  4376. x14 ^= rotl(x13 + x12 | 0, 13);
  4377. x15 ^= rotl(x14 + x13 | 0, 18);
  4378. }
  4379. // Write output (salsa)
  4380. out[oi++] = (y00 + x00) | 0;
  4381. out[oi++] = (y01 + x01) | 0;
  4382. out[oi++] = (y02 + x02) | 0;
  4383. out[oi++] = (y03 + x03) | 0;
  4384. out[oi++] = (y04 + x04) | 0;
  4385. out[oi++] = (y05 + x05) | 0;
  4386. out[oi++] = (y06 + x06) | 0;
  4387. out[oi++] = (y07 + x07) | 0;
  4388. out[oi++] = (y08 + x08) | 0;
  4389. out[oi++] = (y09 + x09) | 0;
  4390. out[oi++] = (y10 + x10) | 0;
  4391. out[oi++] = (y11 + x11) | 0;
  4392. out[oi++] = (y12 + x12) | 0;
  4393. out[oi++] = (y13 + x13) | 0;
  4394. out[oi++] = (y14 + x14) | 0;
  4395. out[oi++] = (y15 + x15) | 0;
  4396. }
  4397. function BlockMix(input, ii, out, oi, r) {
  4398. // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks)
  4399. let head = oi + 0;
  4400. let tail = oi + 16 * r;
  4401. for (let i = 0; i < 16; i++)
  4402. out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1]
  4403. for (let i = 0; i < r; i++, head += 16, ii += 16) {
  4404. // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1
  4405. XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1])
  4406. if (i > 0)
  4407. tail += 16; // First iteration overwrites tmp value in tail
  4408. XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i])
  4409. }
  4410. }
  4411. // Common prologue and epilogue for sync/async functions
  4412. function scryptInit(password, salt, _opts) {
  4413. // Maxmem - 1GB+1KB by default
  4414. const opts = checkOpts({
  4415. dkLen: 32,
  4416. asyncTick: 10,
  4417. maxmem: 1024 ** 3 + 1024,
  4418. }, _opts);
  4419. const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts;
  4420. number(N);
  4421. number(r);
  4422. number(p);
  4423. number(dkLen);
  4424. number(asyncTick);
  4425. number(maxmem);
  4426. if (onProgress !== undefined && typeof onProgress !== 'function')
  4427. throw new Error('progressCb should be function');
  4428. const blockSize = 128 * r;
  4429. const blockSize32 = blockSize / 4;
  4430. if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) {
  4431. // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function
  4432. // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future.
  4433. 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');
  4434. }
  4435. if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) {
  4436. throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)');
  4437. }
  4438. if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) {
  4439. throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32');
  4440. }
  4441. const memUsed = blockSize * (N + p);
  4442. if (memUsed > maxmem) {
  4443. throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`);
  4444. }
  4445. // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor)
  4446. // Since it has only one iteration there is no reason to use async variant
  4447. const B = pbkdf2$1(sha256$1, password, salt, { c: 1, dkLen: blockSize * p });
  4448. const B32 = u32(B);
  4449. // Re-used between parallel iterations. Array(iterations) of B
  4450. const V = u32(new Uint8Array(blockSize * N));
  4451. const tmp = u32(new Uint8Array(blockSize));
  4452. let blockMixCb = () => { };
  4453. if (onProgress) {
  4454. const totalBlockMix = 2 * N * p;
  4455. // Invoke callback if progress changes from 10.01 to 10.02
  4456. // Allows to draw smooth progress bar on up to 8K screen
  4457. const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1);
  4458. let blockMixCnt = 0;
  4459. blockMixCb = () => {
  4460. blockMixCnt++;
  4461. if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix))
  4462. onProgress(blockMixCnt / totalBlockMix);
  4463. };
  4464. }
  4465. return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick };
  4466. }
  4467. function scryptOutput(password, dkLen, B, V, tmp) {
  4468. const res = pbkdf2$1(sha256$1, password, B, { c: 1, dkLen });
  4469. B.fill(0);
  4470. V.fill(0);
  4471. tmp.fill(0);
  4472. return res;
  4473. }
  4474. /**
  4475. * Scrypt KDF from RFC 7914.
  4476. * @param password - pass
  4477. * @param salt - salt
  4478. * @param opts - parameters
  4479. * - `N` is cpu/mem work factor (power of 2 e.g. 2**18)
  4480. * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance
  4481. * - `p` is parallelization factor (1 is common)
  4482. * - `dkLen` is output key length in bytes e.g. 32.
  4483. * - `asyncTick` - (default: 10) max time in ms for which async function can block execution
  4484. * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt
  4485. * - `onProgress` - callback function that would be executed for progress report
  4486. * @returns Derived key
  4487. */
  4488. function scrypt$1(password, salt, opts) {
  4489. const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts);
  4490. for (let pi = 0; pi < p; pi++) {
  4491. const Pi = blockSize32 * pi;
  4492. for (let i = 0; i < blockSize32; i++)
  4493. V[i] = B32[Pi + i]; // V[0] = B[i]
  4494. for (let i = 0, pos = 0; i < N - 1; i++) {
  4495. BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);
  4496. blockMixCb();
  4497. }
  4498. BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element
  4499. blockMixCb();
  4500. for (let i = 0; i < N; i++) {
  4501. // First u32 of the last 64-byte block (u32 is LE)
  4502. const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations
  4503. for (let k = 0; k < blockSize32; k++)
  4504. tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]
  4505. BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])
  4506. blockMixCb();
  4507. }
  4508. }
  4509. return scryptOutput(password, dkLen, B, V, tmp);
  4510. }
  4511. /**
  4512. * Scrypt KDF from RFC 7914.
  4513. */
  4514. async function scryptAsync(password, salt, opts) {
  4515. const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts);
  4516. for (let pi = 0; pi < p; pi++) {
  4517. const Pi = blockSize32 * pi;
  4518. for (let i = 0; i < blockSize32; i++)
  4519. V[i] = B32[Pi + i]; // V[0] = B[i]
  4520. let pos = 0;
  4521. await asyncLoop(N - 1, asyncTick, () => {
  4522. BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);
  4523. blockMixCb();
  4524. });
  4525. BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element
  4526. blockMixCb();
  4527. await asyncLoop(N, asyncTick, () => {
  4528. // First u32 of the last 64-byte block (u32 is LE)
  4529. const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations
  4530. for (let k = 0; k < blockSize32; k++)
  4531. tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]
  4532. BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])
  4533. blockMixCb();
  4534. });
  4535. }
  4536. return scryptOutput(password, dkLen, B, V, tmp);
  4537. }
  4538. let lockedSync = false, lockedAsync = false;
  4539. const _scryptAsync = async function (passwd, salt, N, r, p, dkLen, onProgress) {
  4540. return await scryptAsync(passwd, salt, { N, r, p, dkLen, onProgress });
  4541. };
  4542. const _scryptSync = function (passwd, salt, N, r, p, dkLen) {
  4543. return scrypt$1(passwd, salt, { N, r, p, dkLen });
  4544. };
  4545. let __scryptAsync = _scryptAsync;
  4546. let __scryptSync = _scryptSync;
  4547. /**
  4548. * The [[link-wiki-scrypt]] uses a memory and cpu hard method of
  4549. * derivation to increase the resource cost to brute-force a password
  4550. * for a given key.
  4551. *
  4552. * This means this algorithm is intentionally slow, and can be tuned to
  4553. * become slower. As computation and memory speed improve over time,
  4554. * increasing the difficulty maintains the cost of an attacker.
  4555. *
  4556. * For example, if a target time of 5 seconds is used, a legitimate user
  4557. * which knows their password requires only 5 seconds to unlock their
  4558. * account. A 6 character password has 68 billion possibilities, which
  4559. * would require an attacker to invest over 10,000 years of CPU time. This
  4560. * is of course a crude example (as password generally aren't random),
  4561. * but demonstrates to value of imposing large costs to decryption.
  4562. *
  4563. * For this reason, if building a UI which involved decrypting or
  4564. * encrypting datsa using scrypt, it is recommended to use a
  4565. * [[ProgressCallback]] (as event short periods can seem lik an eternity
  4566. * if the UI freezes). Including the phrase //"decrypting"// in the UI
  4567. * can also help, assuring the user their waiting is for a good reason.
  4568. *
  4569. * @_docloc: api/crypto:Passwords
  4570. *
  4571. * @example:
  4572. * // The password must be converted to bytes, and it is generally
  4573. * // best practices to ensure the string has been normalized. Many
  4574. * // formats explicitly indicate the normalization form to use.
  4575. * password = "hello"
  4576. * passwordBytes = toUtf8Bytes(password, "NFKC")
  4577. *
  4578. * salt = id("some-salt")
  4579. *
  4580. * // Compute the scrypt
  4581. * scrypt(passwordBytes, salt, 1024, 8, 1, 16)
  4582. * //_result:
  4583. */
  4584. async function scrypt(_passwd, _salt, N, r, p, dkLen, progress) {
  4585. const passwd = getBytes(_passwd, "passwd");
  4586. const salt = getBytes(_salt, "salt");
  4587. return hexlify(await __scryptAsync(passwd, salt, N, r, p, dkLen, progress));
  4588. }
  4589. scrypt._ = _scryptAsync;
  4590. scrypt.lock = function () { lockedAsync = true; };
  4591. scrypt.register = function (func) {
  4592. if (lockedAsync) {
  4593. throw new Error("scrypt is locked");
  4594. }
  4595. __scryptAsync = func;
  4596. };
  4597. Object.freeze(scrypt);
  4598. /**
  4599. * Provides a synchronous variant of [[scrypt]].
  4600. *
  4601. * This will completely lock up and freeze the UI in a browser and will
  4602. * prevent any event loop from progressing. For this reason, it is
  4603. * preferred to use the [async variant](scrypt).
  4604. *
  4605. * @_docloc: api/crypto:Passwords
  4606. *
  4607. * @example:
  4608. * // The password must be converted to bytes, and it is generally
  4609. * // best practices to ensure the string has been normalized. Many
  4610. * // formats explicitly indicate the normalization form to use.
  4611. * password = "hello"
  4612. * passwordBytes = toUtf8Bytes(password, "NFKC")
  4613. *
  4614. * salt = id("some-salt")
  4615. *
  4616. * // Compute the scrypt
  4617. * scryptSync(passwordBytes, salt, 1024, 8, 1, 16)
  4618. * //_result:
  4619. */
  4620. function scryptSync(_passwd, _salt, N, r, p, dkLen) {
  4621. const passwd = getBytes(_passwd, "passwd");
  4622. const salt = getBytes(_salt, "salt");
  4623. return hexlify(__scryptSync(passwd, salt, N, r, p, dkLen));
  4624. }
  4625. scryptSync._ = _scryptSync;
  4626. scryptSync.lock = function () { lockedSync = true; };
  4627. scryptSync.register = function (func) {
  4628. if (lockedSync) {
  4629. throw new Error("scryptSync is locked");
  4630. }
  4631. __scryptSync = func;
  4632. };
  4633. Object.freeze(scryptSync);
  4634. const _sha256 = function (data) {
  4635. return createHash("sha256").update(data).digest();
  4636. };
  4637. const _sha512 = function (data) {
  4638. return createHash("sha512").update(data).digest();
  4639. };
  4640. let __sha256 = _sha256;
  4641. let __sha512 = _sha512;
  4642. let locked256 = false, locked512 = false;
  4643. /**
  4644. * Compute the cryptographic SHA2-256 hash of %%data%%.
  4645. *
  4646. * @_docloc: api/crypto:Hash Functions
  4647. * @returns DataHexstring
  4648. *
  4649. * @example:
  4650. * sha256("0x")
  4651. * //_result:
  4652. *
  4653. * sha256("0x1337")
  4654. * //_result:
  4655. *
  4656. * sha256(new Uint8Array([ 0x13, 0x37 ]))
  4657. * //_result:
  4658. *
  4659. */
  4660. function sha256(_data) {
  4661. const data = getBytes(_data, "data");
  4662. return hexlify(__sha256(data));
  4663. }
  4664. sha256._ = _sha256;
  4665. sha256.lock = function () { locked256 = true; };
  4666. sha256.register = function (func) {
  4667. if (locked256) {
  4668. throw new Error("sha256 is locked");
  4669. }
  4670. __sha256 = func;
  4671. };
  4672. Object.freeze(sha256);
  4673. /**
  4674. * Compute the cryptographic SHA2-512 hash of %%data%%.
  4675. *
  4676. * @_docloc: api/crypto:Hash Functions
  4677. * @returns DataHexstring
  4678. *
  4679. * @example:
  4680. * sha512("0x")
  4681. * //_result:
  4682. *
  4683. * sha512("0x1337")
  4684. * //_result:
  4685. *
  4686. * sha512(new Uint8Array([ 0x13, 0x37 ]))
  4687. * //_result:
  4688. */
  4689. function sha512(_data) {
  4690. const data = getBytes(_data, "data");
  4691. return hexlify(__sha512(data));
  4692. }
  4693. sha512._ = _sha512;
  4694. sha512.lock = function () { locked512 = true; };
  4695. sha512.register = function (func) {
  4696. if (locked512) {
  4697. throw new Error("sha512 is locked");
  4698. }
  4699. __sha512 = func;
  4700. };
  4701. Object.freeze(sha256);
  4702. /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
  4703. // 100 lines of code in the file are duplicated from noble-hashes (utils).
  4704. // This is OK: `abstract` directory does not use noble-hashes.
  4705. // User may opt-in into using different hashing library. This way, noble-hashes
  4706. // won't be included into their bundle.
  4707. const _0n$3 = BigInt(0);
  4708. const _1n$4 = BigInt(1);
  4709. const _2n$2 = BigInt(2);
  4710. const u8a = (a) => a instanceof Uint8Array;
  4711. const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
  4712. /**
  4713. * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
  4714. */
  4715. function bytesToHex(bytes) {
  4716. if (!u8a(bytes))
  4717. throw new Error('Uint8Array expected');
  4718. // pre-caching improves the speed 6x
  4719. let hex = '';
  4720. for (let i = 0; i < bytes.length; i++) {
  4721. hex += hexes[bytes[i]];
  4722. }
  4723. return hex;
  4724. }
  4725. function numberToHexUnpadded(num) {
  4726. const hex = num.toString(16);
  4727. return hex.length & 1 ? `0${hex}` : hex;
  4728. }
  4729. function hexToNumber(hex) {
  4730. if (typeof hex !== 'string')
  4731. throw new Error('hex string expected, got ' + typeof hex);
  4732. // Big Endian
  4733. return BigInt(hex === '' ? '0' : `0x${hex}`);
  4734. }
  4735. /**
  4736. * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
  4737. */
  4738. function hexToBytes(hex) {
  4739. if (typeof hex !== 'string')
  4740. throw new Error('hex string expected, got ' + typeof hex);
  4741. const len = hex.length;
  4742. if (len % 2)
  4743. throw new Error('padded hex string expected, got unpadded hex of length ' + len);
  4744. const array = new Uint8Array(len / 2);
  4745. for (let i = 0; i < array.length; i++) {
  4746. const j = i * 2;
  4747. const hexByte = hex.slice(j, j + 2);
  4748. const byte = Number.parseInt(hexByte, 16);
  4749. if (Number.isNaN(byte) || byte < 0)
  4750. throw new Error('Invalid byte sequence');
  4751. array[i] = byte;
  4752. }
  4753. return array;
  4754. }
  4755. // BE: Big Endian, LE: Little Endian
  4756. function bytesToNumberBE(bytes) {
  4757. return hexToNumber(bytesToHex(bytes));
  4758. }
  4759. function bytesToNumberLE(bytes) {
  4760. if (!u8a(bytes))
  4761. throw new Error('Uint8Array expected');
  4762. return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
  4763. }
  4764. function numberToBytesBE(n, len) {
  4765. return hexToBytes(n.toString(16).padStart(len * 2, '0'));
  4766. }
  4767. function numberToBytesLE(n, len) {
  4768. return numberToBytesBE(n, len).reverse();
  4769. }
  4770. // Unpadded, rarely used
  4771. function numberToVarBytesBE(n) {
  4772. return hexToBytes(numberToHexUnpadded(n));
  4773. }
  4774. /**
  4775. * Takes hex string or Uint8Array, converts to Uint8Array.
  4776. * Validates output length.
  4777. * Will throw error for other types.
  4778. * @param title descriptive title for an error e.g. 'private key'
  4779. * @param hex hex string or Uint8Array
  4780. * @param expectedLength optional, will compare to result array's length
  4781. * @returns
  4782. */
  4783. function ensureBytes(title, hex, expectedLength) {
  4784. let res;
  4785. if (typeof hex === 'string') {
  4786. try {
  4787. res = hexToBytes(hex);
  4788. }
  4789. catch (e) {
  4790. throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`);
  4791. }
  4792. }
  4793. else if (u8a(hex)) {
  4794. // Uint8Array.from() instead of hash.slice() because node.js Buffer
  4795. // is instance of Uint8Array, and its slice() creates **mutable** copy
  4796. res = Uint8Array.from(hex);
  4797. }
  4798. else {
  4799. throw new Error(`${title} must be hex string or Uint8Array`);
  4800. }
  4801. const len = res.length;
  4802. if (typeof expectedLength === 'number' && len !== expectedLength)
  4803. throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
  4804. return res;
  4805. }
  4806. /**
  4807. * Copies several Uint8Arrays into one.
  4808. */
  4809. function concatBytes(...arrays) {
  4810. const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));
  4811. let pad = 0; // walk through each item, ensure they have proper type
  4812. arrays.forEach((a) => {
  4813. if (!u8a(a))
  4814. throw new Error('Uint8Array expected');
  4815. r.set(a, pad);
  4816. pad += a.length;
  4817. });
  4818. return r;
  4819. }
  4820. function equalBytes(b1, b2) {
  4821. // We don't care about timing attacks here
  4822. if (b1.length !== b2.length)
  4823. return false;
  4824. for (let i = 0; i < b1.length; i++)
  4825. if (b1[i] !== b2[i])
  4826. return false;
  4827. return true;
  4828. }
  4829. /**
  4830. * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
  4831. */
  4832. function utf8ToBytes(str) {
  4833. if (typeof str !== 'string')
  4834. throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
  4835. return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
  4836. }
  4837. // Bit operations
  4838. /**
  4839. * Calculates amount of bits in a bigint.
  4840. * Same as `n.toString(2).length`
  4841. */
  4842. function bitLen(n) {
  4843. let len;
  4844. for (len = 0; n > _0n$3; n >>= _1n$4, len += 1)
  4845. ;
  4846. return len;
  4847. }
  4848. /**
  4849. * Gets single bit at position.
  4850. * NOTE: first bit position is 0 (same as arrays)
  4851. * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
  4852. */
  4853. function bitGet(n, pos) {
  4854. return (n >> BigInt(pos)) & _1n$4;
  4855. }
  4856. /**
  4857. * Sets single bit at position.
  4858. */
  4859. const bitSet = (n, pos, value) => {
  4860. return n | ((value ? _1n$4 : _0n$3) << BigInt(pos));
  4861. };
  4862. /**
  4863. * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
  4864. * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
  4865. */
  4866. const bitMask = (n) => (_2n$2 << BigInt(n - 1)) - _1n$4;
  4867. // DRBG
  4868. const u8n = (data) => new Uint8Array(data); // creates Uint8Array
  4869. const u8fr = (arr) => Uint8Array.from(arr); // another shortcut
  4870. /**
  4871. * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
  4872. * @returns function that will call DRBG until 2nd arg returns something meaningful
  4873. * @example
  4874. * const drbg = createHmacDRBG<Key>(32, 32, hmac);
  4875. * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
  4876. */
  4877. function createHmacDrbg(hashLen, qByteLen, hmacFn) {
  4878. if (typeof hashLen !== 'number' || hashLen < 2)
  4879. throw new Error('hashLen must be a number');
  4880. if (typeof qByteLen !== 'number' || qByteLen < 2)
  4881. throw new Error('qByteLen must be a number');
  4882. if (typeof hmacFn !== 'function')
  4883. throw new Error('hmacFn must be a function');
  4884. // Step B, Step C: set hashLen to 8*ceil(hlen/8)
  4885. let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
  4886. let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same
  4887. let i = 0; // Iterations counter, will throw when over 1000
  4888. const reset = () => {
  4889. v.fill(1);
  4890. k.fill(0);
  4891. i = 0;
  4892. };
  4893. const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)
  4894. const reseed = (seed = u8n()) => {
  4895. // HMAC-DRBG reseed() function. Steps D-G
  4896. k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)
  4897. v = h(); // v = hmac(k || v)
  4898. if (seed.length === 0)
  4899. return;
  4900. k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)
  4901. v = h(); // v = hmac(k || v)
  4902. };
  4903. const gen = () => {
  4904. // HMAC-DRBG generate() function
  4905. if (i++ >= 1000)
  4906. throw new Error('drbg: tried 1000 values');
  4907. let len = 0;
  4908. const out = [];
  4909. while (len < qByteLen) {
  4910. v = h();
  4911. const sl = v.slice();
  4912. out.push(sl);
  4913. len += v.length;
  4914. }
  4915. return concatBytes(...out);
  4916. };
  4917. const genUntil = (seed, pred) => {
  4918. reset();
  4919. reseed(seed); // Steps D-G
  4920. let res = undefined; // Step H: grind until k is in [1..n-1]
  4921. while (!(res = pred(gen())))
  4922. reseed();
  4923. reset();
  4924. return res;
  4925. };
  4926. return genUntil;
  4927. }
  4928. // Validating curves and fields
  4929. const validatorFns = {
  4930. bigint: (val) => typeof val === 'bigint',
  4931. function: (val) => typeof val === 'function',
  4932. boolean: (val) => typeof val === 'boolean',
  4933. string: (val) => typeof val === 'string',
  4934. stringOrUint8Array: (val) => typeof val === 'string' || val instanceof Uint8Array,
  4935. isSafeInteger: (val) => Number.isSafeInteger(val),
  4936. array: (val) => Array.isArray(val),
  4937. field: (val, object) => object.Fp.isValid(val),
  4938. hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),
  4939. };
  4940. // type Record<K extends string | number | symbol, T> = { [P in K]: T; }
  4941. function validateObject(object, validators, optValidators = {}) {
  4942. const checkField = (fieldName, type, isOptional) => {
  4943. const checkVal = validatorFns[type];
  4944. if (typeof checkVal !== 'function')
  4945. throw new Error(`Invalid validator "${type}", expected function`);
  4946. const val = object[fieldName];
  4947. if (isOptional && val === undefined)
  4948. return;
  4949. if (!checkVal(val, object)) {
  4950. throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);
  4951. }
  4952. };
  4953. for (const [fieldName, type] of Object.entries(validators))
  4954. checkField(fieldName, type, false);
  4955. for (const [fieldName, type] of Object.entries(optValidators))
  4956. checkField(fieldName, type, true);
  4957. return object;
  4958. }
  4959. // validate type tests
  4960. // const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };
  4961. // const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!
  4962. // // Should fail type-check
  4963. // const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });
  4964. // const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });
  4965. // const z3 = validateObject(o, { test: 'boolean', z: 'bug' });
  4966. // const z4 = validateObject(o, { a: 'boolean', z: 'bug' });
  4967. var ut = /*#__PURE__*/Object.freeze({
  4968. __proto__: null,
  4969. bitGet: bitGet,
  4970. bitLen: bitLen,
  4971. bitMask: bitMask,
  4972. bitSet: bitSet,
  4973. bytesToHex: bytesToHex,
  4974. bytesToNumberBE: bytesToNumberBE,
  4975. bytesToNumberLE: bytesToNumberLE,
  4976. concatBytes: concatBytes,
  4977. createHmacDrbg: createHmacDrbg,
  4978. ensureBytes: ensureBytes,
  4979. equalBytes: equalBytes,
  4980. hexToBytes: hexToBytes,
  4981. hexToNumber: hexToNumber,
  4982. numberToBytesBE: numberToBytesBE,
  4983. numberToBytesLE: numberToBytesLE,
  4984. numberToHexUnpadded: numberToHexUnpadded,
  4985. numberToVarBytesBE: numberToVarBytesBE,
  4986. utf8ToBytes: utf8ToBytes,
  4987. validateObject: validateObject
  4988. });
  4989. /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
  4990. // Utilities for modular arithmetics and finite fields
  4991. // prettier-ignore
  4992. const _0n$2 = BigInt(0), _1n$3 = BigInt(1), _2n$1 = BigInt(2), _3n$1 = BigInt(3);
  4993. // prettier-ignore
  4994. const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);
  4995. // prettier-ignore
  4996. BigInt(9); BigInt(16);
  4997. // Calculates a modulo b
  4998. function mod(a, b) {
  4999. const result = a % b;
  5000. return result >= _0n$2 ? result : b + result;
  5001. }
  5002. /**
  5003. * Efficiently raise num to power and do modular division.
  5004. * Unsafe in some contexts: uses ladder, so can expose bigint bits.
  5005. * @example
  5006. * pow(2n, 6n, 11n) // 64n % 11n == 9n
  5007. */
  5008. // TODO: use field version && remove
  5009. function pow(num, power, modulo) {
  5010. if (modulo <= _0n$2 || power < _0n$2)
  5011. throw new Error('Expected power/modulo > 0');
  5012. if (modulo === _1n$3)
  5013. return _0n$2;
  5014. let res = _1n$3;
  5015. while (power > _0n$2) {
  5016. if (power & _1n$3)
  5017. res = (res * num) % modulo;
  5018. num = (num * num) % modulo;
  5019. power >>= _1n$3;
  5020. }
  5021. return res;
  5022. }
  5023. // Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)
  5024. function pow2(x, power, modulo) {
  5025. let res = x;
  5026. while (power-- > _0n$2) {
  5027. res *= res;
  5028. res %= modulo;
  5029. }
  5030. return res;
  5031. }
  5032. // Inverses number over modulo
  5033. function invert(number, modulo) {
  5034. if (number === _0n$2 || modulo <= _0n$2) {
  5035. throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
  5036. }
  5037. // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/
  5038. // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
  5039. let a = mod(number, modulo);
  5040. let b = modulo;
  5041. // prettier-ignore
  5042. let x = _0n$2, u = _1n$3;
  5043. while (a !== _0n$2) {
  5044. // JIT applies optimization if those two lines follow each other
  5045. const q = b / a;
  5046. const r = b % a;
  5047. const m = x - u * q;
  5048. // prettier-ignore
  5049. b = a, a = r, x = u, u = m;
  5050. }
  5051. const gcd = b;
  5052. if (gcd !== _1n$3)
  5053. throw new Error('invert: does not exist');
  5054. return mod(x, modulo);
  5055. }
  5056. /**
  5057. * Tonelli-Shanks square root search algorithm.
  5058. * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
  5059. * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
  5060. * Will start an infinite loop if field order P is not prime.
  5061. * @param P field order
  5062. * @returns function that takes field Fp (created from P) and number n
  5063. */
  5064. function tonelliShanks(P) {
  5065. // Legendre constant: used to calculate Legendre symbol (a | p),
  5066. // which denotes the value of a^((p-1)/2) (mod p).
  5067. // (a | p) ≡ 1 if a is a square (mod p)
  5068. // (a | p) ≡ -1 if a is not a square (mod p)
  5069. // (a | p) ≡ 0 if a ≡ 0 (mod p)
  5070. const legendreC = (P - _1n$3) / _2n$1;
  5071. let Q, S, Z;
  5072. // Step 1: By factoring out powers of 2 from p - 1,
  5073. // find q and s such that p - 1 = q*(2^s) with q odd
  5074. for (Q = P - _1n$3, S = 0; Q % _2n$1 === _0n$2; Q /= _2n$1, S++)
  5075. ;
  5076. // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq
  5077. for (Z = _2n$1; Z < P && pow(Z, legendreC, P) !== P - _1n$3; Z++)
  5078. ;
  5079. // Fast-path
  5080. if (S === 1) {
  5081. const p1div4 = (P + _1n$3) / _4n;
  5082. return function tonelliFast(Fp, n) {
  5083. const root = Fp.pow(n, p1div4);
  5084. if (!Fp.eql(Fp.sqr(root), n))
  5085. throw new Error('Cannot find square root');
  5086. return root;
  5087. };
  5088. }
  5089. // Slow-path
  5090. const Q1div2 = (Q + _1n$3) / _2n$1;
  5091. return function tonelliSlow(Fp, n) {
  5092. // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1
  5093. if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))
  5094. throw new Error('Cannot find square root');
  5095. let r = S;
  5096. // TODO: will fail at Fp2/etc
  5097. let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b
  5098. let x = Fp.pow(n, Q1div2); // first guess at the square root
  5099. let b = Fp.pow(n, Q); // first guess at the fudge factor
  5100. while (!Fp.eql(b, Fp.ONE)) {
  5101. if (Fp.eql(b, Fp.ZERO))
  5102. return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)
  5103. // Find m such b^(2^m)==1
  5104. let m = 1;
  5105. for (let t2 = Fp.sqr(b); m < r; m++) {
  5106. if (Fp.eql(t2, Fp.ONE))
  5107. break;
  5108. t2 = Fp.sqr(t2); // t2 *= t2
  5109. }
  5110. // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow
  5111. const ge = Fp.pow(g, _1n$3 << BigInt(r - m - 1)); // ge = 2^(r-m-1)
  5112. g = Fp.sqr(ge); // g = ge * ge
  5113. x = Fp.mul(x, ge); // x *= ge
  5114. b = Fp.mul(b, g); // b *= g
  5115. r = m;
  5116. }
  5117. return x;
  5118. };
  5119. }
  5120. function FpSqrt(P) {
  5121. // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.
  5122. // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
  5123. // P ≡ 3 (mod 4)
  5124. // √n = n^((P+1)/4)
  5125. if (P % _4n === _3n$1) {
  5126. // Not all roots possible!
  5127. // const ORDER =
  5128. // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;
  5129. // const NUM = 72057594037927816n;
  5130. const p1div4 = (P + _1n$3) / _4n;
  5131. return function sqrt3mod4(Fp, n) {
  5132. const root = Fp.pow(n, p1div4);
  5133. // Throw if root**2 != n
  5134. if (!Fp.eql(Fp.sqr(root), n))
  5135. throw new Error('Cannot find square root');
  5136. return root;
  5137. };
  5138. }
  5139. // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)
  5140. if (P % _8n === _5n) {
  5141. const c1 = (P - _5n) / _8n;
  5142. return function sqrt5mod8(Fp, n) {
  5143. const n2 = Fp.mul(n, _2n$1);
  5144. const v = Fp.pow(n2, c1);
  5145. const nv = Fp.mul(n, v);
  5146. const i = Fp.mul(Fp.mul(nv, _2n$1), v);
  5147. const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
  5148. if (!Fp.eql(Fp.sqr(root), n))
  5149. throw new Error('Cannot find square root');
  5150. return root;
  5151. };
  5152. }
  5153. // Other cases: Tonelli-Shanks algorithm
  5154. return tonelliShanks(P);
  5155. }
  5156. // prettier-ignore
  5157. const FIELD_FIELDS = [
  5158. 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
  5159. 'eql', 'add', 'sub', 'mul', 'pow', 'div',
  5160. 'addN', 'subN', 'mulN', 'sqrN'
  5161. ];
  5162. function validateField(field) {
  5163. const initial = {
  5164. ORDER: 'bigint',
  5165. MASK: 'bigint',
  5166. BYTES: 'isSafeInteger',
  5167. BITS: 'isSafeInteger',
  5168. };
  5169. const opts = FIELD_FIELDS.reduce((map, val) => {
  5170. map[val] = 'function';
  5171. return map;
  5172. }, initial);
  5173. return validateObject(field, opts);
  5174. }
  5175. // Generic field functions
  5176. /**
  5177. * Same as `pow` but for Fp: non-constant-time.
  5178. * Unsafe in some contexts: uses ladder, so can expose bigint bits.
  5179. */
  5180. function FpPow(f, num, power) {
  5181. // Should have same speed as pow for bigints
  5182. // TODO: benchmark!
  5183. if (power < _0n$2)
  5184. throw new Error('Expected power > 0');
  5185. if (power === _0n$2)
  5186. return f.ONE;
  5187. if (power === _1n$3)
  5188. return num;
  5189. let p = f.ONE;
  5190. let d = num;
  5191. while (power > _0n$2) {
  5192. if (power & _1n$3)
  5193. p = f.mul(p, d);
  5194. d = f.sqr(d);
  5195. power >>= _1n$3;
  5196. }
  5197. return p;
  5198. }
  5199. /**
  5200. * Efficiently invert an array of Field elements.
  5201. * `inv(0)` will return `undefined` here: make sure to throw an error.
  5202. */
  5203. function FpInvertBatch(f, nums) {
  5204. const tmp = new Array(nums.length);
  5205. // Walk from first to last, multiply them by each other MOD p
  5206. const lastMultiplied = nums.reduce((acc, num, i) => {
  5207. if (f.is0(num))
  5208. return acc;
  5209. tmp[i] = acc;
  5210. return f.mul(acc, num);
  5211. }, f.ONE);
  5212. // Invert last element
  5213. const inverted = f.inv(lastMultiplied);
  5214. // Walk from last to first, multiply them by inverted each other MOD p
  5215. nums.reduceRight((acc, num, i) => {
  5216. if (f.is0(num))
  5217. return acc;
  5218. tmp[i] = f.mul(acc, tmp[i]);
  5219. return f.mul(acc, num);
  5220. }, inverted);
  5221. return tmp;
  5222. }
  5223. // CURVE.n lengths
  5224. function nLength(n, nBitLength) {
  5225. // Bit size, byte size of CURVE.n
  5226. const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
  5227. const nByteLength = Math.ceil(_nBitLength / 8);
  5228. return { nBitLength: _nBitLength, nByteLength };
  5229. }
  5230. /**
  5231. * Initializes a finite field over prime. **Non-primes are not supported.**
  5232. * Do not init in loop: slow. Very fragile: always run a benchmark on a change.
  5233. * Major performance optimizations:
  5234. * * a) denormalized operations like mulN instead of mul
  5235. * * b) same object shape: never add or remove keys
  5236. * * c) Object.freeze
  5237. * @param ORDER prime positive bigint
  5238. * @param bitLen how many bits the field consumes
  5239. * @param isLE (def: false) if encoding / decoding should be in little-endian
  5240. * @param redef optional faster redefinitions of sqrt and other methods
  5241. */
  5242. function Field(ORDER, bitLen, isLE = false, redef = {}) {
  5243. if (ORDER <= _0n$2)
  5244. throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);
  5245. const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);
  5246. if (BYTES > 2048)
  5247. throw new Error('Field lengths over 2048 bytes are not supported');
  5248. const sqrtP = FpSqrt(ORDER);
  5249. const f = Object.freeze({
  5250. ORDER,
  5251. BITS,
  5252. BYTES,
  5253. MASK: bitMask(BITS),
  5254. ZERO: _0n$2,
  5255. ONE: _1n$3,
  5256. create: (num) => mod(num, ORDER),
  5257. isValid: (num) => {
  5258. if (typeof num !== 'bigint')
  5259. throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
  5260. return _0n$2 <= num && num < ORDER; // 0 is valid element, but it's not invertible
  5261. },
  5262. is0: (num) => num === _0n$2,
  5263. isOdd: (num) => (num & _1n$3) === _1n$3,
  5264. neg: (num) => mod(-num, ORDER),
  5265. eql: (lhs, rhs) => lhs === rhs,
  5266. sqr: (num) => mod(num * num, ORDER),
  5267. add: (lhs, rhs) => mod(lhs + rhs, ORDER),
  5268. sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
  5269. mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
  5270. pow: (num, power) => FpPow(f, num, power),
  5271. div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
  5272. // Same as above, but doesn't normalize
  5273. sqrN: (num) => num * num,
  5274. addN: (lhs, rhs) => lhs + rhs,
  5275. subN: (lhs, rhs) => lhs - rhs,
  5276. mulN: (lhs, rhs) => lhs * rhs,
  5277. inv: (num) => invert(num, ORDER),
  5278. sqrt: redef.sqrt || ((n) => sqrtP(f, n)),
  5279. invertBatch: (lst) => FpInvertBatch(f, lst),
  5280. // TODO: do we really need constant cmov?
  5281. // We don't have const-time bigints anyway, so probably will be not very useful
  5282. cmov: (a, b, c) => (c ? b : a),
  5283. toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
  5284. fromBytes: (bytes) => {
  5285. if (bytes.length !== BYTES)
  5286. throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);
  5287. return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
  5288. },
  5289. });
  5290. return Object.freeze(f);
  5291. }
  5292. /**
  5293. * Returns total number of bytes consumed by the field element.
  5294. * For example, 32 bytes for usual 256-bit weierstrass curve.
  5295. * @param fieldOrder number of field elements, usually CURVE.n
  5296. * @returns byte length of field
  5297. */
  5298. function getFieldBytesLength(fieldOrder) {
  5299. if (typeof fieldOrder !== 'bigint')
  5300. throw new Error('field order must be bigint');
  5301. const bitLength = fieldOrder.toString(2).length;
  5302. return Math.ceil(bitLength / 8);
  5303. }
  5304. /**
  5305. * Returns minimal amount of bytes that can be safely reduced
  5306. * by field order.
  5307. * Should be 2^-128 for 128-bit curve such as P256.
  5308. * @param fieldOrder number of field elements, usually CURVE.n
  5309. * @returns byte length of target hash
  5310. */
  5311. function getMinHashLength(fieldOrder) {
  5312. const length = getFieldBytesLength(fieldOrder);
  5313. return length + Math.ceil(length / 2);
  5314. }
  5315. /**
  5316. * "Constant-time" private key generation utility.
  5317. * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
  5318. * and convert them into private scalar, with the modulo bias being negligible.
  5319. * Needs at least 48 bytes of input for 32-byte private key.
  5320. * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
  5321. * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
  5322. * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
  5323. * @param hash hash output from SHA3 or a similar function
  5324. * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
  5325. * @param isLE interpret hash bytes as LE num
  5326. * @returns valid private scalar
  5327. */
  5328. function mapHashToField(key, fieldOrder, isLE = false) {
  5329. const len = key.length;
  5330. const fieldLen = getFieldBytesLength(fieldOrder);
  5331. const minLen = getMinHashLength(fieldOrder);
  5332. // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
  5333. if (len < 16 || len < minLen || len > 1024)
  5334. throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);
  5335. const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);
  5336. // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
  5337. const reduced = mod(num, fieldOrder - _1n$3) + _1n$3;
  5338. return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
  5339. }
  5340. /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
  5341. // Abelian group utilities
  5342. const _0n$1 = BigInt(0);
  5343. const _1n$2 = BigInt(1);
  5344. // Elliptic curve multiplication of Point by scalar. Fragile.
  5345. // Scalars should always be less than curve order: this should be checked inside of a curve itself.
  5346. // Creates precomputation tables for fast multiplication:
  5347. // - private scalar is split by fixed size windows of W bits
  5348. // - every window point is collected from window's table & added to accumulator
  5349. // - since windows are different, same point inside tables won't be accessed more than once per calc
  5350. // - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
  5351. // - +1 window is neccessary for wNAF
  5352. // - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
  5353. // TODO: Research returning 2d JS array of windows, instead of a single window. This would allow
  5354. // windows to be in different memory locations
  5355. function wNAF(c, bits) {
  5356. const constTimeNegate = (condition, item) => {
  5357. const neg = item.negate();
  5358. return condition ? neg : item;
  5359. };
  5360. const opts = (W) => {
  5361. const windows = Math.ceil(bits / W) + 1; // +1, because
  5362. const windowSize = 2 ** (W - 1); // -1 because we skip zero
  5363. return { windows, windowSize };
  5364. };
  5365. return {
  5366. constTimeNegate,
  5367. // non-const time multiplication ladder
  5368. unsafeLadder(elm, n) {
  5369. let p = c.ZERO;
  5370. let d = elm;
  5371. while (n > _0n$1) {
  5372. if (n & _1n$2)
  5373. p = p.add(d);
  5374. d = d.double();
  5375. n >>= _1n$2;
  5376. }
  5377. return p;
  5378. },
  5379. /**
  5380. * Creates a wNAF precomputation window. Used for caching.
  5381. * Default window size is set by `utils.precompute()` and is equal to 8.
  5382. * Number of precomputed points depends on the curve size:
  5383. * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
  5384. * - 𝑊 is the window size
  5385. * - 𝑛 is the bitlength of the curve order.
  5386. * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
  5387. * @returns precomputed point tables flattened to a single array
  5388. */
  5389. precomputeWindow(elm, W) {
  5390. const { windows, windowSize } = opts(W);
  5391. const points = [];
  5392. let p = elm;
  5393. let base = p;
  5394. for (let window = 0; window < windows; window++) {
  5395. base = p;
  5396. points.push(base);
  5397. // =1, because we skip zero
  5398. for (let i = 1; i < windowSize; i++) {
  5399. base = base.add(p);
  5400. points.push(base);
  5401. }
  5402. p = base.double();
  5403. }
  5404. return points;
  5405. },
  5406. /**
  5407. * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
  5408. * @param W window size
  5409. * @param precomputes precomputed tables
  5410. * @param n scalar (we don't check here, but should be less than curve order)
  5411. * @returns real and fake (for const-time) points
  5412. */
  5413. wNAF(W, precomputes, n) {
  5414. // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise
  5415. // But need to carefully remove other checks before wNAF. ORDER == bits here
  5416. const { windows, windowSize } = opts(W);
  5417. let p = c.ZERO;
  5418. let f = c.BASE;
  5419. const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.
  5420. const maxNumber = 2 ** W;
  5421. const shiftBy = BigInt(W);
  5422. for (let window = 0; window < windows; window++) {
  5423. const offset = window * windowSize;
  5424. // Extract W bits.
  5425. let wbits = Number(n & mask);
  5426. // Shift number by W bits.
  5427. n >>= shiftBy;
  5428. // If the bits are bigger than max size, we'll split those.
  5429. // +224 => 256 - 32
  5430. if (wbits > windowSize) {
  5431. wbits -= maxNumber;
  5432. n += _1n$2;
  5433. }
  5434. // This code was first written with assumption that 'f' and 'p' will never be infinity point:
  5435. // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,
  5436. // there is negate now: it is possible that negated element from low value
  5437. // would be the same as high element, which will create carry into next window.
  5438. // It's not obvious how this can fail, but still worth investigating later.
  5439. // Check if we're onto Zero point.
  5440. // Add random point inside current window to f.
  5441. const offset1 = offset;
  5442. const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero
  5443. const cond1 = window % 2 !== 0;
  5444. const cond2 = wbits < 0;
  5445. if (wbits === 0) {
  5446. // The most important part for const-time getPublicKey
  5447. f = f.add(constTimeNegate(cond1, precomputes[offset1]));
  5448. }
  5449. else {
  5450. p = p.add(constTimeNegate(cond2, precomputes[offset2]));
  5451. }
  5452. }
  5453. // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()
  5454. // Even if the variable is still unused, there are some checks which will
  5455. // throw an exception, so compiler needs to prove they won't happen, which is hard.
  5456. // At this point there is a way to F be infinity-point even if p is not,
  5457. // which makes it less const-time: around 1 bigint multiply.
  5458. return { p, f };
  5459. },
  5460. wNAFCached(P, precomputesMap, n, transform) {
  5461. // @ts-ignore
  5462. const W = P._WINDOW_SIZE || 1;
  5463. // Calculate precomputes on a first run, reuse them after
  5464. let comp = precomputesMap.get(P);
  5465. if (!comp) {
  5466. comp = this.precomputeWindow(P, W);
  5467. if (W !== 1) {
  5468. precomputesMap.set(P, transform(comp));
  5469. }
  5470. }
  5471. return this.wNAF(W, comp, n);
  5472. },
  5473. };
  5474. }
  5475. function validateBasic(curve) {
  5476. validateField(curve.Fp);
  5477. validateObject(curve, {
  5478. n: 'bigint',
  5479. h: 'bigint',
  5480. Gx: 'field',
  5481. Gy: 'field',
  5482. }, {
  5483. nBitLength: 'isSafeInteger',
  5484. nByteLength: 'isSafeInteger',
  5485. });
  5486. // Set defaults
  5487. return Object.freeze({
  5488. ...nLength(curve.n, curve.nBitLength),
  5489. ...curve,
  5490. ...{ p: curve.Fp.ORDER },
  5491. });
  5492. }
  5493. /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
  5494. // Short Weierstrass curve. The formula is: y² = x³ + ax + b
  5495. function validatePointOpts(curve) {
  5496. const opts = validateBasic(curve);
  5497. validateObject(opts, {
  5498. a: 'field',
  5499. b: 'field',
  5500. }, {
  5501. allowedPrivateKeyLengths: 'array',
  5502. wrapPrivateKey: 'boolean',
  5503. isTorsionFree: 'function',
  5504. clearCofactor: 'function',
  5505. allowInfinityPoint: 'boolean',
  5506. fromBytes: 'function',
  5507. toBytes: 'function',
  5508. });
  5509. const { endo, Fp, a } = opts;
  5510. if (endo) {
  5511. if (!Fp.eql(a, Fp.ZERO)) {
  5512. throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');
  5513. }
  5514. if (typeof endo !== 'object' ||
  5515. typeof endo.beta !== 'bigint' ||
  5516. typeof endo.splitScalar !== 'function') {
  5517. throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');
  5518. }
  5519. }
  5520. return Object.freeze({ ...opts });
  5521. }
  5522. // ASN.1 DER encoding utilities
  5523. const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;
  5524. const DER = {
  5525. // asn.1 DER encoding utils
  5526. Err: class DERErr extends Error {
  5527. constructor(m = '') {
  5528. super(m);
  5529. }
  5530. },
  5531. _parseInt(data) {
  5532. const { Err: E } = DER;
  5533. if (data.length < 2 || data[0] !== 0x02)
  5534. throw new E('Invalid signature integer tag');
  5535. const len = data[1];
  5536. const res = data.subarray(2, len + 2);
  5537. if (!len || res.length !== len)
  5538. throw new E('Invalid signature integer: wrong length');
  5539. // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
  5540. // since we always use positive integers here. It must always be empty:
  5541. // - add zero byte if exists
  5542. // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
  5543. if (res[0] & 0b10000000)
  5544. throw new E('Invalid signature integer: negative');
  5545. if (res[0] === 0x00 && !(res[1] & 0b10000000))
  5546. throw new E('Invalid signature integer: unnecessary leading zero');
  5547. return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left
  5548. },
  5549. toSig(hex) {
  5550. // parse DER signature
  5551. const { Err: E } = DER;
  5552. const data = typeof hex === 'string' ? h2b(hex) : hex;
  5553. if (!(data instanceof Uint8Array))
  5554. throw new Error('ui8a expected');
  5555. let l = data.length;
  5556. if (l < 2 || data[0] != 0x30)
  5557. throw new E('Invalid signature tag');
  5558. if (data[1] !== l - 2)
  5559. throw new E('Invalid signature: incorrect length');
  5560. const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));
  5561. const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);
  5562. if (rBytesLeft.length)
  5563. throw new E('Invalid signature: left bytes after parsing');
  5564. return { r, s };
  5565. },
  5566. hexFromSig(sig) {
  5567. // Add leading zero if first byte has negative bit enabled. More details in '_parseInt'
  5568. const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s);
  5569. const h = (num) => {
  5570. const hex = num.toString(16);
  5571. return hex.length & 1 ? `0${hex}` : hex;
  5572. };
  5573. const s = slice(h(sig.s));
  5574. const r = slice(h(sig.r));
  5575. const shl = s.length / 2;
  5576. const rhl = r.length / 2;
  5577. const sl = h(shl);
  5578. const rl = h(rhl);
  5579. return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;
  5580. },
  5581. };
  5582. // Be friendly to bad ECMAScript parsers by not using bigint literals
  5583. // prettier-ignore
  5584. const _0n = BigInt(0), _1n$1 = BigInt(1); BigInt(2); const _3n = BigInt(3); BigInt(4);
  5585. function weierstrassPoints(opts) {
  5586. const CURVE = validatePointOpts(opts);
  5587. const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ
  5588. const toBytes = CURVE.toBytes ||
  5589. ((_c, point, _isCompressed) => {
  5590. const a = point.toAffine();
  5591. return concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));
  5592. });
  5593. const fromBytes = CURVE.fromBytes ||
  5594. ((bytes) => {
  5595. // const head = bytes[0];
  5596. const tail = bytes.subarray(1);
  5597. // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');
  5598. const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
  5599. const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
  5600. return { x, y };
  5601. });
  5602. /**
  5603. * y² = x³ + ax + b: Short weierstrass curve formula
  5604. * @returns y²
  5605. */
  5606. function weierstrassEquation(x) {
  5607. const { a, b } = CURVE;
  5608. const x2 = Fp.sqr(x); // x * x
  5609. const x3 = Fp.mul(x2, x); // x2 * x
  5610. return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b
  5611. }
  5612. // Validate whether the passed curve params are valid.
  5613. // We check if curve equation works for generator point.
  5614. // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.
  5615. // ProjectivePoint class has not been initialized yet.
  5616. if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))
  5617. throw new Error('bad generator point: equation left != right');
  5618. // Valid group elements reside in range 1..n-1
  5619. function isWithinCurveOrder(num) {
  5620. return typeof num === 'bigint' && _0n < num && num < CURVE.n;
  5621. }
  5622. function assertGE(num) {
  5623. if (!isWithinCurveOrder(num))
  5624. throw new Error('Expected valid bigint: 0 < bigint < curve.n');
  5625. }
  5626. // Validates if priv key is valid and converts it to bigint.
  5627. // Supports options allowedPrivateKeyLengths and wrapPrivateKey.
  5628. function normPrivateKeyToScalar(key) {
  5629. const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;
  5630. if (lengths && typeof key !== 'bigint') {
  5631. if (key instanceof Uint8Array)
  5632. key = bytesToHex(key);
  5633. // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes
  5634. if (typeof key !== 'string' || !lengths.includes(key.length))
  5635. throw new Error('Invalid key');
  5636. key = key.padStart(nByteLength * 2, '0');
  5637. }
  5638. let num;
  5639. try {
  5640. num =
  5641. typeof key === 'bigint'
  5642. ? key
  5643. : bytesToNumberBE(ensureBytes('private key', key, nByteLength));
  5644. }
  5645. catch (error) {
  5646. throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);
  5647. }
  5648. if (wrapPrivateKey)
  5649. num = mod(num, n); // disabled by default, enabled for BLS
  5650. assertGE(num); // num in range [1..N-1]
  5651. return num;
  5652. }
  5653. const pointPrecomputes = new Map();
  5654. function assertPrjPoint(other) {
  5655. if (!(other instanceof Point))
  5656. throw new Error('ProjectivePoint expected');
  5657. }
  5658. /**
  5659. * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)
  5660. * Default Point works in 2d / affine coordinates: (x, y)
  5661. * We're doing calculations in projective, because its operations don't require costly inversion.
  5662. */
  5663. class Point {
  5664. constructor(px, py, pz) {
  5665. this.px = px;
  5666. this.py = py;
  5667. this.pz = pz;
  5668. if (px == null || !Fp.isValid(px))
  5669. throw new Error('x required');
  5670. if (py == null || !Fp.isValid(py))
  5671. throw new Error('y required');
  5672. if (pz == null || !Fp.isValid(pz))
  5673. throw new Error('z required');
  5674. }
  5675. // Does not validate if the point is on-curve.
  5676. // Use fromHex instead, or call assertValidity() later.
  5677. static fromAffine(p) {
  5678. const { x, y } = p || {};
  5679. if (!p || !Fp.isValid(x) || !Fp.isValid(y))
  5680. throw new Error('invalid affine point');
  5681. if (p instanceof Point)
  5682. throw new Error('projective point not allowed');
  5683. const is0 = (i) => Fp.eql(i, Fp.ZERO);
  5684. // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)
  5685. if (is0(x) && is0(y))
  5686. return Point.ZERO;
  5687. return new Point(x, y, Fp.ONE);
  5688. }
  5689. get x() {
  5690. return this.toAffine().x;
  5691. }
  5692. get y() {
  5693. return this.toAffine().y;
  5694. }
  5695. /**
  5696. * Takes a bunch of Projective Points but executes only one
  5697. * inversion on all of them. Inversion is very slow operation,
  5698. * so this improves performance massively.
  5699. * Optimization: converts a list of projective points to a list of identical points with Z=1.
  5700. */
  5701. static normalizeZ(points) {
  5702. const toInv = Fp.invertBatch(points.map((p) => p.pz));
  5703. return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
  5704. }
  5705. /**
  5706. * Converts hash string or Uint8Array to Point.
  5707. * @param hex short/long ECDSA hex
  5708. */
  5709. static fromHex(hex) {
  5710. const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));
  5711. P.assertValidity();
  5712. return P;
  5713. }
  5714. // Multiplies generator point by privateKey.
  5715. static fromPrivateKey(privateKey) {
  5716. return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
  5717. }
  5718. // "Private method", don't use it directly
  5719. _setWindowSize(windowSize) {
  5720. this._WINDOW_SIZE = windowSize;
  5721. pointPrecomputes.delete(this);
  5722. }
  5723. // A point on curve is valid if it conforms to equation.
  5724. assertValidity() {
  5725. if (this.is0()) {
  5726. // (0, 1, 0) aka ZERO is invalid in most contexts.
  5727. // In BLS, ZERO can be serialized, so we allow it.
  5728. // (0, 0, 0) is wrong representation of ZERO and is always invalid.
  5729. if (CURVE.allowInfinityPoint && !Fp.is0(this.py))
  5730. return;
  5731. throw new Error('bad point: ZERO');
  5732. }
  5733. // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`
  5734. const { x, y } = this.toAffine();
  5735. // Check if x, y are valid field elements
  5736. if (!Fp.isValid(x) || !Fp.isValid(y))
  5737. throw new Error('bad point: x or y not FE');
  5738. const left = Fp.sqr(y); // y²
  5739. const right = weierstrassEquation(x); // x³ + ax + b
  5740. if (!Fp.eql(left, right))
  5741. throw new Error('bad point: equation left != right');
  5742. if (!this.isTorsionFree())
  5743. throw new Error('bad point: not in prime-order subgroup');
  5744. }
  5745. hasEvenY() {
  5746. const { y } = this.toAffine();
  5747. if (Fp.isOdd)
  5748. return !Fp.isOdd(y);
  5749. throw new Error("Field doesn't support isOdd");
  5750. }
  5751. /**
  5752. * Compare one point to another.
  5753. */
  5754. equals(other) {
  5755. assertPrjPoint(other);
  5756. const { px: X1, py: Y1, pz: Z1 } = this;
  5757. const { px: X2, py: Y2, pz: Z2 } = other;
  5758. const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
  5759. const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
  5760. return U1 && U2;
  5761. }
  5762. /**
  5763. * Flips point to one corresponding to (x, -y) in Affine coordinates.
  5764. */
  5765. negate() {
  5766. return new Point(this.px, Fp.neg(this.py), this.pz);
  5767. }
  5768. // Renes-Costello-Batina exception-free doubling formula.
  5769. // There is 30% faster Jacobian formula, but it is not complete.
  5770. // https://eprint.iacr.org/2015/1060, algorithm 3
  5771. // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
  5772. double() {
  5773. const { a, b } = CURVE;
  5774. const b3 = Fp.mul(b, _3n);
  5775. const { px: X1, py: Y1, pz: Z1 } = this;
  5776. let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
  5777. let t0 = Fp.mul(X1, X1); // step 1
  5778. let t1 = Fp.mul(Y1, Y1);
  5779. let t2 = Fp.mul(Z1, Z1);
  5780. let t3 = Fp.mul(X1, Y1);
  5781. t3 = Fp.add(t3, t3); // step 5
  5782. Z3 = Fp.mul(X1, Z1);
  5783. Z3 = Fp.add(Z3, Z3);
  5784. X3 = Fp.mul(a, Z3);
  5785. Y3 = Fp.mul(b3, t2);
  5786. Y3 = Fp.add(X3, Y3); // step 10
  5787. X3 = Fp.sub(t1, Y3);
  5788. Y3 = Fp.add(t1, Y3);
  5789. Y3 = Fp.mul(X3, Y3);
  5790. X3 = Fp.mul(t3, X3);
  5791. Z3 = Fp.mul(b3, Z3); // step 15
  5792. t2 = Fp.mul(a, t2);
  5793. t3 = Fp.sub(t0, t2);
  5794. t3 = Fp.mul(a, t3);
  5795. t3 = Fp.add(t3, Z3);
  5796. Z3 = Fp.add(t0, t0); // step 20
  5797. t0 = Fp.add(Z3, t0);
  5798. t0 = Fp.add(t0, t2);
  5799. t0 = Fp.mul(t0, t3);
  5800. Y3 = Fp.add(Y3, t0);
  5801. t2 = Fp.mul(Y1, Z1); // step 25
  5802. t2 = Fp.add(t2, t2);
  5803. t0 = Fp.mul(t2, t3);
  5804. X3 = Fp.sub(X3, t0);
  5805. Z3 = Fp.mul(t2, t1);
  5806. Z3 = Fp.add(Z3, Z3); // step 30
  5807. Z3 = Fp.add(Z3, Z3);
  5808. return new Point(X3, Y3, Z3);
  5809. }
  5810. // Renes-Costello-Batina exception-free addition formula.
  5811. // There is 30% faster Jacobian formula, but it is not complete.
  5812. // https://eprint.iacr.org/2015/1060, algorithm 1
  5813. // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
  5814. add(other) {
  5815. assertPrjPoint(other);
  5816. const { px: X1, py: Y1, pz: Z1 } = this;
  5817. const { px: X2, py: Y2, pz: Z2 } = other;
  5818. let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore
  5819. const a = CURVE.a;
  5820. const b3 = Fp.mul(CURVE.b, _3n);
  5821. let t0 = Fp.mul(X1, X2); // step 1
  5822. let t1 = Fp.mul(Y1, Y2);
  5823. let t2 = Fp.mul(Z1, Z2);
  5824. let t3 = Fp.add(X1, Y1);
  5825. let t4 = Fp.add(X2, Y2); // step 5
  5826. t3 = Fp.mul(t3, t4);
  5827. t4 = Fp.add(t0, t1);
  5828. t3 = Fp.sub(t3, t4);
  5829. t4 = Fp.add(X1, Z1);
  5830. let t5 = Fp.add(X2, Z2); // step 10
  5831. t4 = Fp.mul(t4, t5);
  5832. t5 = Fp.add(t0, t2);
  5833. t4 = Fp.sub(t4, t5);
  5834. t5 = Fp.add(Y1, Z1);
  5835. X3 = Fp.add(Y2, Z2); // step 15
  5836. t5 = Fp.mul(t5, X3);
  5837. X3 = Fp.add(t1, t2);
  5838. t5 = Fp.sub(t5, X3);
  5839. Z3 = Fp.mul(a, t4);
  5840. X3 = Fp.mul(b3, t2); // step 20
  5841. Z3 = Fp.add(X3, Z3);
  5842. X3 = Fp.sub(t1, Z3);
  5843. Z3 = Fp.add(t1, Z3);
  5844. Y3 = Fp.mul(X3, Z3);
  5845. t1 = Fp.add(t0, t0); // step 25
  5846. t1 = Fp.add(t1, t0);
  5847. t2 = Fp.mul(a, t2);
  5848. t4 = Fp.mul(b3, t4);
  5849. t1 = Fp.add(t1, t2);
  5850. t2 = Fp.sub(t0, t2); // step 30
  5851. t2 = Fp.mul(a, t2);
  5852. t4 = Fp.add(t4, t2);
  5853. t0 = Fp.mul(t1, t4);
  5854. Y3 = Fp.add(Y3, t0);
  5855. t0 = Fp.mul(t5, t4); // step 35
  5856. X3 = Fp.mul(t3, X3);
  5857. X3 = Fp.sub(X3, t0);
  5858. t0 = Fp.mul(t3, t1);
  5859. Z3 = Fp.mul(t5, Z3);
  5860. Z3 = Fp.add(Z3, t0); // step 40
  5861. return new Point(X3, Y3, Z3);
  5862. }
  5863. subtract(other) {
  5864. return this.add(other.negate());
  5865. }
  5866. is0() {
  5867. return this.equals(Point.ZERO);
  5868. }
  5869. wNAF(n) {
  5870. return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => {
  5871. const toInv = Fp.invertBatch(comp.map((p) => p.pz));
  5872. return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
  5873. });
  5874. }
  5875. /**
  5876. * Non-constant-time multiplication. Uses double-and-add algorithm.
  5877. * It's faster, but should only be used when you don't care about
  5878. * an exposed private key e.g. sig verification, which works over *public* keys.
  5879. */
  5880. multiplyUnsafe(n) {
  5881. const I = Point.ZERO;
  5882. if (n === _0n)
  5883. return I;
  5884. assertGE(n); // Will throw on 0
  5885. if (n === _1n$1)
  5886. return this;
  5887. const { endo } = CURVE;
  5888. if (!endo)
  5889. return wnaf.unsafeLadder(this, n);
  5890. // Apply endomorphism
  5891. let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
  5892. let k1p = I;
  5893. let k2p = I;
  5894. let d = this;
  5895. while (k1 > _0n || k2 > _0n) {
  5896. if (k1 & _1n$1)
  5897. k1p = k1p.add(d);
  5898. if (k2 & _1n$1)
  5899. k2p = k2p.add(d);
  5900. d = d.double();
  5901. k1 >>= _1n$1;
  5902. k2 >>= _1n$1;
  5903. }
  5904. if (k1neg)
  5905. k1p = k1p.negate();
  5906. if (k2neg)
  5907. k2p = k2p.negate();
  5908. k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
  5909. return k1p.add(k2p);
  5910. }
  5911. /**
  5912. * Constant time multiplication.
  5913. * Uses wNAF method. Windowed method may be 10% faster,
  5914. * but takes 2x longer to generate and consumes 2x memory.
  5915. * Uses precomputes when available.
  5916. * Uses endomorphism for Koblitz curves.
  5917. * @param scalar by which the point would be multiplied
  5918. * @returns New point
  5919. */
  5920. multiply(scalar) {
  5921. assertGE(scalar);
  5922. let n = scalar;
  5923. let point, fake; // Fake point is used to const-time mult
  5924. const { endo } = CURVE;
  5925. if (endo) {
  5926. const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);
  5927. let { p: k1p, f: f1p } = this.wNAF(k1);
  5928. let { p: k2p, f: f2p } = this.wNAF(k2);
  5929. k1p = wnaf.constTimeNegate(k1neg, k1p);
  5930. k2p = wnaf.constTimeNegate(k2neg, k2p);
  5931. k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
  5932. point = k1p.add(k2p);
  5933. fake = f1p.add(f2p);
  5934. }
  5935. else {
  5936. const { p, f } = this.wNAF(n);
  5937. point = p;
  5938. fake = f;
  5939. }
  5940. // Normalize `z` for both points, but return only real one
  5941. return Point.normalizeZ([point, fake])[0];
  5942. }
  5943. /**
  5944. * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
  5945. * Not using Strauss-Shamir trick: precomputation tables are faster.
  5946. * The trick could be useful if both P and Q are not G (not in our case).
  5947. * @returns non-zero affine point
  5948. */
  5949. multiplyAndAddUnsafe(Q, a, b) {
  5950. const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes
  5951. const mul = (P, a // Select faster multiply() method
  5952. ) => (a === _0n || a === _1n$1 || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));
  5953. const sum = mul(this, a).add(mul(Q, b));
  5954. return sum.is0() ? undefined : sum;
  5955. }
  5956. // Converts Projective point to affine (x, y) coordinates.
  5957. // Can accept precomputed Z^-1 - for example, from invertBatch.
  5958. // (x, y, z) ∋ (x=x/z, y=y/z)
  5959. toAffine(iz) {
  5960. const { px: x, py: y, pz: z } = this;
  5961. const is0 = this.is0();
  5962. // If invZ was 0, we return zero point. However we still want to execute
  5963. // all operations, so we replace invZ with a random number, 1.
  5964. if (iz == null)
  5965. iz = is0 ? Fp.ONE : Fp.inv(z);
  5966. const ax = Fp.mul(x, iz);
  5967. const ay = Fp.mul(y, iz);
  5968. const zz = Fp.mul(z, iz);
  5969. if (is0)
  5970. return { x: Fp.ZERO, y: Fp.ZERO };
  5971. if (!Fp.eql(zz, Fp.ONE))
  5972. throw new Error('invZ was invalid');
  5973. return { x: ax, y: ay };
  5974. }
  5975. isTorsionFree() {
  5976. const { h: cofactor, isTorsionFree } = CURVE;
  5977. if (cofactor === _1n$1)
  5978. return true; // No subgroups, always torsion-free
  5979. if (isTorsionFree)
  5980. return isTorsionFree(Point, this);
  5981. throw new Error('isTorsionFree() has not been declared for the elliptic curve');
  5982. }
  5983. clearCofactor() {
  5984. const { h: cofactor, clearCofactor } = CURVE;
  5985. if (cofactor === _1n$1)
  5986. return this; // Fast-path
  5987. if (clearCofactor)
  5988. return clearCofactor(Point, this);
  5989. return this.multiplyUnsafe(CURVE.h);
  5990. }
  5991. toRawBytes(isCompressed = true) {
  5992. this.assertValidity();
  5993. return toBytes(Point, this, isCompressed);
  5994. }
  5995. toHex(isCompressed = true) {
  5996. return bytesToHex(this.toRawBytes(isCompressed));
  5997. }
  5998. }
  5999. Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
  6000. Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
  6001. const _bits = CURVE.nBitLength;
  6002. const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
  6003. // Validate if generator point is on curve
  6004. return {
  6005. CURVE,
  6006. ProjectivePoint: Point,
  6007. normPrivateKeyToScalar,
  6008. weierstrassEquation,
  6009. isWithinCurveOrder,
  6010. };
  6011. }
  6012. function validateOpts(curve) {
  6013. const opts = validateBasic(curve);
  6014. validateObject(opts, {
  6015. hash: 'hash',
  6016. hmac: 'function',
  6017. randomBytes: 'function',
  6018. }, {
  6019. bits2int: 'function',
  6020. bits2int_modN: 'function',
  6021. lowS: 'boolean',
  6022. });
  6023. return Object.freeze({ lowS: true, ...opts });
  6024. }
  6025. function weierstrass(curveDef) {
  6026. const CURVE = validateOpts(curveDef);
  6027. const { Fp, n: CURVE_ORDER } = CURVE;
  6028. const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32
  6029. const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32
  6030. function isValidFieldElement(num) {
  6031. return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE
  6032. }
  6033. function modN(a) {
  6034. return mod(a, CURVE_ORDER);
  6035. }
  6036. function invN(a) {
  6037. return invert(a, CURVE_ORDER);
  6038. }
  6039. const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({
  6040. ...CURVE,
  6041. toBytes(_c, point, isCompressed) {
  6042. const a = point.toAffine();
  6043. const x = Fp.toBytes(a.x);
  6044. const cat = concatBytes;
  6045. if (isCompressed) {
  6046. return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);
  6047. }
  6048. else {
  6049. return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));
  6050. }
  6051. },
  6052. fromBytes(bytes) {
  6053. const len = bytes.length;
  6054. const head = bytes[0];
  6055. const tail = bytes.subarray(1);
  6056. // this.assertValidity() is done inside of fromHex
  6057. if (len === compressedLen && (head === 0x02 || head === 0x03)) {
  6058. const x = bytesToNumberBE(tail);
  6059. if (!isValidFieldElement(x))
  6060. throw new Error('Point is not on curve');
  6061. const y2 = weierstrassEquation(x); // y² = x³ + ax + b
  6062. let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4
  6063. const isYOdd = (y & _1n$1) === _1n$1;
  6064. // ECDSA
  6065. const isHeadOdd = (head & 1) === 1;
  6066. if (isHeadOdd !== isYOdd)
  6067. y = Fp.neg(y);
  6068. return { x, y };
  6069. }
  6070. else if (len === uncompressedLen && head === 0x04) {
  6071. const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
  6072. const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
  6073. return { x, y };
  6074. }
  6075. else {
  6076. throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);
  6077. }
  6078. },
  6079. });
  6080. const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength));
  6081. function isBiggerThanHalfOrder(number) {
  6082. const HALF = CURVE_ORDER >> _1n$1;
  6083. return number > HALF;
  6084. }
  6085. function normalizeS(s) {
  6086. return isBiggerThanHalfOrder(s) ? modN(-s) : s;
  6087. }
  6088. // slice bytes num
  6089. const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to));
  6090. /**
  6091. * ECDSA signature with its (r, s) properties. Supports DER & compact representations.
  6092. */
  6093. class Signature {
  6094. constructor(r, s, recovery) {
  6095. this.r = r;
  6096. this.s = s;
  6097. this.recovery = recovery;
  6098. this.assertValidity();
  6099. }
  6100. // pair (bytes of r, bytes of s)
  6101. static fromCompact(hex) {
  6102. const l = CURVE.nByteLength;
  6103. hex = ensureBytes('compactSignature', hex, l * 2);
  6104. return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));
  6105. }
  6106. // DER encoded ECDSA signature
  6107. // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
  6108. static fromDER(hex) {
  6109. const { r, s } = DER.toSig(ensureBytes('DER', hex));
  6110. return new Signature(r, s);
  6111. }
  6112. assertValidity() {
  6113. // can use assertGE here
  6114. if (!isWithinCurveOrder(this.r))
  6115. throw new Error('r must be 0 < r < CURVE.n');
  6116. if (!isWithinCurveOrder(this.s))
  6117. throw new Error('s must be 0 < s < CURVE.n');
  6118. }
  6119. addRecoveryBit(recovery) {
  6120. return new Signature(this.r, this.s, recovery);
  6121. }
  6122. recoverPublicKey(msgHash) {
  6123. const { r, s, recovery: rec } = this;
  6124. const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash
  6125. if (rec == null || ![0, 1, 2, 3].includes(rec))
  6126. throw new Error('recovery id invalid');
  6127. const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
  6128. if (radj >= Fp.ORDER)
  6129. throw new Error('recovery id 2 or 3 invalid');
  6130. const prefix = (rec & 1) === 0 ? '02' : '03';
  6131. const R = Point.fromHex(prefix + numToNByteStr(radj));
  6132. const ir = invN(radj); // r^-1
  6133. const u1 = modN(-h * ir); // -hr^-1
  6134. const u2 = modN(s * ir); // sr^-1
  6135. const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)
  6136. if (!Q)
  6137. throw new Error('point at infinify'); // unsafe is fine: no priv data leaked
  6138. Q.assertValidity();
  6139. return Q;
  6140. }
  6141. // Signatures should be low-s, to prevent malleability.
  6142. hasHighS() {
  6143. return isBiggerThanHalfOrder(this.s);
  6144. }
  6145. normalizeS() {
  6146. return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;
  6147. }
  6148. // DER-encoded
  6149. toDERRawBytes() {
  6150. return hexToBytes(this.toDERHex());
  6151. }
  6152. toDERHex() {
  6153. return DER.hexFromSig({ r: this.r, s: this.s });
  6154. }
  6155. // padded bytes of r, then padded bytes of s
  6156. toCompactRawBytes() {
  6157. return hexToBytes(this.toCompactHex());
  6158. }
  6159. toCompactHex() {
  6160. return numToNByteStr(this.r) + numToNByteStr(this.s);
  6161. }
  6162. }
  6163. const utils = {
  6164. isValidPrivateKey(privateKey) {
  6165. try {
  6166. normPrivateKeyToScalar(privateKey);
  6167. return true;
  6168. }
  6169. catch (error) {
  6170. return false;
  6171. }
  6172. },
  6173. normPrivateKeyToScalar: normPrivateKeyToScalar,
  6174. /**
  6175. * Produces cryptographically secure private key from random of size
  6176. * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
  6177. */
  6178. randomPrivateKey: () => {
  6179. const length = getMinHashLength(CURVE.n);
  6180. return mapHashToField(CURVE.randomBytes(length), CURVE.n);
  6181. },
  6182. /**
  6183. * Creates precompute table for an arbitrary EC point. Makes point "cached".
  6184. * Allows to massively speed-up `point.multiply(scalar)`.
  6185. * @returns cached point
  6186. * @example
  6187. * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
  6188. * fast.multiply(privKey); // much faster ECDH now
  6189. */
  6190. precompute(windowSize = 8, point = Point.BASE) {
  6191. point._setWindowSize(windowSize);
  6192. point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here
  6193. return point;
  6194. },
  6195. };
  6196. /**
  6197. * Computes public key for a private key. Checks for validity of the private key.
  6198. * @param privateKey private key
  6199. * @param isCompressed whether to return compact (default), or full key
  6200. * @returns Public key, full when isCompressed=false; short when isCompressed=true
  6201. */
  6202. function getPublicKey(privateKey, isCompressed = true) {
  6203. return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);
  6204. }
  6205. /**
  6206. * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
  6207. */
  6208. function isProbPub(item) {
  6209. const arr = item instanceof Uint8Array;
  6210. const str = typeof item === 'string';
  6211. const len = (arr || str) && item.length;
  6212. if (arr)
  6213. return len === compressedLen || len === uncompressedLen;
  6214. if (str)
  6215. return len === 2 * compressedLen || len === 2 * uncompressedLen;
  6216. if (item instanceof Point)
  6217. return true;
  6218. return false;
  6219. }
  6220. /**
  6221. * ECDH (Elliptic Curve Diffie Hellman).
  6222. * Computes shared public key from private key and public key.
  6223. * Checks: 1) private key validity 2) shared key is on-curve.
  6224. * Does NOT hash the result.
  6225. * @param privateA private key
  6226. * @param publicB different public key
  6227. * @param isCompressed whether to return compact (default), or full key
  6228. * @returns shared public key
  6229. */
  6230. function getSharedSecret(privateA, publicB, isCompressed = true) {
  6231. if (isProbPub(privateA))
  6232. throw new Error('first arg must be private key');
  6233. if (!isProbPub(publicB))
  6234. throw new Error('second arg must be public key');
  6235. const b = Point.fromHex(publicB); // check for being on-curve
  6236. return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
  6237. }
  6238. // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.
  6239. // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.
  6240. // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.
  6241. // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors
  6242. const bits2int = CURVE.bits2int ||
  6243. function (bytes) {
  6244. // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)
  6245. // for some cases, since bytes.length * 8 is not actual bitLength.
  6246. const num = bytesToNumberBE(bytes); // check for == u8 done here
  6247. const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits
  6248. return delta > 0 ? num >> BigInt(delta) : num;
  6249. };
  6250. const bits2int_modN = CURVE.bits2int_modN ||
  6251. function (bytes) {
  6252. return modN(bits2int(bytes)); // can't use bytesToNumberBE here
  6253. };
  6254. // NOTE: pads output with zero as per spec
  6255. const ORDER_MASK = bitMask(CURVE.nBitLength);
  6256. /**
  6257. * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.
  6258. */
  6259. function int2octets(num) {
  6260. if (typeof num !== 'bigint')
  6261. throw new Error('bigint expected');
  6262. if (!(_0n <= num && num < ORDER_MASK))
  6263. throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);
  6264. // works with order, can have different size than numToField!
  6265. return numberToBytesBE(num, CURVE.nByteLength);
  6266. }
  6267. // Steps A, D of RFC6979 3.2
  6268. // Creates RFC6979 seed; converts msg/privKey to numbers.
  6269. // Used only in sign, not in verify.
  6270. // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.
  6271. // Also it can be bigger for P224 + SHA256
  6272. function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
  6273. if (['recovered', 'canonical'].some((k) => k in opts))
  6274. throw new Error('sign() legacy options not supported');
  6275. const { hash, randomBytes } = CURVE;
  6276. let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default
  6277. if (lowS == null)
  6278. lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash
  6279. msgHash = ensureBytes('msgHash', msgHash);
  6280. if (prehash)
  6281. msgHash = ensureBytes('prehashed msgHash', hash(msgHash));
  6282. // We can't later call bits2octets, since nested bits2int is broken for curves
  6283. // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.
  6284. // const bits2octets = (bits) => int2octets(bits2int_modN(bits))
  6285. const h1int = bits2int_modN(msgHash);
  6286. const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint
  6287. const seedArgs = [int2octets(d), int2octets(h1int)];
  6288. // extraEntropy. RFC6979 3.6: additional k' (optional).
  6289. if (ent != null) {
  6290. // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')
  6291. const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is
  6292. seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes
  6293. }
  6294. const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2
  6295. const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!
  6296. // Converts signature params into point w r/s, checks result for validity.
  6297. function k2sig(kBytes) {
  6298. // RFC 6979 Section 3.2, step 3: k = bits2int(T)
  6299. const k = bits2int(kBytes); // Cannot use fields methods, since it is group element
  6300. if (!isWithinCurveOrder(k))
  6301. return; // Important: all mod() calls here must be done over N
  6302. const ik = invN(k); // k^-1 mod n
  6303. const q = Point.BASE.multiply(k).toAffine(); // q = Gk
  6304. const r = modN(q.x); // r = q.x mod n
  6305. if (r === _0n)
  6306. return;
  6307. // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to
  6308. // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:
  6309. // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT
  6310. const s = modN(ik * modN(m + r * d)); // Not using blinding here
  6311. if (s === _0n)
  6312. return;
  6313. let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n$1); // recovery bit (2 or 3, when q.x > n)
  6314. let normS = s;
  6315. if (lowS && isBiggerThanHalfOrder(s)) {
  6316. normS = normalizeS(s); // if lowS was passed, ensure s is always
  6317. recovery ^= 1; // // in the bottom half of N
  6318. }
  6319. return new Signature(r, normS, recovery); // use normS, not s
  6320. }
  6321. return { seed, k2sig };
  6322. }
  6323. const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };
  6324. const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };
  6325. /**
  6326. * Signs message hash with a private key.
  6327. * ```
  6328. * sign(m, d, k) where
  6329. * (x, y) = G × k
  6330. * r = x mod n
  6331. * s = (m + dr)/k mod n
  6332. * ```
  6333. * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.
  6334. * @param privKey private key
  6335. * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.
  6336. * @returns signature with recovery param
  6337. */
  6338. function sign(msgHash, privKey, opts = defaultSigOpts) {
  6339. const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.
  6340. const C = CURVE;
  6341. const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);
  6342. return drbg(seed, k2sig); // Steps B, C, D, E, F, G
  6343. }
  6344. // Enable precomputes. Slows down first publicKey computation by 20ms.
  6345. Point.BASE._setWindowSize(8);
  6346. // utils.precompute(8, ProjectivePoint.BASE)
  6347. /**
  6348. * Verifies a signature against message hash and public key.
  6349. * Rejects lowS signatures by default: to override,
  6350. * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
  6351. *
  6352. * ```
  6353. * verify(r, s, h, P) where
  6354. * U1 = hs^-1 mod n
  6355. * U2 = rs^-1 mod n
  6356. * R = U1⋅G - U2⋅P
  6357. * mod(R.x, n) == r
  6358. * ```
  6359. */
  6360. function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {
  6361. const sg = signature;
  6362. msgHash = ensureBytes('msgHash', msgHash);
  6363. publicKey = ensureBytes('publicKey', publicKey);
  6364. if ('strict' in opts)
  6365. throw new Error('options.strict was renamed to lowS');
  6366. const { lowS, prehash } = opts;
  6367. let _sig = undefined;
  6368. let P;
  6369. try {
  6370. if (typeof sg === 'string' || sg instanceof Uint8Array) {
  6371. // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).
  6372. // Since DER can also be 2*nByteLength bytes, we check for it first.
  6373. try {
  6374. _sig = Signature.fromDER(sg);
  6375. }
  6376. catch (derError) {
  6377. if (!(derError instanceof DER.Err))
  6378. throw derError;
  6379. _sig = Signature.fromCompact(sg);
  6380. }
  6381. }
  6382. else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {
  6383. const { r, s } = sg;
  6384. _sig = new Signature(r, s);
  6385. }
  6386. else {
  6387. throw new Error('PARSE');
  6388. }
  6389. P = Point.fromHex(publicKey);
  6390. }
  6391. catch (error) {
  6392. if (error.message === 'PARSE')
  6393. throw new Error(`signature must be Signature instance, Uint8Array or hex string`);
  6394. return false;
  6395. }
  6396. if (lowS && _sig.hasHighS())
  6397. return false;
  6398. if (prehash)
  6399. msgHash = CURVE.hash(msgHash);
  6400. const { r, s } = _sig;
  6401. const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element
  6402. const is = invN(s); // s^-1
  6403. const u1 = modN(h * is); // u1 = hs^-1 mod n
  6404. const u2 = modN(r * is); // u2 = rs^-1 mod n
  6405. const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P
  6406. if (!R)
  6407. return false;
  6408. const v = modN(R.x);
  6409. return v === r;
  6410. }
  6411. return {
  6412. CURVE,
  6413. getPublicKey,
  6414. getSharedSecret,
  6415. sign,
  6416. verify,
  6417. ProjectivePoint: Point,
  6418. Signature,
  6419. utils,
  6420. };
  6421. }
  6422. /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
  6423. // connects noble-curves to noble-hashes
  6424. function getHash(hash) {
  6425. return {
  6426. hash,
  6427. hmac: (key, ...msgs) => hmac(hash, key, concatBytes$1(...msgs)),
  6428. randomBytes: randomBytes$2,
  6429. };
  6430. }
  6431. function createCurve(curveDef, defHash) {
  6432. const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });
  6433. return Object.freeze({ ...create(defHash), create });
  6434. }
  6435. /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
  6436. const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');
  6437. const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');
  6438. const _1n = BigInt(1);
  6439. const _2n = BigInt(2);
  6440. const divNearest = (a, b) => (a + b / _2n) / b;
  6441. /**
  6442. * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.
  6443. * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]
  6444. */
  6445. function sqrtMod(y) {
  6446. const P = secp256k1P;
  6447. // prettier-ignore
  6448. const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
  6449. // prettier-ignore
  6450. const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
  6451. const b2 = (y * y * y) % P; // x^3, 11
  6452. const b3 = (b2 * b2 * y) % P; // x^7
  6453. const b6 = (pow2(b3, _3n, P) * b3) % P;
  6454. const b9 = (pow2(b6, _3n, P) * b3) % P;
  6455. const b11 = (pow2(b9, _2n, P) * b2) % P;
  6456. const b22 = (pow2(b11, _11n, P) * b11) % P;
  6457. const b44 = (pow2(b22, _22n, P) * b22) % P;
  6458. const b88 = (pow2(b44, _44n, P) * b44) % P;
  6459. const b176 = (pow2(b88, _88n, P) * b88) % P;
  6460. const b220 = (pow2(b176, _44n, P) * b44) % P;
  6461. const b223 = (pow2(b220, _3n, P) * b3) % P;
  6462. const t1 = (pow2(b223, _23n, P) * b22) % P;
  6463. const t2 = (pow2(t1, _6n, P) * b2) % P;
  6464. const root = pow2(t2, _2n, P);
  6465. if (!Fp.eql(Fp.sqr(root), y))
  6466. throw new Error('Cannot find square root');
  6467. return root;
  6468. }
  6469. const Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });
  6470. const secp256k1 = createCurve({
  6471. a: BigInt(0),
  6472. b: BigInt(7),
  6473. Fp,
  6474. n: secp256k1N,
  6475. // Base point (x, y) aka generator point
  6476. Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),
  6477. Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),
  6478. h: BigInt(1),
  6479. lowS: true,
  6480. /**
  6481. * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
  6482. * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
  6483. * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
  6484. * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066
  6485. */
  6486. endo: {
  6487. beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),
  6488. splitScalar: (k) => {
  6489. const n = secp256k1N;
  6490. const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');
  6491. const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');
  6492. const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');
  6493. const b2 = a1;
  6494. const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)
  6495. const c1 = divNearest(b2 * k, n);
  6496. const c2 = divNearest(-b1 * k, n);
  6497. let k1 = mod(k - c1 * a1 - c2 * a2, n);
  6498. let k2 = mod(-c1 * b1 - c2 * b2, n);
  6499. const k1neg = k1 > POW_2_128;
  6500. const k2neg = k2 > POW_2_128;
  6501. if (k1neg)
  6502. k1 = n - k1;
  6503. if (k2neg)
  6504. k2 = n - k2;
  6505. if (k1 > POW_2_128 || k2 > POW_2_128) {
  6506. throw new Error('splitScalar: Endomorphism failed, k=' + k);
  6507. }
  6508. return { k1neg, k1, k2neg, k2 };
  6509. },
  6510. },
  6511. }, sha256$1);
  6512. // Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.
  6513. // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki
  6514. BigInt(0);
  6515. secp256k1.ProjectivePoint;
  6516. /**
  6517. * A constant for the zero address.
  6518. *
  6519. * (**i.e.** ``"0x0000000000000000000000000000000000000000"``)
  6520. */
  6521. const ZeroAddress = "0x0000000000000000000000000000000000000000";
  6522. /**
  6523. * A constant for the zero hash.
  6524. *
  6525. * (**i.e.** ``"0x0000000000000000000000000000000000000000000000000000000000000000"``)
  6526. */
  6527. const ZeroHash = "0x0000000000000000000000000000000000000000000000000000000000000000";
  6528. /**
  6529. * A constant for the order N for the secp256k1 curve.
  6530. *
  6531. * (**i.e.** ``0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n``)
  6532. */
  6533. const N$1 = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");
  6534. /**
  6535. * A constant for the number of wei in a single ether.
  6536. *
  6537. * (**i.e.** ``1000000000000000000n``)
  6538. */
  6539. const WeiPerEther = BigInt("1000000000000000000");
  6540. /**
  6541. * A constant for the maximum value for a ``uint256``.
  6542. *
  6543. * (**i.e.** ``0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn``)
  6544. */
  6545. const MaxUint256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
  6546. /**
  6547. * A constant for the minimum value for an ``int256``.
  6548. *
  6549. * (**i.e.** ``-8000000000000000000000000000000000000000000000000000000000000000n``)
  6550. */
  6551. const MinInt256 = BigInt("0x8000000000000000000000000000000000000000000000000000000000000000") * BigInt(-1);
  6552. /**
  6553. * A constant for the maximum value for an ``int256``.
  6554. *
  6555. * (**i.e.** ``0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn``)
  6556. */
  6557. const MaxInt256 = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
  6558. // NFKC (composed) // (decomposed)
  6559. /**
  6560. * A constant for the ether symbol (normalized using NFKC).
  6561. *
  6562. * (**i.e.** ``"\\u039e"``)
  6563. */
  6564. const EtherSymbol = "\u039e"; // "\uD835\uDF63";
  6565. /**
  6566. * A constant for the [[link-eip-191]] personal message prefix.
  6567. *
  6568. * (**i.e.** ``"\\x19Ethereum Signed Message:\\n"``)
  6569. */
  6570. const MessagePrefix = "\x19Ethereum Signed Message:\n";
  6571. // Constants
  6572. const BN_0$7 = BigInt(0);
  6573. const BN_1$3 = BigInt(1);
  6574. const BN_2$3 = BigInt(2);
  6575. const BN_27$1 = BigInt(27);
  6576. const BN_28$1 = BigInt(28);
  6577. const BN_35$1 = BigInt(35);
  6578. const _guard$3 = {};
  6579. function toUint256(value) {
  6580. return zeroPadValue(toBeArray(value), 32);
  6581. }
  6582. /**
  6583. * A Signature @TODO
  6584. *
  6585. *
  6586. * @_docloc: api/crypto:Signing
  6587. */
  6588. class Signature {
  6589. #r;
  6590. #s;
  6591. #v;
  6592. #networkV;
  6593. /**
  6594. * The ``r`` value for a signautre.
  6595. *
  6596. * This represents the ``x`` coordinate of a "reference" or
  6597. * challenge point, from which the ``y`` can be computed.
  6598. */
  6599. get r() { return this.#r; }
  6600. set r(value) {
  6601. assertArgument(dataLength(value) === 32, "invalid r", "value", value);
  6602. this.#r = hexlify(value);
  6603. }
  6604. /**
  6605. * The ``s`` value for a signature.
  6606. */
  6607. get s() { return this.#s; }
  6608. set s(_value) {
  6609. assertArgument(dataLength(_value) === 32, "invalid s", "value", _value);
  6610. const value = hexlify(_value);
  6611. assertArgument(parseInt(value.substring(0, 3)) < 8, "non-canonical s", "value", value);
  6612. this.#s = value;
  6613. }
  6614. /**
  6615. * The ``v`` value for a signature.
  6616. *
  6617. * Since a given ``x`` value for ``r`` has two possible values for
  6618. * its correspondin ``y``, the ``v`` indicates which of the two ``y``
  6619. * values to use.
  6620. *
  6621. * It is normalized to the values ``27`` or ``28`` for legacy
  6622. * purposes.
  6623. */
  6624. get v() { return this.#v; }
  6625. set v(value) {
  6626. const v = getNumber(value, "value");
  6627. assertArgument(v === 27 || v === 28, "invalid v", "v", value);
  6628. this.#v = v;
  6629. }
  6630. /**
  6631. * The EIP-155 ``v`` for legacy transactions. For non-legacy
  6632. * transactions, this value is ``null``.
  6633. */
  6634. get networkV() { return this.#networkV; }
  6635. /**
  6636. * The chain ID for EIP-155 legacy transactions. For non-legacy
  6637. * transactions, this value is ``null``.
  6638. */
  6639. get legacyChainId() {
  6640. const v = this.networkV;
  6641. if (v == null) {
  6642. return null;
  6643. }
  6644. return Signature.getChainId(v);
  6645. }
  6646. /**
  6647. * The ``yParity`` for the signature.
  6648. *
  6649. * See ``v`` for more details on how this value is used.
  6650. */
  6651. get yParity() {
  6652. return (this.v === 27) ? 0 : 1;
  6653. }
  6654. /**
  6655. * The [[link-eip-2098]] compact representation of the ``yParity``
  6656. * and ``s`` compacted into a single ``bytes32``.
  6657. */
  6658. get yParityAndS() {
  6659. // The EIP-2098 compact representation
  6660. const yParityAndS = getBytes(this.s);
  6661. if (this.yParity) {
  6662. yParityAndS[0] |= 0x80;
  6663. }
  6664. return hexlify(yParityAndS);
  6665. }
  6666. /**
  6667. * The [[link-eip-2098]] compact representation.
  6668. */
  6669. get compactSerialized() {
  6670. return concat([this.r, this.yParityAndS]);
  6671. }
  6672. /**
  6673. * The serialized representation.
  6674. */
  6675. get serialized() {
  6676. return concat([this.r, this.s, (this.yParity ? "0x1c" : "0x1b")]);
  6677. }
  6678. /**
  6679. * @private
  6680. */
  6681. constructor(guard, r, s, v) {
  6682. assertPrivate(guard, _guard$3, "Signature");
  6683. this.#r = r;
  6684. this.#s = s;
  6685. this.#v = v;
  6686. this.#networkV = null;
  6687. }
  6688. [Symbol.for('nodejs.util.inspect.custom')]() {
  6689. return `Signature { r: "${this.r}", s: "${this.s}", yParity: ${this.yParity}, networkV: ${this.networkV} }`;
  6690. }
  6691. /**
  6692. * Returns a new identical [[Signature]].
  6693. */
  6694. clone() {
  6695. const clone = new Signature(_guard$3, this.r, this.s, this.v);
  6696. if (this.networkV) {
  6697. clone.#networkV = this.networkV;
  6698. }
  6699. return clone;
  6700. }
  6701. /**
  6702. * Returns a representation that is compatible with ``JSON.stringify``.
  6703. */
  6704. toJSON() {
  6705. const networkV = this.networkV;
  6706. return {
  6707. _type: "signature",
  6708. networkV: ((networkV != null) ? networkV.toString() : null),
  6709. r: this.r, s: this.s, v: this.v,
  6710. };
  6711. }
  6712. /**
  6713. * Compute the chain ID from the ``v`` in a legacy EIP-155 transactions.
  6714. *
  6715. * @example:
  6716. * Signature.getChainId(45)
  6717. * //_result:
  6718. *
  6719. * Signature.getChainId(46)
  6720. * //_result:
  6721. */
  6722. static getChainId(v) {
  6723. const bv = getBigInt(v, "v");
  6724. // The v is not an EIP-155 v, so it is the unspecified chain ID
  6725. if ((bv == BN_27$1) || (bv == BN_28$1)) {
  6726. return BN_0$7;
  6727. }
  6728. // Bad value for an EIP-155 v
  6729. assertArgument(bv >= BN_35$1, "invalid EIP-155 v", "v", v);
  6730. return (bv - BN_35$1) / BN_2$3;
  6731. }
  6732. /**
  6733. * Compute the ``v`` for a chain ID for a legacy EIP-155 transactions.
  6734. *
  6735. * Legacy transactions which use [[link-eip-155]] hijack the ``v``
  6736. * property to include the chain ID.
  6737. *
  6738. * @example:
  6739. * Signature.getChainIdV(5, 27)
  6740. * //_result:
  6741. *
  6742. * Signature.getChainIdV(5, 28)
  6743. * //_result:
  6744. *
  6745. */
  6746. static getChainIdV(chainId, v) {
  6747. return (getBigInt(chainId) * BN_2$3) + BigInt(35 + v - 27);
  6748. }
  6749. /**
  6750. * Compute the normalized legacy transaction ``v`` from a ``yParirty``,
  6751. * a legacy transaction ``v`` or a legacy [[link-eip-155]] transaction.
  6752. *
  6753. * @example:
  6754. * // The values 0 and 1 imply v is actually yParity
  6755. * Signature.getNormalizedV(0)
  6756. * //_result:
  6757. *
  6758. * // Legacy non-EIP-1559 transaction (i.e. 27 or 28)
  6759. * Signature.getNormalizedV(27)
  6760. * //_result:
  6761. *
  6762. * // Legacy EIP-155 transaction (i.e. >= 35)
  6763. * Signature.getNormalizedV(46)
  6764. * //_result:
  6765. *
  6766. * // Invalid values throw
  6767. * Signature.getNormalizedV(5)
  6768. * //_error:
  6769. */
  6770. static getNormalizedV(v) {
  6771. const bv = getBigInt(v);
  6772. if (bv === BN_0$7 || bv === BN_27$1) {
  6773. return 27;
  6774. }
  6775. if (bv === BN_1$3 || bv === BN_28$1) {
  6776. return 28;
  6777. }
  6778. assertArgument(bv >= BN_35$1, "invalid v", "v", v);
  6779. // Otherwise, EIP-155 v means odd is 27 and even is 28
  6780. return (bv & BN_1$3) ? 27 : 28;
  6781. }
  6782. /**
  6783. * Creates a new [[Signature]].
  6784. *
  6785. * If no %%sig%% is provided, a new [[Signature]] is created
  6786. * with default values.
  6787. *
  6788. * If %%sig%% is a string, it is parsed.
  6789. */
  6790. static from(sig) {
  6791. function assertError(check, message) {
  6792. assertArgument(check, message, "signature", sig);
  6793. }
  6794. if (sig == null) {
  6795. return new Signature(_guard$3, ZeroHash, ZeroHash, 27);
  6796. }
  6797. if (typeof (sig) === "string") {
  6798. const bytes = getBytes(sig, "signature");
  6799. if (bytes.length === 64) {
  6800. const r = hexlify(bytes.slice(0, 32));
  6801. const s = bytes.slice(32, 64);
  6802. const v = (s[0] & 0x80) ? 28 : 27;
  6803. s[0] &= 0x7f;
  6804. return new Signature(_guard$3, r, hexlify(s), v);
  6805. }
  6806. if (bytes.length === 65) {
  6807. const r = hexlify(bytes.slice(0, 32));
  6808. const s = bytes.slice(32, 64);
  6809. assertError((s[0] & 0x80) === 0, "non-canonical s");
  6810. const v = Signature.getNormalizedV(bytes[64]);
  6811. return new Signature(_guard$3, r, hexlify(s), v);
  6812. }
  6813. assertError(false, "invalid raw signature length");
  6814. }
  6815. if (sig instanceof Signature) {
  6816. return sig.clone();
  6817. }
  6818. // Get r
  6819. const _r = sig.r;
  6820. assertError(_r != null, "missing r");
  6821. const r = toUint256(_r);
  6822. // Get s; by any means necessary (we check consistency below)
  6823. const s = (function (s, yParityAndS) {
  6824. if (s != null) {
  6825. return toUint256(s);
  6826. }
  6827. if (yParityAndS != null) {
  6828. assertError(isHexString(yParityAndS, 32), "invalid yParityAndS");
  6829. const bytes = getBytes(yParityAndS);
  6830. bytes[0] &= 0x7f;
  6831. return hexlify(bytes);
  6832. }
  6833. assertError(false, "missing s");
  6834. })(sig.s, sig.yParityAndS);
  6835. assertError((getBytes(s)[0] & 0x80) == 0, "non-canonical s");
  6836. // Get v; by any means necessary (we check consistency below)
  6837. const { networkV, v } = (function (_v, yParityAndS, yParity) {
  6838. if (_v != null) {
  6839. const v = getBigInt(_v);
  6840. return {
  6841. networkV: ((v >= BN_35$1) ? v : undefined),
  6842. v: Signature.getNormalizedV(v)
  6843. };
  6844. }
  6845. if (yParityAndS != null) {
  6846. assertError(isHexString(yParityAndS, 32), "invalid yParityAndS");
  6847. return { v: ((getBytes(yParityAndS)[0] & 0x80) ? 28 : 27) };
  6848. }
  6849. if (yParity != null) {
  6850. switch (getNumber(yParity, "sig.yParity")) {
  6851. case 0: return { v: 27 };
  6852. case 1: return { v: 28 };
  6853. }
  6854. assertError(false, "invalid yParity");
  6855. }
  6856. assertError(false, "missing v");
  6857. })(sig.v, sig.yParityAndS, sig.yParity);
  6858. const result = new Signature(_guard$3, r, s, v);
  6859. if (networkV) {
  6860. result.#networkV = networkV;
  6861. }
  6862. // If multiple of v, yParity, yParityAndS we given, check they match
  6863. assertError(sig.yParity == null || getNumber(sig.yParity, "sig.yParity") === result.yParity, "yParity mismatch");
  6864. assertError(sig.yParityAndS == null || sig.yParityAndS === result.yParityAndS, "yParityAndS mismatch");
  6865. return result;
  6866. }
  6867. }
  6868. /**
  6869. * Add details about signing here.
  6870. *
  6871. * @_subsection: api/crypto:Signing [about-signing]
  6872. */
  6873. /**
  6874. * A **SigningKey** provides high-level access to the elliptic curve
  6875. * cryptography (ECC) operations and key management.
  6876. */
  6877. class SigningKey {
  6878. #privateKey;
  6879. /**
  6880. * Creates a new **SigningKey** for %%privateKey%%.
  6881. */
  6882. constructor(privateKey) {
  6883. assertArgument(dataLength(privateKey) === 32, "invalid private key", "privateKey", "[REDACTED]");
  6884. this.#privateKey = hexlify(privateKey);
  6885. }
  6886. /**
  6887. * The private key.
  6888. */
  6889. get privateKey() { return this.#privateKey; }
  6890. /**
  6891. * The uncompressed public key.
  6892. *
  6893. * This will always begin with the prefix ``0x04`` and be 132
  6894. * characters long (the ``0x`` prefix and 130 hexadecimal nibbles).
  6895. */
  6896. get publicKey() { return SigningKey.computePublicKey(this.#privateKey); }
  6897. /**
  6898. * The compressed public key.
  6899. *
  6900. * This will always begin with either the prefix ``0x02`` or ``0x03``
  6901. * and be 68 characters long (the ``0x`` prefix and 33 hexadecimal
  6902. * nibbles)
  6903. */
  6904. get compressedPublicKey() { return SigningKey.computePublicKey(this.#privateKey, true); }
  6905. /**
  6906. * Return the signature of the signed %%digest%%.
  6907. */
  6908. sign(digest) {
  6909. assertArgument(dataLength(digest) === 32, "invalid digest length", "digest", digest);
  6910. const sig = secp256k1.sign(getBytesCopy(digest), getBytesCopy(this.#privateKey), {
  6911. lowS: true
  6912. });
  6913. return Signature.from({
  6914. r: toBeHex(sig.r, 32),
  6915. s: toBeHex(sig.s, 32),
  6916. v: (sig.recovery ? 0x1c : 0x1b)
  6917. });
  6918. }
  6919. /**
  6920. * Returns the [[link-wiki-ecdh]] shared secret between this
  6921. * private key and the %%other%% key.
  6922. *
  6923. * The %%other%% key may be any type of key, a raw public key,
  6924. * a compressed/uncompressed pubic key or aprivate key.
  6925. *
  6926. * Best practice is usually to use a cryptographic hash on the
  6927. * returned value before using it as a symetric secret.
  6928. *
  6929. * @example:
  6930. * sign1 = new SigningKey(id("some-secret-1"))
  6931. * sign2 = new SigningKey(id("some-secret-2"))
  6932. *
  6933. * // Notice that privA.computeSharedSecret(pubB)...
  6934. * sign1.computeSharedSecret(sign2.publicKey)
  6935. * //_result:
  6936. *
  6937. * // ...is equal to privB.computeSharedSecret(pubA).
  6938. * sign2.computeSharedSecret(sign1.publicKey)
  6939. * //_result:
  6940. */
  6941. computeSharedSecret(other) {
  6942. const pubKey = SigningKey.computePublicKey(other);
  6943. return hexlify(secp256k1.getSharedSecret(getBytesCopy(this.#privateKey), getBytes(pubKey), false));
  6944. }
  6945. /**
  6946. * Compute the public key for %%key%%, optionally %%compressed%%.
  6947. *
  6948. * The %%key%% may be any type of key, a raw public key, a
  6949. * compressed/uncompressed public key or private key.
  6950. *
  6951. * @example:
  6952. * sign = new SigningKey(id("some-secret"));
  6953. *
  6954. * // Compute the uncompressed public key for a private key
  6955. * SigningKey.computePublicKey(sign.privateKey)
  6956. * //_result:
  6957. *
  6958. * // Compute the compressed public key for a private key
  6959. * SigningKey.computePublicKey(sign.privateKey, true)
  6960. * //_result:
  6961. *
  6962. * // Compute the uncompressed public key
  6963. * SigningKey.computePublicKey(sign.publicKey, false);
  6964. * //_result:
  6965. *
  6966. * // Compute the Compressed a public key
  6967. * SigningKey.computePublicKey(sign.publicKey, true);
  6968. * //_result:
  6969. */
  6970. static computePublicKey(key, compressed) {
  6971. let bytes = getBytes(key, "key");
  6972. // private key
  6973. if (bytes.length === 32) {
  6974. const pubKey = secp256k1.getPublicKey(bytes, !!compressed);
  6975. return hexlify(pubKey);
  6976. }
  6977. // raw public key; use uncompressed key with 0x04 prefix
  6978. if (bytes.length === 64) {
  6979. const pub = new Uint8Array(65);
  6980. pub[0] = 0x04;
  6981. pub.set(bytes, 1);
  6982. bytes = pub;
  6983. }
  6984. const point = secp256k1.ProjectivePoint.fromHex(bytes);
  6985. return hexlify(point.toRawBytes(compressed));
  6986. }
  6987. /**
  6988. * Returns the public key for the private key which produced the
  6989. * %%signature%% for the given %%digest%%.
  6990. *
  6991. * @example:
  6992. * key = new SigningKey(id("some-secret"))
  6993. * digest = id("hello world")
  6994. * sig = key.sign(digest)
  6995. *
  6996. * // Notice the signer public key...
  6997. * key.publicKey
  6998. * //_result:
  6999. *
  7000. * // ...is equal to the recovered public key
  7001. * SigningKey.recoverPublicKey(digest, sig)
  7002. * //_result:
  7003. *
  7004. */
  7005. static recoverPublicKey(digest, signature) {
  7006. assertArgument(dataLength(digest) === 32, "invalid digest length", "digest", digest);
  7007. const sig = Signature.from(signature);
  7008. let secpSig = secp256k1.Signature.fromCompact(getBytesCopy(concat([sig.r, sig.s])));
  7009. secpSig = secpSig.addRecoveryBit(sig.yParity);
  7010. const pubKey = secpSig.recoverPublicKey(getBytesCopy(digest));
  7011. assertArgument(pubKey != null, "invalid signautre for digest", "signature", signature);
  7012. return "0x" + pubKey.toHex(false);
  7013. }
  7014. /**
  7015. * Returns the point resulting from adding the ellipic curve points
  7016. * %%p0%% and %%p1%%.
  7017. *
  7018. * This is not a common function most developers should require, but
  7019. * can be useful for certain privacy-specific techniques.
  7020. *
  7021. * For example, it is used by [[HDNodeWallet]] to compute child
  7022. * addresses from parent public keys and chain codes.
  7023. */
  7024. static addPoints(p0, p1, compressed) {
  7025. const pub0 = secp256k1.ProjectivePoint.fromHex(SigningKey.computePublicKey(p0).substring(2));
  7026. const pub1 = secp256k1.ProjectivePoint.fromHex(SigningKey.computePublicKey(p1).substring(2));
  7027. return "0x" + pub0.add(pub1).toHex(!!compressed);
  7028. }
  7029. }
  7030. /**
  7031. * A fundamental building block of Ethereum is the underlying
  7032. * cryptographic primitives.
  7033. *
  7034. * @_section: api/crypto:Cryptographic Functions [about-crypto]
  7035. */
  7036. /**
  7037. * Once called, prevents any future change to the underlying cryptographic
  7038. * primitives using the ``.register`` feature for hooks.
  7039. */
  7040. function lock() {
  7041. computeHmac.lock();
  7042. keccak256.lock();
  7043. pbkdf2.lock();
  7044. randomBytes.lock();
  7045. ripemd160.lock();
  7046. scrypt.lock();
  7047. scryptSync.lock();
  7048. sha256.lock();
  7049. sha512.lock();
  7050. randomBytes.lock();
  7051. }
  7052. const BN_0$6 = BigInt(0);
  7053. const BN_36 = BigInt(36);
  7054. function getChecksumAddress(address) {
  7055. // if (!isHexString(address, 20)) {
  7056. // logger.throwArgumentError("invalid address", "address", address);
  7057. // }
  7058. address = address.toLowerCase();
  7059. const chars = address.substring(2).split("");
  7060. const expanded = new Uint8Array(40);
  7061. for (let i = 0; i < 40; i++) {
  7062. expanded[i] = chars[i].charCodeAt(0);
  7063. }
  7064. const hashed = getBytes(keccak256(expanded));
  7065. for (let i = 0; i < 40; i += 2) {
  7066. if ((hashed[i >> 1] >> 4) >= 8) {
  7067. chars[i] = chars[i].toUpperCase();
  7068. }
  7069. if ((hashed[i >> 1] & 0x0f) >= 8) {
  7070. chars[i + 1] = chars[i + 1].toUpperCase();
  7071. }
  7072. }
  7073. return "0x" + chars.join("");
  7074. }
  7075. // See: https://en.wikipedia.org/wiki/International_Bank_Account_Number
  7076. // Create lookup table
  7077. const ibanLookup = {};
  7078. for (let i = 0; i < 10; i++) {
  7079. ibanLookup[String(i)] = String(i);
  7080. }
  7081. for (let i = 0; i < 26; i++) {
  7082. ibanLookup[String.fromCharCode(65 + i)] = String(10 + i);
  7083. }
  7084. // How many decimal digits can we process? (for 64-bit float, this is 15)
  7085. // i.e. Math.floor(Math.log10(Number.MAX_SAFE_INTEGER));
  7086. const safeDigits = 15;
  7087. function ibanChecksum(address) {
  7088. address = address.toUpperCase();
  7089. address = address.substring(4) + address.substring(0, 2) + "00";
  7090. let expanded = address.split("").map((c) => { return ibanLookup[c]; }).join("");
  7091. // Javascript can handle integers safely up to 15 (decimal) digits
  7092. while (expanded.length >= safeDigits) {
  7093. let block = expanded.substring(0, safeDigits);
  7094. expanded = parseInt(block, 10) % 97 + expanded.substring(block.length);
  7095. }
  7096. let checksum = String(98 - (parseInt(expanded, 10) % 97));
  7097. while (checksum.length < 2) {
  7098. checksum = "0" + checksum;
  7099. }
  7100. return checksum;
  7101. }
  7102. const Base36 = (function () {
  7103. const result = {};
  7104. for (let i = 0; i < 36; i++) {
  7105. const key = "0123456789abcdefghijklmnopqrstuvwxyz"[i];
  7106. result[key] = BigInt(i);
  7107. }
  7108. return result;
  7109. })();
  7110. function fromBase36(value) {
  7111. value = value.toLowerCase();
  7112. let result = BN_0$6;
  7113. for (let i = 0; i < value.length; i++) {
  7114. result = result * BN_36 + Base36[value[i]];
  7115. }
  7116. return result;
  7117. }
  7118. /**
  7119. * Returns a normalized and checksumed address for %%address%%.
  7120. * This accepts non-checksum addresses, checksum addresses and
  7121. * [[getIcapAddress]] formats.
  7122. *
  7123. * The checksum in Ethereum uses the capitalization (upper-case
  7124. * vs lower-case) of the characters within an address to encode
  7125. * its checksum, which offers, on average, a checksum of 15-bits.
  7126. *
  7127. * If %%address%% contains both upper-case and lower-case, it is
  7128. * assumed to already be a checksum address and its checksum is
  7129. * validated, and if the address fails its expected checksum an
  7130. * error is thrown.
  7131. *
  7132. * If you wish the checksum of %%address%% to be ignore, it should
  7133. * be converted to lower-case (i.e. ``.toLowercase()``) before
  7134. * being passed in. This should be a very rare situation though,
  7135. * that you wish to bypass the safegaurds in place to protect
  7136. * against an address that has been incorrectly copied from another
  7137. * source.
  7138. *
  7139. * @example:
  7140. * // Adds the checksum (via upper-casing specific letters)
  7141. * getAddress("0x8ba1f109551bd432803012645ac136ddd64dba72")
  7142. * //_result:
  7143. *
  7144. * // Converts ICAP address and adds checksum
  7145. * getAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36");
  7146. * //_result:
  7147. *
  7148. * // Throws an error if an address contains mixed case,
  7149. * // but the checksum fails
  7150. * getAddress("0x8Ba1f109551bD432803012645Ac136ddd64DBA72")
  7151. * //_error:
  7152. */
  7153. function getAddress(address) {
  7154. assertArgument(typeof (address) === "string", "invalid address", "address", address);
  7155. if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) {
  7156. // Missing the 0x prefix
  7157. if (!address.startsWith("0x")) {
  7158. address = "0x" + address;
  7159. }
  7160. const result = getChecksumAddress(address);
  7161. // It is a checksummed address with a bad checksum
  7162. assertArgument(!address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) || result === address, "bad address checksum", "address", address);
  7163. return result;
  7164. }
  7165. // Maybe ICAP? (we only support direct mode)
  7166. if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) {
  7167. // It is an ICAP address with a bad checksum
  7168. assertArgument(address.substring(2, 4) === ibanChecksum(address), "bad icap checksum", "address", address);
  7169. let result = fromBase36(address.substring(4)).toString(16);
  7170. while (result.length < 40) {
  7171. result = "0" + result;
  7172. }
  7173. return getChecksumAddress("0x" + result);
  7174. }
  7175. assertArgument(false, "invalid address", "address", address);
  7176. }
  7177. /**
  7178. * The [ICAP Address format](link-icap) format is an early checksum
  7179. * format which attempts to be compatible with the banking
  7180. * industry [IBAN format](link-wiki-iban) for bank accounts.
  7181. *
  7182. * It is no longer common or a recommended format.
  7183. *
  7184. * @example:
  7185. * getIcapAddress("0x8ba1f109551bd432803012645ac136ddd64dba72");
  7186. * //_result:
  7187. *
  7188. * getIcapAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36");
  7189. * //_result:
  7190. *
  7191. * // Throws an error if the ICAP checksum is wrong
  7192. * getIcapAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK37");
  7193. * //_error:
  7194. */
  7195. function getIcapAddress(address) {
  7196. //let base36 = _base16To36(getAddress(address).substring(2)).toUpperCase();
  7197. let base36 = BigInt(getAddress(address)).toString(36).toUpperCase();
  7198. while (base36.length < 30) {
  7199. base36 = "0" + base36;
  7200. }
  7201. return "XE" + ibanChecksum("XE00" + base36) + base36;
  7202. }
  7203. // http://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed
  7204. /**
  7205. * Returns the address that would result from a ``CREATE`` for %%tx%%.
  7206. *
  7207. * This can be used to compute the address a contract will be
  7208. * deployed to by an EOA when sending a deployment transaction (i.e.
  7209. * when the ``to`` address is ``null``).
  7210. *
  7211. * This can also be used to compute the address a contract will be
  7212. * deployed to by a contract, by using the contract's address as the
  7213. * ``to`` and the contract's nonce.
  7214. *
  7215. * @example
  7216. * from = "0x8ba1f109551bD432803012645Ac136ddd64DBA72";
  7217. * nonce = 5;
  7218. *
  7219. * getCreateAddress({ from, nonce });
  7220. * //_result:
  7221. */
  7222. function getCreateAddress(tx) {
  7223. const from = getAddress(tx.from);
  7224. const nonce = getBigInt(tx.nonce, "tx.nonce");
  7225. let nonceHex = nonce.toString(16);
  7226. if (nonceHex === "0") {
  7227. nonceHex = "0x";
  7228. }
  7229. else if (nonceHex.length % 2) {
  7230. nonceHex = "0x0" + nonceHex;
  7231. }
  7232. else {
  7233. nonceHex = "0x" + nonceHex;
  7234. }
  7235. return getAddress(dataSlice(keccak256(encodeRlp([from, nonceHex])), 12));
  7236. }
  7237. /**
  7238. * Returns the address that would result from a ``CREATE2`` operation
  7239. * with the given %%from%%, %%salt%% and %%initCodeHash%%.
  7240. *
  7241. * To compute the %%initCodeHash%% from a contract's init code, use
  7242. * the [[keccak256]] function.
  7243. *
  7244. * For a quick overview and example of ``CREATE2``, see [[link-ricmoo-wisps]].
  7245. *
  7246. * @example
  7247. * // The address of the contract
  7248. * from = "0x8ba1f109551bD432803012645Ac136ddd64DBA72"
  7249. *
  7250. * // The salt
  7251. * salt = id("HelloWorld")
  7252. *
  7253. * // The hash of the initCode
  7254. * initCode = "0x6394198df16000526103ff60206004601c335afa6040516060f3";
  7255. * initCodeHash = keccak256(initCode)
  7256. *
  7257. * getCreate2Address(from, salt, initCodeHash)
  7258. * //_result:
  7259. */
  7260. function getCreate2Address(_from, _salt, _initCodeHash) {
  7261. const from = getAddress(_from);
  7262. const salt = getBytes(_salt, "salt");
  7263. const initCodeHash = getBytes(_initCodeHash, "initCodeHash");
  7264. assertArgument(salt.length === 32, "salt must be 32 bytes", "salt", _salt);
  7265. assertArgument(initCodeHash.length === 32, "initCodeHash must be 32 bytes", "initCodeHash", _initCodeHash);
  7266. return getAddress(dataSlice(keccak256(concat(["0xff", from, salt, initCodeHash])), 12));
  7267. }
  7268. /**
  7269. * Returns true if %%value%% is an object which implements the
  7270. * [[Addressable]] interface.
  7271. *
  7272. * @example:
  7273. * // Wallets and AbstractSigner sub-classes
  7274. * isAddressable(Wallet.createRandom())
  7275. * //_result:
  7276. *
  7277. * // Contracts
  7278. * contract = new Contract("dai.tokens.ethers.eth", [ ], provider)
  7279. * isAddressable(contract)
  7280. * //_result:
  7281. */
  7282. function isAddressable(value) {
  7283. return (value && typeof (value.getAddress) === "function");
  7284. }
  7285. /**
  7286. * Returns true if %%value%% is a valid address.
  7287. *
  7288. * @example:
  7289. * // Valid address
  7290. * isAddress("0x8ba1f109551bD432803012645Ac136ddd64DBA72")
  7291. * //_result:
  7292. *
  7293. * // Valid ICAP address
  7294. * isAddress("XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36")
  7295. * //_result:
  7296. *
  7297. * // Invalid checksum
  7298. * isAddress("0x8Ba1f109551bD432803012645Ac136ddd64DBa72")
  7299. * //_result:
  7300. *
  7301. * // Invalid ICAP checksum
  7302. * isAddress("0x8Ba1f109551bD432803012645Ac136ddd64DBA72")
  7303. * //_result:
  7304. *
  7305. * // Not an address (an ENS name requires a provided and an
  7306. * // asynchronous API to access)
  7307. * isAddress("ricmoo.eth")
  7308. * //_result:
  7309. */
  7310. function isAddress(value) {
  7311. try {
  7312. getAddress(value);
  7313. return true;
  7314. }
  7315. catch (error) { }
  7316. return false;
  7317. }
  7318. async function checkAddress(target, promise) {
  7319. const result = await promise;
  7320. if (result == null || result === "0x0000000000000000000000000000000000000000") {
  7321. assert(typeof (target) !== "string", "unconfigured name", "UNCONFIGURED_NAME", { value: target });
  7322. assertArgument(false, "invalid AddressLike value; did not resolve to a value address", "target", target);
  7323. }
  7324. return getAddress(result);
  7325. }
  7326. /**
  7327. * Resolves to an address for the %%target%%, which may be any
  7328. * supported address type, an [[Addressable]] or a Promise which
  7329. * resolves to an address.
  7330. *
  7331. * If an ENS name is provided, but that name has not been correctly
  7332. * configured a [[UnconfiguredNameError]] is thrown.
  7333. *
  7334. * @example:
  7335. * addr = "0x6B175474E89094C44Da98b954EedeAC495271d0F"
  7336. *
  7337. * // Addresses are return synchronously
  7338. * resolveAddress(addr, provider)
  7339. * //_result:
  7340. *
  7341. * // Address promises are resolved asynchronously
  7342. * resolveAddress(Promise.resolve(addr))
  7343. * //_result:
  7344. *
  7345. * // ENS names are resolved asynchronously
  7346. * resolveAddress("dai.tokens.ethers.eth", provider)
  7347. * //_result:
  7348. *
  7349. * // Addressable objects are resolved asynchronously
  7350. * contract = new Contract(addr, [ ])
  7351. * resolveAddress(contract, provider)
  7352. * //_result:
  7353. *
  7354. * // Unconfigured ENS names reject
  7355. * resolveAddress("nothing-here.ricmoo.eth", provider)
  7356. * //_error:
  7357. *
  7358. * // ENS names require a NameResolver object passed in
  7359. * // (notice the provider was omitted)
  7360. * resolveAddress("nothing-here.ricmoo.eth")
  7361. * //_error:
  7362. */
  7363. function resolveAddress(target, resolver) {
  7364. if (typeof (target) === "string") {
  7365. if (target.match(/^0x[0-9a-f]{40}$/i)) {
  7366. return getAddress(target);
  7367. }
  7368. assert(resolver != null, "ENS resolution requires a provider", "UNSUPPORTED_OPERATION", { operation: "resolveName" });
  7369. return checkAddress(target, resolver.resolveName(target));
  7370. }
  7371. else if (isAddressable(target)) {
  7372. return checkAddress(target, target.getAddress());
  7373. }
  7374. else if (target && typeof (target.then) === "function") {
  7375. return checkAddress(target, target);
  7376. }
  7377. assertArgument(false, "unsupported addressable value", "target", target);
  7378. }
  7379. /**
  7380. * A Typed object allows a value to have its type explicitly
  7381. * specified.
  7382. *
  7383. * For example, in Solidity, the value ``45`` could represent a
  7384. * ``uint8`` or a ``uint256``. The value ``0x1234`` could represent
  7385. * a ``bytes2`` or ``bytes``.
  7386. *
  7387. * Since JavaScript has no meaningful way to explicitly inform any
  7388. * APIs which what the type is, this allows transparent interoperation
  7389. * with Soldity.
  7390. *
  7391. * @_subsection: api/abi:Typed Values
  7392. */
  7393. const _gaurd = {};
  7394. function n(value, width) {
  7395. let signed = false;
  7396. if (width < 0) {
  7397. signed = true;
  7398. width *= -1;
  7399. }
  7400. // @TODO: Check range is valid for value
  7401. return new Typed(_gaurd, `${signed ? "" : "u"}int${width}`, value, { signed, width });
  7402. }
  7403. function b(value, size) {
  7404. // @TODO: Check range is valid for value
  7405. return new Typed(_gaurd, `bytes${(size) ? size : ""}`, value, { size });
  7406. }
  7407. const _typedSymbol = Symbol.for("_ethers_typed");
  7408. /**
  7409. * The **Typed** class to wrap values providing explicit type information.
  7410. */
  7411. class Typed {
  7412. /**
  7413. * The type, as a Solidity-compatible type.
  7414. */
  7415. type;
  7416. /**
  7417. * The actual value.
  7418. */
  7419. value;
  7420. #options;
  7421. /**
  7422. * @_ignore:
  7423. */
  7424. _typedSymbol;
  7425. /**
  7426. * @_ignore:
  7427. */
  7428. constructor(gaurd, type, value, options) {
  7429. if (options == null) {
  7430. options = null;
  7431. }
  7432. assertPrivate(_gaurd, gaurd, "Typed");
  7433. defineProperties(this, { _typedSymbol, type, value });
  7434. this.#options = options;
  7435. // Check the value is valid
  7436. this.format();
  7437. }
  7438. /**
  7439. * Format the type as a Human-Readable type.
  7440. */
  7441. format() {
  7442. if (this.type === "array") {
  7443. throw new Error("");
  7444. }
  7445. else if (this.type === "dynamicArray") {
  7446. throw new Error("");
  7447. }
  7448. else if (this.type === "tuple") {
  7449. return `tuple(${this.value.map((v) => v.format()).join(",")})`;
  7450. }
  7451. return this.type;
  7452. }
  7453. /**
  7454. * The default value returned by this type.
  7455. */
  7456. defaultValue() {
  7457. return 0;
  7458. }
  7459. /**
  7460. * The minimum value for numeric types.
  7461. */
  7462. minValue() {
  7463. return 0;
  7464. }
  7465. /**
  7466. * The maximum value for numeric types.
  7467. */
  7468. maxValue() {
  7469. return 0;
  7470. }
  7471. /**
  7472. * Returns ``true`` and provides a type guard is this is a [[TypedBigInt]].
  7473. */
  7474. isBigInt() {
  7475. return !!(this.type.match(/^u?int[0-9]+$/));
  7476. }
  7477. /**
  7478. * Returns ``true`` and provides a type guard is this is a [[TypedData]].
  7479. */
  7480. isData() {
  7481. return this.type.startsWith("bytes");
  7482. }
  7483. /**
  7484. * Returns ``true`` and provides a type guard is this is a [[TypedString]].
  7485. */
  7486. isString() {
  7487. return (this.type === "string");
  7488. }
  7489. /**
  7490. * Returns the tuple name, if this is a tuple. Throws otherwise.
  7491. */
  7492. get tupleName() {
  7493. if (this.type !== "tuple") {
  7494. throw TypeError("not a tuple");
  7495. }
  7496. return this.#options;
  7497. }
  7498. // Returns the length of this type as an array
  7499. // - `null` indicates the length is unforced, it could be dynamic
  7500. // - `-1` indicates the length is dynamic
  7501. // - any other value indicates it is a static array and is its length
  7502. /**
  7503. * Returns the length of the array type or ``-1`` if it is dynamic.
  7504. *
  7505. * Throws if the type is not an array.
  7506. */
  7507. get arrayLength() {
  7508. if (this.type !== "array") {
  7509. throw TypeError("not an array");
  7510. }
  7511. if (this.#options === true) {
  7512. return -1;
  7513. }
  7514. if (this.#options === false) {
  7515. return (this.value).length;
  7516. }
  7517. return null;
  7518. }
  7519. /**
  7520. * Returns a new **Typed** of %%type%% with the %%value%%.
  7521. */
  7522. static from(type, value) {
  7523. return new Typed(_gaurd, type, value);
  7524. }
  7525. /**
  7526. * Return a new ``uint8`` type for %%v%%.
  7527. */
  7528. static uint8(v) { return n(v, 8); }
  7529. /**
  7530. * Return a new ``uint16`` type for %%v%%.
  7531. */
  7532. static uint16(v) { return n(v, 16); }
  7533. /**
  7534. * Return a new ``uint24`` type for %%v%%.
  7535. */
  7536. static uint24(v) { return n(v, 24); }
  7537. /**
  7538. * Return a new ``uint32`` type for %%v%%.
  7539. */
  7540. static uint32(v) { return n(v, 32); }
  7541. /**
  7542. * Return a new ``uint40`` type for %%v%%.
  7543. */
  7544. static uint40(v) { return n(v, 40); }
  7545. /**
  7546. * Return a new ``uint48`` type for %%v%%.
  7547. */
  7548. static uint48(v) { return n(v, 48); }
  7549. /**
  7550. * Return a new ``uint56`` type for %%v%%.
  7551. */
  7552. static uint56(v) { return n(v, 56); }
  7553. /**
  7554. * Return a new ``uint64`` type for %%v%%.
  7555. */
  7556. static uint64(v) { return n(v, 64); }
  7557. /**
  7558. * Return a new ``uint72`` type for %%v%%.
  7559. */
  7560. static uint72(v) { return n(v, 72); }
  7561. /**
  7562. * Return a new ``uint80`` type for %%v%%.
  7563. */
  7564. static uint80(v) { return n(v, 80); }
  7565. /**
  7566. * Return a new ``uint88`` type for %%v%%.
  7567. */
  7568. static uint88(v) { return n(v, 88); }
  7569. /**
  7570. * Return a new ``uint96`` type for %%v%%.
  7571. */
  7572. static uint96(v) { return n(v, 96); }
  7573. /**
  7574. * Return a new ``uint104`` type for %%v%%.
  7575. */
  7576. static uint104(v) { return n(v, 104); }
  7577. /**
  7578. * Return a new ``uint112`` type for %%v%%.
  7579. */
  7580. static uint112(v) { return n(v, 112); }
  7581. /**
  7582. * Return a new ``uint120`` type for %%v%%.
  7583. */
  7584. static uint120(v) { return n(v, 120); }
  7585. /**
  7586. * Return a new ``uint128`` type for %%v%%.
  7587. */
  7588. static uint128(v) { return n(v, 128); }
  7589. /**
  7590. * Return a new ``uint136`` type for %%v%%.
  7591. */
  7592. static uint136(v) { return n(v, 136); }
  7593. /**
  7594. * Return a new ``uint144`` type for %%v%%.
  7595. */
  7596. static uint144(v) { return n(v, 144); }
  7597. /**
  7598. * Return a new ``uint152`` type for %%v%%.
  7599. */
  7600. static uint152(v) { return n(v, 152); }
  7601. /**
  7602. * Return a new ``uint160`` type for %%v%%.
  7603. */
  7604. static uint160(v) { return n(v, 160); }
  7605. /**
  7606. * Return a new ``uint168`` type for %%v%%.
  7607. */
  7608. static uint168(v) { return n(v, 168); }
  7609. /**
  7610. * Return a new ``uint176`` type for %%v%%.
  7611. */
  7612. static uint176(v) { return n(v, 176); }
  7613. /**
  7614. * Return a new ``uint184`` type for %%v%%.
  7615. */
  7616. static uint184(v) { return n(v, 184); }
  7617. /**
  7618. * Return a new ``uint192`` type for %%v%%.
  7619. */
  7620. static uint192(v) { return n(v, 192); }
  7621. /**
  7622. * Return a new ``uint200`` type for %%v%%.
  7623. */
  7624. static uint200(v) { return n(v, 200); }
  7625. /**
  7626. * Return a new ``uint208`` type for %%v%%.
  7627. */
  7628. static uint208(v) { return n(v, 208); }
  7629. /**
  7630. * Return a new ``uint216`` type for %%v%%.
  7631. */
  7632. static uint216(v) { return n(v, 216); }
  7633. /**
  7634. * Return a new ``uint224`` type for %%v%%.
  7635. */
  7636. static uint224(v) { return n(v, 224); }
  7637. /**
  7638. * Return a new ``uint232`` type for %%v%%.
  7639. */
  7640. static uint232(v) { return n(v, 232); }
  7641. /**
  7642. * Return a new ``uint240`` type for %%v%%.
  7643. */
  7644. static uint240(v) { return n(v, 240); }
  7645. /**
  7646. * Return a new ``uint248`` type for %%v%%.
  7647. */
  7648. static uint248(v) { return n(v, 248); }
  7649. /**
  7650. * Return a new ``uint256`` type for %%v%%.
  7651. */
  7652. static uint256(v) { return n(v, 256); }
  7653. /**
  7654. * Return a new ``uint256`` type for %%v%%.
  7655. */
  7656. static uint(v) { return n(v, 256); }
  7657. /**
  7658. * Return a new ``int8`` type for %%v%%.
  7659. */
  7660. static int8(v) { return n(v, -8); }
  7661. /**
  7662. * Return a new ``int16`` type for %%v%%.
  7663. */
  7664. static int16(v) { return n(v, -16); }
  7665. /**
  7666. * Return a new ``int24`` type for %%v%%.
  7667. */
  7668. static int24(v) { return n(v, -24); }
  7669. /**
  7670. * Return a new ``int32`` type for %%v%%.
  7671. */
  7672. static int32(v) { return n(v, -32); }
  7673. /**
  7674. * Return a new ``int40`` type for %%v%%.
  7675. */
  7676. static int40(v) { return n(v, -40); }
  7677. /**
  7678. * Return a new ``int48`` type for %%v%%.
  7679. */
  7680. static int48(v) { return n(v, -48); }
  7681. /**
  7682. * Return a new ``int56`` type for %%v%%.
  7683. */
  7684. static int56(v) { return n(v, -56); }
  7685. /**
  7686. * Return a new ``int64`` type for %%v%%.
  7687. */
  7688. static int64(v) { return n(v, -64); }
  7689. /**
  7690. * Return a new ``int72`` type for %%v%%.
  7691. */
  7692. static int72(v) { return n(v, -72); }
  7693. /**
  7694. * Return a new ``int80`` type for %%v%%.
  7695. */
  7696. static int80(v) { return n(v, -80); }
  7697. /**
  7698. * Return a new ``int88`` type for %%v%%.
  7699. */
  7700. static int88(v) { return n(v, -88); }
  7701. /**
  7702. * Return a new ``int96`` type for %%v%%.
  7703. */
  7704. static int96(v) { return n(v, -96); }
  7705. /**
  7706. * Return a new ``int104`` type for %%v%%.
  7707. */
  7708. static int104(v) { return n(v, -104); }
  7709. /**
  7710. * Return a new ``int112`` type for %%v%%.
  7711. */
  7712. static int112(v) { return n(v, -112); }
  7713. /**
  7714. * Return a new ``int120`` type for %%v%%.
  7715. */
  7716. static int120(v) { return n(v, -120); }
  7717. /**
  7718. * Return a new ``int128`` type for %%v%%.
  7719. */
  7720. static int128(v) { return n(v, -128); }
  7721. /**
  7722. * Return a new ``int136`` type for %%v%%.
  7723. */
  7724. static int136(v) { return n(v, -136); }
  7725. /**
  7726. * Return a new ``int144`` type for %%v%%.
  7727. */
  7728. static int144(v) { return n(v, -144); }
  7729. /**
  7730. * Return a new ``int52`` type for %%v%%.
  7731. */
  7732. static int152(v) { return n(v, -152); }
  7733. /**
  7734. * Return a new ``int160`` type for %%v%%.
  7735. */
  7736. static int160(v) { return n(v, -160); }
  7737. /**
  7738. * Return a new ``int168`` type for %%v%%.
  7739. */
  7740. static int168(v) { return n(v, -168); }
  7741. /**
  7742. * Return a new ``int176`` type for %%v%%.
  7743. */
  7744. static int176(v) { return n(v, -176); }
  7745. /**
  7746. * Return a new ``int184`` type for %%v%%.
  7747. */
  7748. static int184(v) { return n(v, -184); }
  7749. /**
  7750. * Return a new ``int92`` type for %%v%%.
  7751. */
  7752. static int192(v) { return n(v, -192); }
  7753. /**
  7754. * Return a new ``int200`` type for %%v%%.
  7755. */
  7756. static int200(v) { return n(v, -200); }
  7757. /**
  7758. * Return a new ``int208`` type for %%v%%.
  7759. */
  7760. static int208(v) { return n(v, -208); }
  7761. /**
  7762. * Return a new ``int216`` type for %%v%%.
  7763. */
  7764. static int216(v) { return n(v, -216); }
  7765. /**
  7766. * Return a new ``int224`` type for %%v%%.
  7767. */
  7768. static int224(v) { return n(v, -224); }
  7769. /**
  7770. * Return a new ``int232`` type for %%v%%.
  7771. */
  7772. static int232(v) { return n(v, -232); }
  7773. /**
  7774. * Return a new ``int240`` type for %%v%%.
  7775. */
  7776. static int240(v) { return n(v, -240); }
  7777. /**
  7778. * Return a new ``int248`` type for %%v%%.
  7779. */
  7780. static int248(v) { return n(v, -248); }
  7781. /**
  7782. * Return a new ``int256`` type for %%v%%.
  7783. */
  7784. static int256(v) { return n(v, -256); }
  7785. /**
  7786. * Return a new ``int256`` type for %%v%%.
  7787. */
  7788. static int(v) { return n(v, -256); }
  7789. /**
  7790. * Return a new ``bytes1`` type for %%v%%.
  7791. */
  7792. static bytes1(v) { return b(v, 1); }
  7793. /**
  7794. * Return a new ``bytes2`` type for %%v%%.
  7795. */
  7796. static bytes2(v) { return b(v, 2); }
  7797. /**
  7798. * Return a new ``bytes3`` type for %%v%%.
  7799. */
  7800. static bytes3(v) { return b(v, 3); }
  7801. /**
  7802. * Return a new ``bytes4`` type for %%v%%.
  7803. */
  7804. static bytes4(v) { return b(v, 4); }
  7805. /**
  7806. * Return a new ``bytes5`` type for %%v%%.
  7807. */
  7808. static bytes5(v) { return b(v, 5); }
  7809. /**
  7810. * Return a new ``bytes6`` type for %%v%%.
  7811. */
  7812. static bytes6(v) { return b(v, 6); }
  7813. /**
  7814. * Return a new ``bytes7`` type for %%v%%.
  7815. */
  7816. static bytes7(v) { return b(v, 7); }
  7817. /**
  7818. * Return a new ``bytes8`` type for %%v%%.
  7819. */
  7820. static bytes8(v) { return b(v, 8); }
  7821. /**
  7822. * Return a new ``bytes9`` type for %%v%%.
  7823. */
  7824. static bytes9(v) { return b(v, 9); }
  7825. /**
  7826. * Return a new ``bytes10`` type for %%v%%.
  7827. */
  7828. static bytes10(v) { return b(v, 10); }
  7829. /**
  7830. * Return a new ``bytes11`` type for %%v%%.
  7831. */
  7832. static bytes11(v) { return b(v, 11); }
  7833. /**
  7834. * Return a new ``bytes12`` type for %%v%%.
  7835. */
  7836. static bytes12(v) { return b(v, 12); }
  7837. /**
  7838. * Return a new ``bytes13`` type for %%v%%.
  7839. */
  7840. static bytes13(v) { return b(v, 13); }
  7841. /**
  7842. * Return a new ``bytes14`` type for %%v%%.
  7843. */
  7844. static bytes14(v) { return b(v, 14); }
  7845. /**
  7846. * Return a new ``bytes15`` type for %%v%%.
  7847. */
  7848. static bytes15(v) { return b(v, 15); }
  7849. /**
  7850. * Return a new ``bytes16`` type for %%v%%.
  7851. */
  7852. static bytes16(v) { return b(v, 16); }
  7853. /**
  7854. * Return a new ``bytes17`` type for %%v%%.
  7855. */
  7856. static bytes17(v) { return b(v, 17); }
  7857. /**
  7858. * Return a new ``bytes18`` type for %%v%%.
  7859. */
  7860. static bytes18(v) { return b(v, 18); }
  7861. /**
  7862. * Return a new ``bytes19`` type for %%v%%.
  7863. */
  7864. static bytes19(v) { return b(v, 19); }
  7865. /**
  7866. * Return a new ``bytes20`` type for %%v%%.
  7867. */
  7868. static bytes20(v) { return b(v, 20); }
  7869. /**
  7870. * Return a new ``bytes21`` type for %%v%%.
  7871. */
  7872. static bytes21(v) { return b(v, 21); }
  7873. /**
  7874. * Return a new ``bytes22`` type for %%v%%.
  7875. */
  7876. static bytes22(v) { return b(v, 22); }
  7877. /**
  7878. * Return a new ``bytes23`` type for %%v%%.
  7879. */
  7880. static bytes23(v) { return b(v, 23); }
  7881. /**
  7882. * Return a new ``bytes24`` type for %%v%%.
  7883. */
  7884. static bytes24(v) { return b(v, 24); }
  7885. /**
  7886. * Return a new ``bytes25`` type for %%v%%.
  7887. */
  7888. static bytes25(v) { return b(v, 25); }
  7889. /**
  7890. * Return a new ``bytes26`` type for %%v%%.
  7891. */
  7892. static bytes26(v) { return b(v, 26); }
  7893. /**
  7894. * Return a new ``bytes27`` type for %%v%%.
  7895. */
  7896. static bytes27(v) { return b(v, 27); }
  7897. /**
  7898. * Return a new ``bytes28`` type for %%v%%.
  7899. */
  7900. static bytes28(v) { return b(v, 28); }
  7901. /**
  7902. * Return a new ``bytes29`` type for %%v%%.
  7903. */
  7904. static bytes29(v) { return b(v, 29); }
  7905. /**
  7906. * Return a new ``bytes30`` type for %%v%%.
  7907. */
  7908. static bytes30(v) { return b(v, 30); }
  7909. /**
  7910. * Return a new ``bytes31`` type for %%v%%.
  7911. */
  7912. static bytes31(v) { return b(v, 31); }
  7913. /**
  7914. * Return a new ``bytes32`` type for %%v%%.
  7915. */
  7916. static bytes32(v) { return b(v, 32); }
  7917. /**
  7918. * Return a new ``address`` type for %%v%%.
  7919. */
  7920. static address(v) { return new Typed(_gaurd, "address", v); }
  7921. /**
  7922. * Return a new ``bool`` type for %%v%%.
  7923. */
  7924. static bool(v) { return new Typed(_gaurd, "bool", !!v); }
  7925. /**
  7926. * Return a new ``bytes`` type for %%v%%.
  7927. */
  7928. static bytes(v) { return new Typed(_gaurd, "bytes", v); }
  7929. /**
  7930. * Return a new ``string`` type for %%v%%.
  7931. */
  7932. static string(v) { return new Typed(_gaurd, "string", v); }
  7933. /**
  7934. * Return a new ``array`` type for %%v%%, allowing %%dynamic%% length.
  7935. */
  7936. static array(v, dynamic) {
  7937. throw new Error("not implemented yet");
  7938. }
  7939. /**
  7940. * Return a new ``tuple`` type for %%v%%, with the optional %%name%%.
  7941. */
  7942. static tuple(v, name) {
  7943. throw new Error("not implemented yet");
  7944. }
  7945. /**
  7946. * Return a new ``uint8`` type for %%v%%.
  7947. */
  7948. static overrides(v) {
  7949. return new Typed(_gaurd, "overrides", Object.assign({}, v));
  7950. }
  7951. /**
  7952. * Returns true only if %%value%% is a [[Typed]] instance.
  7953. */
  7954. static isTyped(value) {
  7955. return (value
  7956. && typeof (value) === "object"
  7957. && "_typedSymbol" in value
  7958. && value._typedSymbol === _typedSymbol);
  7959. }
  7960. /**
  7961. * If the value is a [[Typed]] instance, validates the underlying value
  7962. * and returns it, otherwise returns value directly.
  7963. *
  7964. * This is useful for functions that with to accept either a [[Typed]]
  7965. * object or values.
  7966. */
  7967. static dereference(value, type) {
  7968. if (Typed.isTyped(value)) {
  7969. if (value.type !== type) {
  7970. throw new Error(`invalid type: expecetd ${type}, got ${value.type}`);
  7971. }
  7972. return value.value;
  7973. }
  7974. return value;
  7975. }
  7976. }
  7977. /**
  7978. * @_ignore
  7979. */
  7980. class AddressCoder extends Coder {
  7981. constructor(localName) {
  7982. super("address", "address", localName, false);
  7983. }
  7984. defaultValue() {
  7985. return "0x0000000000000000000000000000000000000000";
  7986. }
  7987. encode(writer, _value) {
  7988. let value = Typed.dereference(_value, "string");
  7989. try {
  7990. value = getAddress(value);
  7991. }
  7992. catch (error) {
  7993. return this._throwError(error.message, _value);
  7994. }
  7995. return writer.writeValue(value);
  7996. }
  7997. decode(reader) {
  7998. return getAddress(toBeHex(reader.readValue(), 20));
  7999. }
  8000. }
  8001. /**
  8002. * Clones the functionality of an existing Coder, but without a localName
  8003. *
  8004. * @_ignore
  8005. */
  8006. class AnonymousCoder extends Coder {
  8007. coder;
  8008. constructor(coder) {
  8009. super(coder.name, coder.type, "_", coder.dynamic);
  8010. this.coder = coder;
  8011. }
  8012. defaultValue() {
  8013. return this.coder.defaultValue();
  8014. }
  8015. encode(writer, value) {
  8016. return this.coder.encode(writer, value);
  8017. }
  8018. decode(reader) {
  8019. return this.coder.decode(reader);
  8020. }
  8021. }
  8022. /**
  8023. * @_ignore
  8024. */
  8025. function pack(writer, coders, values) {
  8026. let arrayValues = [];
  8027. if (Array.isArray(values)) {
  8028. arrayValues = values;
  8029. }
  8030. else if (values && typeof (values) === "object") {
  8031. let unique = {};
  8032. arrayValues = coders.map((coder) => {
  8033. const name = coder.localName;
  8034. assert(name, "cannot encode object for signature with missing names", "INVALID_ARGUMENT", { argument: "values", info: { coder }, value: values });
  8035. assert(!unique[name], "cannot encode object for signature with duplicate names", "INVALID_ARGUMENT", { argument: "values", info: { coder }, value: values });
  8036. unique[name] = true;
  8037. return values[name];
  8038. });
  8039. }
  8040. else {
  8041. assertArgument(false, "invalid tuple value", "tuple", values);
  8042. }
  8043. assertArgument(coders.length === arrayValues.length, "types/value length mismatch", "tuple", values);
  8044. let staticWriter = new Writer();
  8045. let dynamicWriter = new Writer();
  8046. let updateFuncs = [];
  8047. coders.forEach((coder, index) => {
  8048. let value = arrayValues[index];
  8049. if (coder.dynamic) {
  8050. // Get current dynamic offset (for the future pointer)
  8051. let dynamicOffset = dynamicWriter.length;
  8052. // Encode the dynamic value into the dynamicWriter
  8053. coder.encode(dynamicWriter, value);
  8054. // Prepare to populate the correct offset once we are done
  8055. let updateFunc = staticWriter.writeUpdatableValue();
  8056. updateFuncs.push((baseOffset) => {
  8057. updateFunc(baseOffset + dynamicOffset);
  8058. });
  8059. }
  8060. else {
  8061. coder.encode(staticWriter, value);
  8062. }
  8063. });
  8064. // Backfill all the dynamic offsets, now that we know the static length
  8065. updateFuncs.forEach((func) => { func(staticWriter.length); });
  8066. let length = writer.appendWriter(staticWriter);
  8067. length += writer.appendWriter(dynamicWriter);
  8068. return length;
  8069. }
  8070. /**
  8071. * @_ignore
  8072. */
  8073. function unpack(reader, coders) {
  8074. let values = [];
  8075. let keys = [];
  8076. // A reader anchored to this base
  8077. let baseReader = reader.subReader(0);
  8078. coders.forEach((coder) => {
  8079. let value = null;
  8080. if (coder.dynamic) {
  8081. let offset = reader.readIndex();
  8082. let offsetReader = baseReader.subReader(offset);
  8083. try {
  8084. value = coder.decode(offsetReader);
  8085. }
  8086. catch (error) {
  8087. // Cannot recover from this
  8088. if (isError(error, "BUFFER_OVERRUN")) {
  8089. throw error;
  8090. }
  8091. value = error;
  8092. value.baseType = coder.name;
  8093. value.name = coder.localName;
  8094. value.type = coder.type;
  8095. }
  8096. }
  8097. else {
  8098. try {
  8099. value = coder.decode(reader);
  8100. }
  8101. catch (error) {
  8102. // Cannot recover from this
  8103. if (isError(error, "BUFFER_OVERRUN")) {
  8104. throw error;
  8105. }
  8106. value = error;
  8107. value.baseType = coder.name;
  8108. value.name = coder.localName;
  8109. value.type = coder.type;
  8110. }
  8111. }
  8112. if (value == undefined) {
  8113. throw new Error("investigate");
  8114. }
  8115. values.push(value);
  8116. keys.push(coder.localName || null);
  8117. });
  8118. return Result.fromItems(values, keys);
  8119. }
  8120. /**
  8121. * @_ignore
  8122. */
  8123. class ArrayCoder extends Coder {
  8124. coder;
  8125. length;
  8126. constructor(coder, length, localName) {
  8127. const type = (coder.type + "[" + (length >= 0 ? length : "") + "]");
  8128. const dynamic = (length === -1 || coder.dynamic);
  8129. super("array", type, localName, dynamic);
  8130. defineProperties(this, { coder, length });
  8131. }
  8132. defaultValue() {
  8133. // Verifies the child coder is valid (even if the array is dynamic or 0-length)
  8134. const defaultChild = this.coder.defaultValue();
  8135. const result = [];
  8136. for (let i = 0; i < this.length; i++) {
  8137. result.push(defaultChild);
  8138. }
  8139. return result;
  8140. }
  8141. encode(writer, _value) {
  8142. const value = Typed.dereference(_value, "array");
  8143. if (!Array.isArray(value)) {
  8144. this._throwError("expected array value", value);
  8145. }
  8146. let count = this.length;
  8147. if (count === -1) {
  8148. count = value.length;
  8149. writer.writeValue(value.length);
  8150. }
  8151. assertArgumentCount(value.length, count, "coder array" + (this.localName ? (" " + this.localName) : ""));
  8152. let coders = [];
  8153. for (let i = 0; i < value.length; i++) {
  8154. coders.push(this.coder);
  8155. }
  8156. return pack(writer, coders, value);
  8157. }
  8158. decode(reader) {
  8159. let count = this.length;
  8160. if (count === -1) {
  8161. count = reader.readIndex();
  8162. // Check that there is *roughly* enough data to ensure
  8163. // stray random data is not being read as a length. Each
  8164. // slot requires at least 32 bytes for their value (or 32
  8165. // bytes as a link to the data). This could use a much
  8166. // tighter bound, but we are erroring on the side of safety.
  8167. assert(count * WordSize <= reader.dataLength, "insufficient data length", "BUFFER_OVERRUN", { buffer: reader.bytes, offset: count * WordSize, length: reader.dataLength });
  8168. }
  8169. let coders = [];
  8170. for (let i = 0; i < count; i++) {
  8171. coders.push(new AnonymousCoder(this.coder));
  8172. }
  8173. return unpack(reader, coders);
  8174. }
  8175. }
  8176. /**
  8177. * @_ignore
  8178. */
  8179. class BooleanCoder extends Coder {
  8180. constructor(localName) {
  8181. super("bool", "bool", localName, false);
  8182. }
  8183. defaultValue() {
  8184. return false;
  8185. }
  8186. encode(writer, _value) {
  8187. const value = Typed.dereference(_value, "bool");
  8188. return writer.writeValue(value ? 1 : 0);
  8189. }
  8190. decode(reader) {
  8191. return !!reader.readValue();
  8192. }
  8193. }
  8194. /**
  8195. * @_ignore
  8196. */
  8197. class DynamicBytesCoder extends Coder {
  8198. constructor(type, localName) {
  8199. super(type, type, localName, true);
  8200. }
  8201. defaultValue() {
  8202. return "0x";
  8203. }
  8204. encode(writer, value) {
  8205. value = getBytesCopy(value);
  8206. let length = writer.writeValue(value.length);
  8207. length += writer.writeBytes(value);
  8208. return length;
  8209. }
  8210. decode(reader) {
  8211. return reader.readBytes(reader.readIndex(), true);
  8212. }
  8213. }
  8214. /**
  8215. * @_ignore
  8216. */
  8217. class BytesCoder extends DynamicBytesCoder {
  8218. constructor(localName) {
  8219. super("bytes", localName);
  8220. }
  8221. decode(reader) {
  8222. return hexlify(super.decode(reader));
  8223. }
  8224. }
  8225. /**
  8226. * @_ignore
  8227. */
  8228. class FixedBytesCoder extends Coder {
  8229. size;
  8230. constructor(size, localName) {
  8231. let name = "bytes" + String(size);
  8232. super(name, name, localName, false);
  8233. defineProperties(this, { size }, { size: "number" });
  8234. }
  8235. defaultValue() {
  8236. return ("0x0000000000000000000000000000000000000000000000000000000000000000").substring(0, 2 + this.size * 2);
  8237. }
  8238. encode(writer, _value) {
  8239. let data = getBytesCopy(Typed.dereference(_value, this.type));
  8240. if (data.length !== this.size) {
  8241. this._throwError("incorrect data length", _value);
  8242. }
  8243. return writer.writeBytes(data);
  8244. }
  8245. decode(reader) {
  8246. return hexlify(reader.readBytes(this.size));
  8247. }
  8248. }
  8249. const Empty = new Uint8Array([]);
  8250. /**
  8251. * @_ignore
  8252. */
  8253. class NullCoder extends Coder {
  8254. constructor(localName) {
  8255. super("null", "", localName, false);
  8256. }
  8257. defaultValue() {
  8258. return null;
  8259. }
  8260. encode(writer, value) {
  8261. if (value != null) {
  8262. this._throwError("not null", value);
  8263. }
  8264. return writer.writeBytes(Empty);
  8265. }
  8266. decode(reader) {
  8267. reader.readBytes(0);
  8268. return null;
  8269. }
  8270. }
  8271. const BN_0$5 = BigInt(0);
  8272. const BN_1$2 = BigInt(1);
  8273. const BN_MAX_UINT256$1 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
  8274. /**
  8275. * @_ignore
  8276. */
  8277. class NumberCoder extends Coder {
  8278. size;
  8279. signed;
  8280. constructor(size, signed, localName) {
  8281. const name = ((signed ? "int" : "uint") + (size * 8));
  8282. super(name, name, localName, false);
  8283. defineProperties(this, { size, signed }, { size: "number", signed: "boolean" });
  8284. }
  8285. defaultValue() {
  8286. return 0;
  8287. }
  8288. encode(writer, _value) {
  8289. let value = getBigInt(Typed.dereference(_value, this.type));
  8290. // Check bounds are safe for encoding
  8291. let maxUintValue = mask(BN_MAX_UINT256$1, WordSize * 8);
  8292. if (this.signed) {
  8293. let bounds = mask(maxUintValue, (this.size * 8) - 1);
  8294. if (value > bounds || value < -(bounds + BN_1$2)) {
  8295. this._throwError("value out-of-bounds", _value);
  8296. }
  8297. value = toTwos(value, 8 * WordSize);
  8298. }
  8299. else if (value < BN_0$5 || value > mask(maxUintValue, this.size * 8)) {
  8300. this._throwError("value out-of-bounds", _value);
  8301. }
  8302. return writer.writeValue(value);
  8303. }
  8304. decode(reader) {
  8305. let value = mask(reader.readValue(), this.size * 8);
  8306. if (this.signed) {
  8307. value = fromTwos(value, this.size * 8);
  8308. }
  8309. return value;
  8310. }
  8311. }
  8312. /**
  8313. * @_ignore
  8314. */
  8315. class StringCoder extends DynamicBytesCoder {
  8316. constructor(localName) {
  8317. super("string", localName);
  8318. }
  8319. defaultValue() {
  8320. return "";
  8321. }
  8322. encode(writer, _value) {
  8323. return super.encode(writer, toUtf8Bytes(Typed.dereference(_value, "string")));
  8324. }
  8325. decode(reader) {
  8326. return toUtf8String(super.decode(reader));
  8327. }
  8328. }
  8329. /**
  8330. * @_ignore
  8331. */
  8332. class TupleCoder extends Coder {
  8333. coders;
  8334. constructor(coders, localName) {
  8335. let dynamic = false;
  8336. const types = [];
  8337. coders.forEach((coder) => {
  8338. if (coder.dynamic) {
  8339. dynamic = true;
  8340. }
  8341. types.push(coder.type);
  8342. });
  8343. const type = ("tuple(" + types.join(",") + ")");
  8344. super("tuple", type, localName, dynamic);
  8345. defineProperties(this, { coders: Object.freeze(coders.slice()) });
  8346. }
  8347. defaultValue() {
  8348. const values = [];
  8349. this.coders.forEach((coder) => {
  8350. values.push(coder.defaultValue());
  8351. });
  8352. // We only output named properties for uniquely named coders
  8353. const uniqueNames = this.coders.reduce((accum, coder) => {
  8354. const name = coder.localName;
  8355. if (name) {
  8356. if (!accum[name]) {
  8357. accum[name] = 0;
  8358. }
  8359. accum[name]++;
  8360. }
  8361. return accum;
  8362. }, {});
  8363. // Add named values
  8364. this.coders.forEach((coder, index) => {
  8365. let name = coder.localName;
  8366. if (!name || uniqueNames[name] !== 1) {
  8367. return;
  8368. }
  8369. if (name === "length") {
  8370. name = "_length";
  8371. }
  8372. if (values[name] != null) {
  8373. return;
  8374. }
  8375. values[name] = values[index];
  8376. });
  8377. return Object.freeze(values);
  8378. }
  8379. encode(writer, _value) {
  8380. const value = Typed.dereference(_value, "tuple");
  8381. return pack(writer, this.coders, value);
  8382. }
  8383. decode(reader) {
  8384. return unpack(reader, this.coders);
  8385. }
  8386. }
  8387. /**
  8388. * A simple hashing function which operates on UTF-8 strings to
  8389. * compute an 32-byte identifier.
  8390. *
  8391. * This simply computes the [UTF-8 bytes](toUtf8Bytes) and computes
  8392. * the [[keccak256]].
  8393. *
  8394. * @example:
  8395. * id("hello world")
  8396. * //_result:
  8397. */
  8398. function id(value) {
  8399. return keccak256(toUtf8Bytes(value));
  8400. }
  8401. // created 2023-09-25T01:01:55.148Z
  8402. // compressed base64-encoded blob for include-ens data
  8403. // source: https://github.com/adraffy/ens-normalize.js/blob/main/src/make.js
  8404. // see: https://github.com/adraffy/ens-normalize.js#security
  8405. // SHA-256: 0565ed049b9cf1614bb9e11ba7d8ac6a6fb96c893253d890f7e2b2884b9ded32
  8406. 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';
  8407. const FENCED = new Map([[8217,"apostrophe"],[8260,"fraction slash"],[12539,"middle dot"]]);
  8408. const NSM_MAX = 4;
  8409. function decode_arithmetic(bytes) {
  8410. let pos = 0;
  8411. function u16() { return (bytes[pos++] << 8) | bytes[pos++]; }
  8412. // decode the frequency table
  8413. let symbol_count = u16();
  8414. let total = 1;
  8415. let acc = [0, 1]; // first symbol has frequency 1
  8416. for (let i = 1; i < symbol_count; i++) {
  8417. acc.push(total += u16());
  8418. }
  8419. // skip the sized-payload that the last 3 symbols index into
  8420. let skip = u16();
  8421. let pos_payload = pos;
  8422. pos += skip;
  8423. let read_width = 0;
  8424. let read_buffer = 0;
  8425. function read_bit() {
  8426. if (read_width == 0) {
  8427. // this will read beyond end of buffer
  8428. // but (undefined|0) => zero pad
  8429. read_buffer = (read_buffer << 8) | bytes[pos++];
  8430. read_width = 8;
  8431. }
  8432. return (read_buffer >> --read_width) & 1;
  8433. }
  8434. const N = 31;
  8435. const FULL = 2**N;
  8436. const HALF = FULL >>> 1;
  8437. const QRTR = HALF >> 1;
  8438. const MASK = FULL - 1;
  8439. // fill register
  8440. let register = 0;
  8441. for (let i = 0; i < N; i++) register = (register << 1) | read_bit();
  8442. let symbols = [];
  8443. let low = 0;
  8444. let range = FULL; // treat like a float
  8445. while (true) {
  8446. let value = Math.floor((((register - low + 1) * total) - 1) / range);
  8447. let start = 0;
  8448. let end = symbol_count;
  8449. while (end - start > 1) { // binary search
  8450. let mid = (start + end) >>> 1;
  8451. if (value < acc[mid]) {
  8452. end = mid;
  8453. } else {
  8454. start = mid;
  8455. }
  8456. }
  8457. if (start == 0) break; // first symbol is end mark
  8458. symbols.push(start);
  8459. let a = low + Math.floor(range * acc[start] / total);
  8460. let b = low + Math.floor(range * acc[start+1] / total) - 1;
  8461. while (((a ^ b) & HALF) == 0) {
  8462. register = (register << 1) & MASK | read_bit();
  8463. a = (a << 1) & MASK;
  8464. b = (b << 1) & MASK | 1;
  8465. }
  8466. while (a & ~b & QRTR) {
  8467. register = (register & HALF) | ((register << 1) & (MASK >>> 1)) | read_bit();
  8468. a = (a << 1) ^ HALF;
  8469. b = ((b ^ HALF) << 1) | HALF | 1;
  8470. }
  8471. low = a;
  8472. range = 1 + b - a;
  8473. }
  8474. let offset = symbol_count - 4;
  8475. return symbols.map(x => { // index into payload
  8476. switch (x - offset) {
  8477. case 3: return offset + 0x10100 + ((bytes[pos_payload++] << 16) | (bytes[pos_payload++] << 8) | bytes[pos_payload++]);
  8478. case 2: return offset + 0x100 + ((bytes[pos_payload++] << 8) | bytes[pos_payload++]);
  8479. case 1: return offset + bytes[pos_payload++];
  8480. default: return x - 1;
  8481. }
  8482. });
  8483. }
  8484. // returns an iterator which returns the next symbol
  8485. function read_payload(v) {
  8486. let pos = 0;
  8487. return () => v[pos++];
  8488. }
  8489. function read_compressed_payload(s) {
  8490. return read_payload(decode_arithmetic(unsafe_atob(s)));
  8491. }
  8492. // unsafe in the sense:
  8493. // expected well-formed Base64 w/o padding
  8494. // 20220922: added for https://github.com/adraffy/ens-normalize.js/issues/4
  8495. function unsafe_atob(s) {
  8496. let lookup = [];
  8497. [...'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'].forEach((c, i) => lookup[c.charCodeAt(0)] = i);
  8498. let n = s.length;
  8499. let ret = new Uint8Array((6 * n) >> 3);
  8500. for (let i = 0, pos = 0, width = 0, carry = 0; i < n; i++) {
  8501. carry = (carry << 6) | lookup[s.charCodeAt(i)];
  8502. width += 6;
  8503. if (width >= 8) {
  8504. ret[pos++] = (carry >> (width -= 8));
  8505. }
  8506. }
  8507. return ret;
  8508. }
  8509. // eg. [0,1,2,3...] => [0,-1,1,-2,...]
  8510. function signed(i) {
  8511. return (i & 1) ? (~i >> 1) : (i >> 1);
  8512. }
  8513. function read_deltas(n, next) {
  8514. let v = Array(n);
  8515. for (let i = 0, x = 0; i < n; i++) v[i] = x += signed(next());
  8516. return v;
  8517. }
  8518. // [123][5] => [0 3] [1 1] [0 0]
  8519. function read_sorted(next, prev = 0) {
  8520. let ret = [];
  8521. while (true) {
  8522. let x = next();
  8523. let n = next();
  8524. if (!n) break;
  8525. prev += x;
  8526. for (let i = 0; i < n; i++) {
  8527. ret.push(prev + i);
  8528. }
  8529. prev += n + 1;
  8530. }
  8531. return ret;
  8532. }
  8533. function read_sorted_arrays(next) {
  8534. return read_array_while(() => {
  8535. let v = read_sorted(next);
  8536. if (v.length) return v;
  8537. });
  8538. }
  8539. // returns map of x => ys
  8540. function read_mapped(next) {
  8541. let ret = [];
  8542. while (true) {
  8543. let w = next();
  8544. if (w == 0) break;
  8545. ret.push(read_linear_table(w, next));
  8546. }
  8547. while (true) {
  8548. let w = next() - 1;
  8549. if (w < 0) break;
  8550. ret.push(read_replacement_table(w, next));
  8551. }
  8552. return ret.flat();
  8553. }
  8554. // read until next is falsy
  8555. // return array of read values
  8556. function read_array_while(next) {
  8557. let v = [];
  8558. while (true) {
  8559. let x = next(v.length);
  8560. if (!x) break;
  8561. v.push(x);
  8562. }
  8563. return v;
  8564. }
  8565. // read w columns of length n
  8566. // return as n rows of length w
  8567. function read_transposed(n, w, next) {
  8568. let m = Array(n).fill().map(() => []);
  8569. for (let i = 0; i < w; i++) {
  8570. read_deltas(n, next).forEach((x, j) => m[j].push(x));
  8571. }
  8572. return m;
  8573. }
  8574. // returns [[x, ys], [x+dx, ys+dy], [x+2*dx, ys+2*dy], ...]
  8575. // where dx/dy = steps, n = run size, w = length of y
  8576. function read_linear_table(w, next) {
  8577. let dx = 1 + next();
  8578. let dy = next();
  8579. let vN = read_array_while(next);
  8580. let m = read_transposed(vN.length, 1+w, next);
  8581. return m.flatMap((v, i) => {
  8582. let [x, ...ys] = v;
  8583. return Array(vN[i]).fill().map((_, j) => {
  8584. let j_dy = j * dy;
  8585. return [x + j * dx, ys.map(y => y + j_dy)];
  8586. });
  8587. });
  8588. }
  8589. // return [[x, ys...], ...]
  8590. // where w = length of y
  8591. function read_replacement_table(w, next) {
  8592. let n = 1 + next();
  8593. let m = read_transposed(n, 1+w, next);
  8594. return m.map(v => [v[0], v.slice(1)]);
  8595. }
  8596. function read_trie(next) {
  8597. let ret = [];
  8598. let sorted = read_sorted(next);
  8599. expand(decode([]), []);
  8600. return ret; // not sorted
  8601. function decode(Q) { // characters that lead into this node
  8602. let S = next(); // state: valid, save, check
  8603. let B = read_array_while(() => { // buckets leading to new nodes
  8604. let cps = read_sorted(next).map(i => sorted[i]);
  8605. if (cps.length) return decode(cps);
  8606. });
  8607. return {S, B, Q};
  8608. }
  8609. function expand({S, B}, cps, saved) {
  8610. if (S & 4 && saved === cps[cps.length-1]) return;
  8611. if (S & 2) saved = cps[cps.length-1];
  8612. if (S & 1) ret.push(cps);
  8613. for (let br of B) {
  8614. for (let cp of br.Q) {
  8615. expand(br, [...cps, cp], saved);
  8616. }
  8617. }
  8618. }
  8619. }
  8620. function hex_cp(cp) {
  8621. return cp.toString(16).toUpperCase().padStart(2, '0');
  8622. }
  8623. function quote_cp(cp) {
  8624. return `{${hex_cp(cp)}}`; // raffy convention: like "\u{X}" w/o the "\u"
  8625. }
  8626. /*
  8627. export function explode_cp(s) {
  8628. return [...s].map(c => c.codePointAt(0));
  8629. }
  8630. */
  8631. function explode_cp(s) { // this is about 2x faster
  8632. let cps = [];
  8633. for (let pos = 0, len = s.length; pos < len; ) {
  8634. let cp = s.codePointAt(pos);
  8635. pos += cp < 0x10000 ? 1 : 2;
  8636. cps.push(cp);
  8637. }
  8638. return cps;
  8639. }
  8640. function str_from_cps(cps) {
  8641. const chunk = 4096;
  8642. let len = cps.length;
  8643. if (len < chunk) return String.fromCodePoint(...cps);
  8644. let buf = [];
  8645. for (let i = 0; i < len; ) {
  8646. buf.push(String.fromCodePoint(...cps.slice(i, i += chunk)));
  8647. }
  8648. return buf.join('');
  8649. }
  8650. function compare_arrays(a, b) {
  8651. let n = a.length;
  8652. let c = n - b.length;
  8653. for (let i = 0; c == 0 && i < n; i++) c = a[i] - b[i];
  8654. return c;
  8655. }
  8656. // created 2023-09-25T01:01:55.148Z
  8657. // compressed base64-encoded blob for include-nf data
  8658. // source: https://github.com/adraffy/ens-normalize.js/blob/main/src/make.js
  8659. // see: https://github.com/adraffy/ens-normalize.js#security
  8660. // SHA-256: a974b6f8541fc29d919bc85118af0a44015851fab5343f8679cb31be2bdb209e
  8661. 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';
  8662. // https://unicode.org/reports/tr15/
  8663. // for reference implementation
  8664. // see: /derive/nf.js
  8665. // algorithmic hangul
  8666. // https://www.unicode.org/versions/Unicode15.0.0/ch03.pdf (page 144)
  8667. const S0 = 0xAC00;
  8668. const L0 = 0x1100;
  8669. const V0 = 0x1161;
  8670. const T0 = 0x11A7;
  8671. const L_COUNT = 19;
  8672. const V_COUNT = 21;
  8673. const T_COUNT = 28;
  8674. const N_COUNT = V_COUNT * T_COUNT;
  8675. const S_COUNT = L_COUNT * N_COUNT;
  8676. const S1 = S0 + S_COUNT;
  8677. const L1 = L0 + L_COUNT;
  8678. const V1 = V0 + V_COUNT;
  8679. const T1$1 = T0 + T_COUNT;
  8680. function unpack_cc(packed) {
  8681. return (packed >> 24) & 0xFF;
  8682. }
  8683. function unpack_cp(packed) {
  8684. return packed & 0xFFFFFF;
  8685. }
  8686. let SHIFTED_RANK, EXCLUSIONS, DECOMP, RECOMP;
  8687. function init$1() {
  8688. //console.time('nf');
  8689. let r = read_compressed_payload(COMPRESSED);
  8690. SHIFTED_RANK = new Map(read_sorted_arrays(r).flatMap((v, i) => v.map(x => [x, (i+1) << 24]))); // pre-shifted
  8691. EXCLUSIONS = new Set(read_sorted(r));
  8692. DECOMP = new Map();
  8693. RECOMP = new Map();
  8694. for (let [cp, cps] of read_mapped(r)) {
  8695. if (!EXCLUSIONS.has(cp) && cps.length == 2) {
  8696. let [a, b] = cps;
  8697. let bucket = RECOMP.get(a);
  8698. if (!bucket) {
  8699. bucket = new Map();
  8700. RECOMP.set(a, bucket);
  8701. }
  8702. bucket.set(b, cp);
  8703. }
  8704. DECOMP.set(cp, cps.reverse()); // stored reversed
  8705. }
  8706. //console.timeEnd('nf');
  8707. // 20230905: 11ms
  8708. }
  8709. function is_hangul(cp) {
  8710. return cp >= S0 && cp < S1;
  8711. }
  8712. function compose_pair(a, b) {
  8713. if (a >= L0 && a < L1 && b >= V0 && b < V1) {
  8714. return S0 + (a - L0) * N_COUNT + (b - V0) * T_COUNT;
  8715. } else if (is_hangul(a) && b > T0 && b < T1$1 && (a - S0) % T_COUNT == 0) {
  8716. return a + (b - T0);
  8717. } else {
  8718. let recomp = RECOMP.get(a);
  8719. if (recomp) {
  8720. recomp = recomp.get(b);
  8721. if (recomp) {
  8722. return recomp;
  8723. }
  8724. }
  8725. return -1;
  8726. }
  8727. }
  8728. function decomposed(cps) {
  8729. if (!SHIFTED_RANK) init$1();
  8730. let ret = [];
  8731. let buf = [];
  8732. let check_order = false;
  8733. function add(cp) {
  8734. let cc = SHIFTED_RANK.get(cp);
  8735. if (cc) {
  8736. check_order = true;
  8737. cp |= cc;
  8738. }
  8739. ret.push(cp);
  8740. }
  8741. for (let cp of cps) {
  8742. while (true) {
  8743. if (cp < 0x80) {
  8744. ret.push(cp);
  8745. } else if (is_hangul(cp)) {
  8746. let s_index = cp - S0;
  8747. let l_index = s_index / N_COUNT | 0;
  8748. let v_index = (s_index % N_COUNT) / T_COUNT | 0;
  8749. let t_index = s_index % T_COUNT;
  8750. add(L0 + l_index);
  8751. add(V0 + v_index);
  8752. if (t_index > 0) add(T0 + t_index);
  8753. } else {
  8754. let mapped = DECOMP.get(cp);
  8755. if (mapped) {
  8756. buf.push(...mapped);
  8757. } else {
  8758. add(cp);
  8759. }
  8760. }
  8761. if (!buf.length) break;
  8762. cp = buf.pop();
  8763. }
  8764. }
  8765. if (check_order && ret.length > 1) {
  8766. let prev_cc = unpack_cc(ret[0]);
  8767. for (let i = 1; i < ret.length; i++) {
  8768. let cc = unpack_cc(ret[i]);
  8769. if (cc == 0 || prev_cc <= cc) {
  8770. prev_cc = cc;
  8771. continue;
  8772. }
  8773. let j = i-1;
  8774. while (true) {
  8775. let tmp = ret[j+1];
  8776. ret[j+1] = ret[j];
  8777. ret[j] = tmp;
  8778. if (!j) break;
  8779. prev_cc = unpack_cc(ret[--j]);
  8780. if (prev_cc <= cc) break;
  8781. }
  8782. prev_cc = unpack_cc(ret[i]);
  8783. }
  8784. }
  8785. return ret;
  8786. }
  8787. function composed_from_decomposed(v) {
  8788. let ret = [];
  8789. let stack = [];
  8790. let prev_cp = -1;
  8791. let prev_cc = 0;
  8792. for (let packed of v) {
  8793. let cc = unpack_cc(packed);
  8794. let cp = unpack_cp(packed);
  8795. if (prev_cp == -1) {
  8796. if (cc == 0) {
  8797. prev_cp = cp;
  8798. } else {
  8799. ret.push(cp);
  8800. }
  8801. } else if (prev_cc > 0 && prev_cc >= cc) {
  8802. if (cc == 0) {
  8803. ret.push(prev_cp, ...stack);
  8804. stack.length = 0;
  8805. prev_cp = cp;
  8806. } else {
  8807. stack.push(cp);
  8808. }
  8809. prev_cc = cc;
  8810. } else {
  8811. let composed = compose_pair(prev_cp, cp);
  8812. if (composed >= 0) {
  8813. prev_cp = composed;
  8814. } else if (prev_cc == 0 && cc == 0) {
  8815. ret.push(prev_cp);
  8816. prev_cp = cp;
  8817. } else {
  8818. stack.push(cp);
  8819. prev_cc = cc;
  8820. }
  8821. }
  8822. }
  8823. if (prev_cp >= 0) {
  8824. ret.push(prev_cp, ...stack);
  8825. }
  8826. return ret;
  8827. }
  8828. // note: cps can be iterable
  8829. function nfd(cps) {
  8830. return decomposed(cps).map(unpack_cp);
  8831. }
  8832. function nfc(cps) {
  8833. return composed_from_decomposed(decomposed(cps));
  8834. }
  8835. const HYPHEN = 0x2D;
  8836. const STOP_CH = '.';
  8837. const FE0F = 0xFE0F;
  8838. const UNIQUE_PH = 1;
  8839. // 20230913: replace [...v] with Array_from(v) to avoid large spreads
  8840. const Array_from = x => Array.from(x); // Array.from.bind(Array);
  8841. function group_has_cp(g, cp) {
  8842. // 20230913: keep primary and secondary distinct instead of creating valid union
  8843. return g.P.has(cp) || g.Q.has(cp);
  8844. }
  8845. class Emoji extends Array {
  8846. get is_emoji() { return true; } // free tagging system
  8847. }
  8848. let MAPPED, IGNORED, CM, NSM, ESCAPE, GROUPS, WHOLE_VALID, WHOLE_MAP, VALID, EMOJI_LIST, EMOJI_ROOT;
  8849. function init() {
  8850. if (MAPPED) return;
  8851. let r = read_compressed_payload(COMPRESSED$1);
  8852. const read_sorted_array = () => read_sorted(r);
  8853. const read_sorted_set = () => new Set(read_sorted_array());
  8854. const set_add_many = (set, v) => v.forEach(x => set.add(x));
  8855. MAPPED = new Map(read_mapped(r));
  8856. IGNORED = read_sorted_set(); // ignored characters are not valid, so just read raw codepoints
  8857. /*
  8858. // direct include from payload is smaller than the decompression code
  8859. const FENCED = new Map(read_array_while(() => {
  8860. let cp = r();
  8861. if (cp) return [cp, read_str(r())];
  8862. }));
  8863. */
  8864. // 20230217: we still need all CM for proper error formatting
  8865. // but norm only needs NSM subset that are potentially-valid
  8866. CM = read_sorted_array();
  8867. NSM = new Set(read_sorted_array().map(i => CM[i]));
  8868. CM = new Set(CM);
  8869. ESCAPE = read_sorted_set(); // characters that should not be printed
  8870. read_sorted_set(); // only needed to illustrate ens_tokenize() transformations
  8871. let chunks = read_sorted_arrays(r);
  8872. let unrestricted = r();
  8873. //const read_chunked = () => new Set(read_sorted_array().flatMap(i => chunks[i]).concat(read_sorted_array()));
  8874. const read_chunked = () => {
  8875. // 20230921: build set in parts, 2x faster
  8876. let set = new Set();
  8877. read_sorted_array().forEach(i => set_add_many(set, chunks[i]));
  8878. set_add_many(set, read_sorted_array());
  8879. return set;
  8880. };
  8881. GROUPS = read_array_while(i => {
  8882. // minifier property mangling seems unsafe
  8883. // so these are manually renamed to single chars
  8884. let N = read_array_while(r).map(x => x+0x60);
  8885. if (N.length) {
  8886. let R = i >= unrestricted; // unrestricted then restricted
  8887. N[0] -= 32; // capitalize
  8888. N = str_from_cps(N);
  8889. if (R) N=`Restricted[${N}]`;
  8890. let P = read_chunked(); // primary
  8891. let Q = read_chunked(); // secondary
  8892. let M = !r(); // not-whitelisted, check for NSM
  8893. // *** this code currently isn't needed ***
  8894. /*
  8895. let V = [...P, ...Q].sort((a, b) => a-b); // derive: sorted valid
  8896. let M = r()-1; // number of combining mark
  8897. if (M < 0) { // whitelisted
  8898. M = new Map(read_array_while(() => {
  8899. let i = r();
  8900. if (i) return [V[i-1], read_array_while(() => {
  8901. let v = read_array_while(r);
  8902. if (v.length) return v.map(x => x-1);
  8903. })];
  8904. }));
  8905. }*/
  8906. return {N, P, Q, M, R};
  8907. }
  8908. });
  8909. // decode compressed wholes
  8910. WHOLE_VALID = read_sorted_set();
  8911. WHOLE_MAP = new Map();
  8912. let wholes = read_sorted_array().concat(Array_from(WHOLE_VALID)).sort((a, b) => a-b); // must be sorted
  8913. wholes.forEach((cp, i) => {
  8914. let d = r();
  8915. let w = wholes[i] = d ? wholes[i-d] : {V: [], M: new Map()};
  8916. w.V.push(cp); // add to member set
  8917. if (!WHOLE_VALID.has(cp)) {
  8918. WHOLE_MAP.set(cp, w); // register with whole map
  8919. }
  8920. });
  8921. // compute confusable-extent complements
  8922. // usage: WHOLE_MAP.get(cp).M.get(cp) = complement set
  8923. for (let {V, M} of new Set(WHOLE_MAP.values())) {
  8924. // connect all groups that have each whole character
  8925. let recs = [];
  8926. for (let cp of V) {
  8927. let gs = GROUPS.filter(g => group_has_cp(g, cp));
  8928. let rec = recs.find(({G}) => gs.some(g => G.has(g)));
  8929. if (!rec) {
  8930. rec = {G: new Set(), V: []};
  8931. recs.push(rec);
  8932. }
  8933. rec.V.push(cp);
  8934. set_add_many(rec.G, gs);
  8935. }
  8936. // per character cache groups which are not a member of the extent
  8937. let union = recs.flatMap(x => Array_from(x.G)); // all of the groups used by this whole
  8938. for (let {G, V} of recs) {
  8939. let complement = new Set(union.filter(g => !G.has(g))); // groups not covered by the extent
  8940. for (let cp of V) {
  8941. M.set(cp, complement); // this is the same reference
  8942. }
  8943. }
  8944. }
  8945. // compute valid set
  8946. // 20230924: VALID was union but can be re-used
  8947. VALID = new Set(); // exists in 1+ groups
  8948. let multi = new Set(); // exists in 2+ groups
  8949. const add_to_union = cp => VALID.has(cp) ? multi.add(cp) : VALID.add(cp);
  8950. for (let g of GROUPS) {
  8951. for (let cp of g.P) add_to_union(cp);
  8952. for (let cp of g.Q) add_to_union(cp);
  8953. }
  8954. // dual purpose WHOLE_MAP: return placeholder if unique non-confusable
  8955. for (let cp of VALID) {
  8956. if (!WHOLE_MAP.has(cp) && !multi.has(cp)) {
  8957. WHOLE_MAP.set(cp, UNIQUE_PH);
  8958. }
  8959. }
  8960. // add all decomposed parts
  8961. // see derive: "Valid is Closed (via Brute-force)"
  8962. set_add_many(VALID, nfd(VALID));
  8963. // decode emoji
  8964. // 20230719: emoji are now fully-expanded to avoid quirk logic
  8965. EMOJI_LIST = read_trie(r).map(v => Emoji.from(v)).sort(compare_arrays);
  8966. EMOJI_ROOT = new Map(); // this has approx 7K nodes (2+ per emoji)
  8967. for (let cps of EMOJI_LIST) {
  8968. // 20230719: change to *slightly* stricter algorithm which disallows
  8969. // insertion of misplaced FE0F in emoji sequences (matching ENSIP-15)
  8970. // example: beautified [A B] (eg. flag emoji)
  8971. // before: allow: [A FE0F B], error: [A FE0F FE0F B]
  8972. // after: error: both
  8973. // note: this code now matches ENSNormalize.{cs,java} logic
  8974. let prev = [EMOJI_ROOT];
  8975. for (let cp of cps) {
  8976. let next = prev.map(node => {
  8977. let child = node.get(cp);
  8978. if (!child) {
  8979. // should this be object?
  8980. // (most have 1-2 items, few have many)
  8981. // 20230719: no, v8 default map is 4?
  8982. child = new Map();
  8983. node.set(cp, child);
  8984. }
  8985. return child;
  8986. });
  8987. if (cp === FE0F) {
  8988. prev.push(...next); // less than 20 elements
  8989. } else {
  8990. prev = next;
  8991. }
  8992. }
  8993. for (let x of prev) {
  8994. x.V = cps;
  8995. }
  8996. }
  8997. }
  8998. // if escaped: {HEX}
  8999. // else: "x" {HEX}
  9000. function quoted_cp(cp) {
  9001. return (should_escape(cp) ? '' : `${bidi_qq(safe_str_from_cps([cp]))} `) + quote_cp(cp);
  9002. }
  9003. // 20230211: some messages can be mixed-directional and result in spillover
  9004. // use 200E after a quoted string to force the remainder of a string from
  9005. // acquring the direction of the quote
  9006. // https://www.w3.org/International/questions/qa-bidi-unicode-controls#exceptions
  9007. function bidi_qq(s) {
  9008. return `"${s}"\u200E`; // strong LTR
  9009. }
  9010. function check_label_extension(cps) {
  9011. if (cps.length >= 4 && cps[2] == HYPHEN && cps[3] == HYPHEN) {
  9012. throw new Error(`invalid label extension: "${str_from_cps(cps.slice(0, 4))}"`); // this can only be ascii so cant be bidi
  9013. }
  9014. }
  9015. function check_leading_underscore(cps) {
  9016. const UNDERSCORE = 0x5F;
  9017. for (let i = cps.lastIndexOf(UNDERSCORE); i > 0; ) {
  9018. if (cps[--i] !== UNDERSCORE) {
  9019. throw new Error('underscore allowed only at start');
  9020. }
  9021. }
  9022. }
  9023. // check that a fenced cp is not leading, trailing, or touching another fenced cp
  9024. function check_fenced(cps) {
  9025. let cp = cps[0];
  9026. let prev = FENCED.get(cp);
  9027. if (prev) throw error_placement(`leading ${prev}`);
  9028. let n = cps.length;
  9029. let last = -1; // prevents trailing from throwing
  9030. for (let i = 1; i < n; i++) {
  9031. cp = cps[i];
  9032. let match = FENCED.get(cp);
  9033. if (match) {
  9034. // since cps[0] isn't fenced, cps[1] cannot throw
  9035. if (last == i) throw error_placement(`${prev} + ${match}`);
  9036. last = i + 1;
  9037. prev = match;
  9038. }
  9039. }
  9040. if (last == n) throw error_placement(`trailing ${prev}`);
  9041. }
  9042. // create a safe to print string
  9043. // invisibles are escaped
  9044. // leading cm uses placeholder
  9045. // if cps exceed max, middle truncate with ellipsis
  9046. // quoter(cp) => string, eg. 3000 => "{3000}"
  9047. // note: in html, you'd call this function then replace [<>&] with entities
  9048. function safe_str_from_cps(cps, max = Infinity, quoter = quote_cp) {
  9049. //if (Number.isInteger(cps)) cps = [cps];
  9050. //if (!Array.isArray(cps)) throw new TypeError(`expected codepoints`);
  9051. let buf = [];
  9052. if (is_combining_mark(cps[0])) buf.push('◌');
  9053. if (cps.length > max) {
  9054. max >>= 1;
  9055. cps = [...cps.slice(0, max), 0x2026, ...cps.slice(-max)];
  9056. }
  9057. let prev = 0;
  9058. let n = cps.length;
  9059. for (let i = 0; i < n; i++) {
  9060. let cp = cps[i];
  9061. if (should_escape(cp)) {
  9062. buf.push(str_from_cps(cps.slice(prev, i)));
  9063. buf.push(quoter(cp));
  9064. prev = i + 1;
  9065. }
  9066. }
  9067. buf.push(str_from_cps(cps.slice(prev, n)));
  9068. return buf.join('');
  9069. }
  9070. // note: set(s) cannot be exposed because they can be modified
  9071. // note: Object.freeze() doesn't work
  9072. function is_combining_mark(cp) {
  9073. init();
  9074. return CM.has(cp);
  9075. }
  9076. function should_escape(cp) {
  9077. init();
  9078. return ESCAPE.has(cp);
  9079. }
  9080. function ens_normalize(name) {
  9081. return flatten(split(name, nfc, filter_fe0f));
  9082. }
  9083. function split(name, nf, ef) {
  9084. if (!name) return []; // 20230719: empty name allowance
  9085. init();
  9086. let offset = 0;
  9087. // https://unicode.org/reports/tr46/#Validity_Criteria
  9088. // 4.) "The label must not contain a U+002E ( . ) FULL STOP."
  9089. return name.split(STOP_CH).map(label => {
  9090. let input = explode_cp(label);
  9091. let info = {
  9092. input,
  9093. offset, // codepoint, not substring!
  9094. };
  9095. offset += input.length + 1; // + stop
  9096. try {
  9097. // 1.) "The label must be in Unicode Normalization Form NFC"
  9098. let tokens = info.tokens = tokens_from_str(input, nf, ef);
  9099. let token_count = tokens.length;
  9100. let type;
  9101. if (!token_count) { // the label was effectively empty (could of had ignored characters)
  9102. //norm = [];
  9103. //type = 'None'; // use this instead of next match, "ASCII"
  9104. // 20230120: change to strict
  9105. // https://discuss.ens.domains/t/ens-name-normalization-2nd/14564/59
  9106. throw new Error(`empty label`);
  9107. }
  9108. let norm = info.output = tokens.flat();
  9109. check_leading_underscore(norm);
  9110. let emoji = info.emoji = token_count > 1 || tokens[0].is_emoji; // same as: tokens.some(x => x.is_emoji);
  9111. if (!emoji && norm.every(cp => cp < 0x80)) { // special case for ascii
  9112. // 20230123: matches matches WHATWG, see note 3.3
  9113. check_label_extension(norm); // only needed for ascii
  9114. // cant have fenced
  9115. // cant have cm
  9116. // cant have wholes
  9117. // see derive: "Fastpath ASCII"
  9118. type = 'ASCII';
  9119. } else {
  9120. let chars = tokens.flatMap(x => x.is_emoji ? [] : x); // all of the nfc tokens concat together
  9121. if (!chars.length) { // theres no text, just emoji
  9122. type = 'Emoji';
  9123. } else {
  9124. // 5.) "The label must not begin with a combining mark, that is: General_Category=Mark."
  9125. if (CM.has(norm[0])) throw error_placement('leading combining mark');
  9126. for (let i = 1; i < token_count; i++) { // we've already checked the first token
  9127. let cps = tokens[i];
  9128. if (!cps.is_emoji && CM.has(cps[0])) { // every text token has emoji neighbors, eg. EtEEEtEt...
  9129. // bidi_qq() not needed since emoji is LTR and cps is a CM
  9130. throw error_placement(`emoji + combining mark: "${str_from_cps(tokens[i-1])} + ${safe_str_from_cps([cps[0]])}"`);
  9131. }
  9132. }
  9133. check_fenced(norm);
  9134. let unique = Array_from(new Set(chars));
  9135. let [g] = determine_group(unique); // take the first match
  9136. // see derive: "Matching Groups have Same CM Style"
  9137. // alternative: could form a hybrid type: Latin/Japanese/...
  9138. check_group(g, chars); // need text in order
  9139. check_whole(g, unique); // only need unique text (order would be required for multiple-char confusables)
  9140. type = g.N;
  9141. // 20230121: consider exposing restricted flag
  9142. // it's simpler to just check for 'Restricted'
  9143. // or even better: type.endsWith(']')
  9144. //if (g.R) info.restricted = true;
  9145. }
  9146. }
  9147. info.type = type;
  9148. } catch (err) {
  9149. info.error = err; // use full error object
  9150. }
  9151. return info;
  9152. });
  9153. }
  9154. function check_whole(group, unique) {
  9155. let maker;
  9156. let shared = [];
  9157. for (let cp of unique) {
  9158. let whole = WHOLE_MAP.get(cp);
  9159. if (whole === UNIQUE_PH) return; // unique, non-confusable
  9160. if (whole) {
  9161. let set = whole.M.get(cp); // groups which have a character that look-like this character
  9162. maker = maker ? maker.filter(g => set.has(g)) : Array_from(set);
  9163. if (!maker.length) return; // confusable intersection is empty
  9164. } else {
  9165. shared.push(cp);
  9166. }
  9167. }
  9168. if (maker) {
  9169. // we have 1+ confusable
  9170. // check if any of the remaining groups
  9171. // contain the shared characters too
  9172. for (let g of maker) {
  9173. if (shared.every(cp => group_has_cp(g, cp))) {
  9174. throw new Error(`whole-script confusable: ${group.N}/${g.N}`);
  9175. }
  9176. }
  9177. }
  9178. }
  9179. // assumption: unique.size > 0
  9180. // returns list of matching groups
  9181. function determine_group(unique) {
  9182. let groups = GROUPS;
  9183. for (let cp of unique) {
  9184. // note: we need to dodge CM that are whitelisted
  9185. // but that code isn't currently necessary
  9186. let gs = groups.filter(g => group_has_cp(g, cp));
  9187. if (!gs.length) {
  9188. if (!GROUPS.some(g => group_has_cp(g, cp))) {
  9189. // the character was composed of valid parts
  9190. // but it's NFC form is invalid
  9191. // 20230716: change to more exact statement, see: ENSNormalize.{cs,java}
  9192. // note: this doesn't have to be a composition
  9193. // 20230720: change to full check
  9194. throw error_disallowed(cp); // this should be rare
  9195. } else {
  9196. // there is no group that contains all these characters
  9197. // throw using the highest priority group that matched
  9198. // https://www.unicode.org/reports/tr39/#mixed_script_confusables
  9199. throw error_group_member(groups[0], cp);
  9200. }
  9201. }
  9202. groups = gs;
  9203. if (gs.length == 1) break; // there is only one group left
  9204. }
  9205. // there are at least 1 group(s) with all of these characters
  9206. return groups;
  9207. }
  9208. // throw on first error
  9209. function flatten(split) {
  9210. return split.map(({input, error, output}) => {
  9211. if (error) {
  9212. // don't print label again if just a single label
  9213. let msg = error.message;
  9214. // bidi_qq() only necessary if msg is digits
  9215. throw new Error(split.length == 1 ? msg : `Invalid label ${bidi_qq(safe_str_from_cps(input, 63))}: ${msg}`);
  9216. }
  9217. return str_from_cps(output);
  9218. }).join(STOP_CH);
  9219. }
  9220. function error_disallowed(cp) {
  9221. // TODO: add cp to error?
  9222. return new Error(`disallowed character: ${quoted_cp(cp)}`);
  9223. }
  9224. function error_group_member(g, cp) {
  9225. let quoted = quoted_cp(cp);
  9226. let gg = GROUPS.find(g => g.P.has(cp)); // only check primary
  9227. if (gg) {
  9228. quoted = `${gg.N} ${quoted}`;
  9229. }
  9230. return new Error(`illegal mixture: ${g.N} + ${quoted}`);
  9231. }
  9232. function error_placement(where) {
  9233. return new Error(`illegal placement: ${where}`);
  9234. }
  9235. // assumption: cps.length > 0
  9236. // assumption: cps[0] isn't a CM
  9237. // assumption: the previous character isn't an emoji
  9238. function check_group(g, cps) {
  9239. for (let cp of cps) {
  9240. if (!group_has_cp(g, cp)) {
  9241. // for whitelisted scripts, this will throw illegal mixture on invalid cm, eg. "e{300}{300}"
  9242. // at the moment, it's unnecessary to introduce an extra error type
  9243. // until there exists a whitelisted multi-character
  9244. // eg. if (M < 0 && is_combining_mark(cp)) { ... }
  9245. // there are 3 cases:
  9246. // 1. illegal cm for wrong group => mixture error
  9247. // 2. illegal cm for same group => cm error
  9248. // requires set of whitelist cm per group:
  9249. // eg. new Set([...g.P, ...g.Q].flatMap(nfc).filter(cp => CM.has(cp)))
  9250. // 3. wrong group => mixture error
  9251. throw error_group_member(g, cp);
  9252. }
  9253. }
  9254. //if (M >= 0) { // we have a known fixed cm count
  9255. if (g.M) { // we need to check for NSM
  9256. let decomposed = nfd(cps);
  9257. for (let i = 1, e = decomposed.length; i < e; i++) { // see: assumption
  9258. // 20230210: bugfix: using cps instead of decomposed h/t Carbon225
  9259. /*
  9260. if (CM.has(decomposed[i])) {
  9261. let j = i + 1;
  9262. while (j < e && CM.has(decomposed[j])) j++;
  9263. if (j - i > M) {
  9264. throw new Error(`too many combining marks: ${g.N} ${bidi_qq(str_from_cps(decomposed.slice(i-1, j)))} (${j-i}/${M})`);
  9265. }
  9266. i = j;
  9267. }
  9268. */
  9269. // 20230217: switch to NSM counting
  9270. // https://www.unicode.org/reports/tr39/#Optional_Detection
  9271. if (NSM.has(decomposed[i])) {
  9272. let j = i + 1;
  9273. for (let cp; j < e && NSM.has(cp = decomposed[j]); j++) {
  9274. // a. Forbid sequences of the same nonspacing mark.
  9275. for (let k = i; k < j; k++) { // O(n^2) but n < 100
  9276. if (decomposed[k] == cp) {
  9277. throw new Error(`duplicate non-spacing marks: ${quoted_cp(cp)}`);
  9278. }
  9279. }
  9280. }
  9281. // parse to end so we have full nsm count
  9282. // b. Forbid sequences of more than 4 nonspacing marks (gc=Mn or gc=Me).
  9283. if (j - i > NSM_MAX) {
  9284. // note: this slice starts with a base char or spacing-mark cm
  9285. throw new Error(`excessive non-spacing marks: ${bidi_qq(safe_str_from_cps(decomposed.slice(i-1, j)))} (${j-i}/${NSM_MAX})`);
  9286. }
  9287. i = j;
  9288. }
  9289. }
  9290. }
  9291. // *** this code currently isn't needed ***
  9292. /*
  9293. let cm_whitelist = M instanceof Map;
  9294. for (let i = 0, e = cps.length; i < e; ) {
  9295. let cp = cps[i++];
  9296. let seqs = cm_whitelist && M.get(cp);
  9297. if (seqs) {
  9298. // list of codepoints that can follow
  9299. // if this exists, this will always be 1+
  9300. let j = i;
  9301. while (j < e && CM.has(cps[j])) j++;
  9302. let cms = cps.slice(i, j);
  9303. let match = seqs.find(seq => !compare_arrays(seq, cms));
  9304. if (!match) throw new Error(`disallowed combining mark sequence: "${safe_str_from_cps([cp, ...cms])}"`);
  9305. i = j;
  9306. } else if (!V.has(cp)) {
  9307. // https://www.unicode.org/reports/tr39/#mixed_script_confusables
  9308. let quoted = quoted_cp(cp);
  9309. for (let cp of cps) {
  9310. let u = UNIQUE.get(cp);
  9311. if (u && u !== g) {
  9312. // if both scripts are restricted this error is confusing
  9313. // because we don't differentiate RestrictedA from RestrictedB
  9314. if (!u.R) quoted = `${quoted} is ${u.N}`;
  9315. break;
  9316. }
  9317. }
  9318. throw new Error(`disallowed ${g.N} character: ${quoted}`);
  9319. //throw new Error(`disallowed character: ${quoted} (expected ${g.N})`);
  9320. //throw new Error(`${g.N} does not allow: ${quoted}`);
  9321. }
  9322. }
  9323. if (!cm_whitelist) {
  9324. let decomposed = nfd(cps);
  9325. for (let i = 1, e = decomposed.length; i < e; i++) { // we know it can't be cm leading
  9326. if (CM.has(decomposed[i])) {
  9327. let j = i + 1;
  9328. while (j < e && CM.has(decomposed[j])) j++;
  9329. if (j - i > M) {
  9330. throw new Error(`too many combining marks: "${str_from_cps(decomposed.slice(i-1, j))}" (${j-i}/${M})`);
  9331. }
  9332. i = j;
  9333. }
  9334. }
  9335. }
  9336. */
  9337. }
  9338. // given a list of codepoints
  9339. // returns a list of lists, where emoji are a fully-qualified (as Array subclass)
  9340. // eg. explode_cp("abc💩d") => [[61, 62, 63], Emoji[1F4A9, FE0F], [64]]
  9341. // 20230818: rename for 'process' name collision h/t Javarome
  9342. // https://github.com/adraffy/ens-normalize.js/issues/23
  9343. function tokens_from_str(input, nf, ef) {
  9344. let ret = [];
  9345. let chars = [];
  9346. input = input.slice().reverse(); // flip so we can pop
  9347. while (input.length) {
  9348. let emoji = consume_emoji_reversed(input);
  9349. if (emoji) {
  9350. if (chars.length) {
  9351. ret.push(nf(chars));
  9352. chars = [];
  9353. }
  9354. ret.push(ef(emoji));
  9355. } else {
  9356. let cp = input.pop();
  9357. if (VALID.has(cp)) {
  9358. chars.push(cp);
  9359. } else {
  9360. let cps = MAPPED.get(cp);
  9361. if (cps) {
  9362. chars.push(...cps); // less than 10 elements
  9363. } else if (!IGNORED.has(cp)) {
  9364. // 20230912: unicode 15.1 changed the order of processing such that
  9365. // disallowed parts are only rejected after NFC
  9366. // https://unicode.org/reports/tr46/#Validity_Criteria
  9367. // this doesn't impact normalization as of today
  9368. // technically, this error can be removed as the group logic will apply similar logic
  9369. // however the error type might be less clear
  9370. throw error_disallowed(cp);
  9371. }
  9372. }
  9373. }
  9374. }
  9375. if (chars.length) {
  9376. ret.push(nf(chars));
  9377. }
  9378. return ret;
  9379. }
  9380. function filter_fe0f(cps) {
  9381. return cps.filter(cp => cp != FE0F);
  9382. }
  9383. // given array of codepoints
  9384. // returns the longest valid emoji sequence (or undefined if no match)
  9385. // *MUTATES* the supplied array
  9386. // disallows interleaved ignored characters
  9387. // fills (optional) eaten array with matched codepoints
  9388. function consume_emoji_reversed(cps, eaten) {
  9389. let node = EMOJI_ROOT;
  9390. let emoji;
  9391. let pos = cps.length;
  9392. while (pos) {
  9393. node = node.get(cps[--pos]);
  9394. if (!node) break;
  9395. let {V} = node;
  9396. if (V) { // this is a valid emoji (so far)
  9397. emoji = V;
  9398. cps.length = pos; // truncate
  9399. }
  9400. }
  9401. return emoji;
  9402. }
  9403. const Zeros = new Uint8Array(32);
  9404. Zeros.fill(0);
  9405. function checkComponent(comp) {
  9406. assertArgument(comp.length !== 0, "invalid ENS name; empty component", "comp", comp);
  9407. return comp;
  9408. }
  9409. function ensNameSplit(name) {
  9410. const bytes = toUtf8Bytes(ensNormalize(name));
  9411. const comps = [];
  9412. if (name.length === 0) {
  9413. return comps;
  9414. }
  9415. let last = 0;
  9416. for (let i = 0; i < bytes.length; i++) {
  9417. const d = bytes[i];
  9418. // A separator (i.e. "."); copy this component
  9419. if (d === 0x2e) {
  9420. comps.push(checkComponent(bytes.slice(last, i)));
  9421. last = i + 1;
  9422. }
  9423. }
  9424. // There was a stray separator at the end of the name
  9425. assertArgument(last < bytes.length, "invalid ENS name; empty component", "name", name);
  9426. comps.push(checkComponent(bytes.slice(last)));
  9427. return comps;
  9428. }
  9429. /**
  9430. * Returns the ENS %%name%% normalized.
  9431. */
  9432. function ensNormalize(name) {
  9433. try {
  9434. if (name.length === 0) {
  9435. throw new Error("empty label");
  9436. }
  9437. return ens_normalize(name);
  9438. }
  9439. catch (error) {
  9440. assertArgument(false, `invalid ENS name (${error.message})`, "name", name);
  9441. }
  9442. }
  9443. /**
  9444. * Returns ``true`` if %%name%% is a valid ENS name.
  9445. */
  9446. function isValidName(name) {
  9447. try {
  9448. return (ensNameSplit(name).length !== 0);
  9449. }
  9450. catch (error) { }
  9451. return false;
  9452. }
  9453. /**
  9454. * Returns the [[link-namehash]] for %%name%%.
  9455. */
  9456. function namehash(name) {
  9457. assertArgument(typeof (name) === "string", "invalid ENS name; not a string", "name", name);
  9458. assertArgument(name.length, `invalid ENS name (empty label)`, "name", name);
  9459. let result = Zeros;
  9460. const comps = ensNameSplit(name);
  9461. while (comps.length) {
  9462. result = keccak256(concat([result, keccak256((comps.pop()))]));
  9463. }
  9464. return hexlify(result);
  9465. }
  9466. /**
  9467. * Returns the DNS encoded %%name%%.
  9468. *
  9469. * This is used for various parts of ENS name resolution, such
  9470. * as the wildcard resolution.
  9471. */
  9472. function dnsEncode(name, _maxLength) {
  9473. const length = (_maxLength != null) ? _maxLength : 63;
  9474. assertArgument(length <= 255, "DNS encoded label cannot exceed 255", "length", length);
  9475. return hexlify(concat(ensNameSplit(name).map((comp) => {
  9476. assertArgument(comp.length <= length, `label ${JSON.stringify(name)} exceeds ${length} bytes`, "name", name);
  9477. const bytes = new Uint8Array(comp.length + 1);
  9478. bytes.set(comp, 1);
  9479. bytes[0] = bytes.length - 1;
  9480. return bytes;
  9481. }))) + "00";
  9482. }
  9483. function accessSetify(addr, storageKeys) {
  9484. return {
  9485. address: getAddress(addr),
  9486. storageKeys: storageKeys.map((storageKey, index) => {
  9487. assertArgument(isHexString(storageKey, 32), "invalid slot", `storageKeys[${index}]`, storageKey);
  9488. return storageKey.toLowerCase();
  9489. })
  9490. };
  9491. }
  9492. /**
  9493. * Returns a [[AccessList]] from any ethers-supported access-list structure.
  9494. */
  9495. function accessListify(value) {
  9496. if (Array.isArray(value)) {
  9497. return value.map((set, index) => {
  9498. if (Array.isArray(set)) {
  9499. assertArgument(set.length === 2, "invalid slot set", `value[${index}]`, set);
  9500. return accessSetify(set[0], set[1]);
  9501. }
  9502. assertArgument(set != null && typeof (set) === "object", "invalid address-slot set", "value", value);
  9503. return accessSetify(set.address, set.storageKeys);
  9504. });
  9505. }
  9506. assertArgument(value != null && typeof (value) === "object", "invalid access list", "value", value);
  9507. const result = Object.keys(value).map((addr) => {
  9508. const storageKeys = value[addr].reduce((accum, storageKey) => {
  9509. accum[storageKey] = true;
  9510. return accum;
  9511. }, {});
  9512. return accessSetify(addr, Object.keys(storageKeys).sort());
  9513. });
  9514. result.sort((a, b) => (a.address.localeCompare(b.address)));
  9515. return result;
  9516. }
  9517. /**
  9518. * Returns the address for the %%key%%.
  9519. *
  9520. * The key may be any standard form of public key or a private key.
  9521. */
  9522. function computeAddress(key) {
  9523. let pubkey;
  9524. if (typeof (key) === "string") {
  9525. pubkey = SigningKey.computePublicKey(key, false);
  9526. }
  9527. else {
  9528. pubkey = key.publicKey;
  9529. }
  9530. return getAddress(keccak256("0x" + pubkey.substring(4)).substring(26));
  9531. }
  9532. /**
  9533. * Returns the recovered address for the private key that was
  9534. * used to sign %%digest%% that resulted in %%signature%%.
  9535. */
  9536. function recoverAddress(digest, signature) {
  9537. return computeAddress(SigningKey.recoverPublicKey(digest, signature));
  9538. }
  9539. const BN_0$4 = BigInt(0);
  9540. const BN_2$2 = BigInt(2);
  9541. const BN_27 = BigInt(27);
  9542. const BN_28 = BigInt(28);
  9543. const BN_35 = BigInt(35);
  9544. const BN_MAX_UINT = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
  9545. const BLOB_SIZE = 4096 * 32;
  9546. function getVersionedHash(version, hash) {
  9547. let versioned = version.toString(16);
  9548. while (versioned.length < 2) {
  9549. versioned = "0" + versioned;
  9550. }
  9551. versioned += sha256(hash).substring(4);
  9552. return "0x" + versioned;
  9553. }
  9554. function handleAddress(value) {
  9555. if (value === "0x") {
  9556. return null;
  9557. }
  9558. return getAddress(value);
  9559. }
  9560. function handleAccessList(value, param) {
  9561. try {
  9562. return accessListify(value);
  9563. }
  9564. catch (error) {
  9565. assertArgument(false, error.message, param, value);
  9566. }
  9567. }
  9568. function handleNumber(_value, param) {
  9569. if (_value === "0x") {
  9570. return 0;
  9571. }
  9572. return getNumber(_value, param);
  9573. }
  9574. function handleUint(_value, param) {
  9575. if (_value === "0x") {
  9576. return BN_0$4;
  9577. }
  9578. const value = getBigInt(_value, param);
  9579. assertArgument(value <= BN_MAX_UINT, "value exceeds uint size", param, value);
  9580. return value;
  9581. }
  9582. function formatNumber(_value, name) {
  9583. const value = getBigInt(_value, "value");
  9584. const result = toBeArray(value);
  9585. assertArgument(result.length <= 32, `value too large`, `tx.${name}`, value);
  9586. return result;
  9587. }
  9588. function formatAccessList(value) {
  9589. return accessListify(value).map((set) => [set.address, set.storageKeys]);
  9590. }
  9591. function formatHashes(value, param) {
  9592. assertArgument(Array.isArray(value), `invalid ${param}`, "value", value);
  9593. for (let i = 0; i < value.length; i++) {
  9594. assertArgument(isHexString(value[i], 32), "invalid ${ param } hash", `value[${i}]`, value[i]);
  9595. }
  9596. return value;
  9597. }
  9598. function _parseLegacy(data) {
  9599. const fields = decodeRlp(data);
  9600. assertArgument(Array.isArray(fields) && (fields.length === 9 || fields.length === 6), "invalid field count for legacy transaction", "data", data);
  9601. const tx = {
  9602. type: 0,
  9603. nonce: handleNumber(fields[0], "nonce"),
  9604. gasPrice: handleUint(fields[1], "gasPrice"),
  9605. gasLimit: handleUint(fields[2], "gasLimit"),
  9606. to: handleAddress(fields[3]),
  9607. value: handleUint(fields[4], "value"),
  9608. data: hexlify(fields[5]),
  9609. chainId: BN_0$4
  9610. };
  9611. // Legacy unsigned transaction
  9612. if (fields.length === 6) {
  9613. return tx;
  9614. }
  9615. const v = handleUint(fields[6], "v");
  9616. const r = handleUint(fields[7], "r");
  9617. const s = handleUint(fields[8], "s");
  9618. if (r === BN_0$4 && s === BN_0$4) {
  9619. // EIP-155 unsigned transaction
  9620. tx.chainId = v;
  9621. }
  9622. else {
  9623. // Compute the EIP-155 chain ID (or 0 for legacy)
  9624. let chainId = (v - BN_35) / BN_2$2;
  9625. if (chainId < BN_0$4) {
  9626. chainId = BN_0$4;
  9627. }
  9628. tx.chainId = chainId;
  9629. // Signed Legacy Transaction
  9630. assertArgument(chainId !== BN_0$4 || (v === BN_27 || v === BN_28), "non-canonical legacy v", "v", fields[6]);
  9631. tx.signature = Signature.from({
  9632. r: zeroPadValue(fields[7], 32),
  9633. s: zeroPadValue(fields[8], 32),
  9634. v
  9635. });
  9636. //tx.hash = keccak256(data);
  9637. }
  9638. return tx;
  9639. }
  9640. function _serializeLegacy(tx, sig) {
  9641. const fields = [
  9642. formatNumber(tx.nonce, "nonce"),
  9643. formatNumber(tx.gasPrice || 0, "gasPrice"),
  9644. formatNumber(tx.gasLimit, "gasLimit"),
  9645. (tx.to || "0x"),
  9646. formatNumber(tx.value, "value"),
  9647. tx.data,
  9648. ];
  9649. let chainId = BN_0$4;
  9650. if (tx.chainId != BN_0$4) {
  9651. // A chainId was provided; if non-zero we'll use EIP-155
  9652. chainId = getBigInt(tx.chainId, "tx.chainId");
  9653. // We have a chainId in the tx and an EIP-155 v in the signature,
  9654. // make sure they agree with each other
  9655. assertArgument(!sig || sig.networkV == null || sig.legacyChainId === chainId, "tx.chainId/sig.v mismatch", "sig", sig);
  9656. }
  9657. else if (tx.signature) {
  9658. // No explicit chainId, but EIP-155 have a derived implicit chainId
  9659. const legacy = tx.signature.legacyChainId;
  9660. if (legacy != null) {
  9661. chainId = legacy;
  9662. }
  9663. }
  9664. // Requesting an unsigned transaction
  9665. if (!sig) {
  9666. // We have an EIP-155 transaction (chainId was specified and non-zero)
  9667. if (chainId !== BN_0$4) {
  9668. fields.push(toBeArray(chainId));
  9669. fields.push("0x");
  9670. fields.push("0x");
  9671. }
  9672. return encodeRlp(fields);
  9673. }
  9674. // @TODO: We should probably check that tx.signature, chainId, and sig
  9675. // match but that logic could break existing code, so schedule
  9676. // this for the next major bump.
  9677. // Compute the EIP-155 v
  9678. let v = BigInt(27 + sig.yParity);
  9679. if (chainId !== BN_0$4) {
  9680. v = Signature.getChainIdV(chainId, sig.v);
  9681. }
  9682. else if (BigInt(sig.v) !== v) {
  9683. assertArgument(false, "tx.chainId/sig.v mismatch", "sig", sig);
  9684. }
  9685. // Add the signature
  9686. fields.push(toBeArray(v));
  9687. fields.push(toBeArray(sig.r));
  9688. fields.push(toBeArray(sig.s));
  9689. return encodeRlp(fields);
  9690. }
  9691. function _parseEipSignature(tx, fields) {
  9692. let yParity;
  9693. try {
  9694. yParity = handleNumber(fields[0], "yParity");
  9695. if (yParity !== 0 && yParity !== 1) {
  9696. throw new Error("bad yParity");
  9697. }
  9698. }
  9699. catch (error) {
  9700. assertArgument(false, "invalid yParity", "yParity", fields[0]);
  9701. }
  9702. const r = zeroPadValue(fields[1], 32);
  9703. const s = zeroPadValue(fields[2], 32);
  9704. const signature = Signature.from({ r, s, yParity });
  9705. tx.signature = signature;
  9706. }
  9707. function _parseEip1559(data) {
  9708. const fields = decodeRlp(getBytes(data).slice(1));
  9709. assertArgument(Array.isArray(fields) && (fields.length === 9 || fields.length === 12), "invalid field count for transaction type: 2", "data", hexlify(data));
  9710. const tx = {
  9711. type: 2,
  9712. chainId: handleUint(fields[0], "chainId"),
  9713. nonce: handleNumber(fields[1], "nonce"),
  9714. maxPriorityFeePerGas: handleUint(fields[2], "maxPriorityFeePerGas"),
  9715. maxFeePerGas: handleUint(fields[3], "maxFeePerGas"),
  9716. gasPrice: null,
  9717. gasLimit: handleUint(fields[4], "gasLimit"),
  9718. to: handleAddress(fields[5]),
  9719. value: handleUint(fields[6], "value"),
  9720. data: hexlify(fields[7]),
  9721. accessList: handleAccessList(fields[8], "accessList"),
  9722. };
  9723. // Unsigned EIP-1559 Transaction
  9724. if (fields.length === 9) {
  9725. return tx;
  9726. }
  9727. //tx.hash = keccak256(data);
  9728. _parseEipSignature(tx, fields.slice(9));
  9729. return tx;
  9730. }
  9731. function _serializeEip1559(tx, sig) {
  9732. const fields = [
  9733. formatNumber(tx.chainId, "chainId"),
  9734. formatNumber(tx.nonce, "nonce"),
  9735. formatNumber(tx.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"),
  9736. formatNumber(tx.maxFeePerGas || 0, "maxFeePerGas"),
  9737. formatNumber(tx.gasLimit, "gasLimit"),
  9738. (tx.to || "0x"),
  9739. formatNumber(tx.value, "value"),
  9740. tx.data,
  9741. formatAccessList(tx.accessList || [])
  9742. ];
  9743. if (sig) {
  9744. fields.push(formatNumber(sig.yParity, "yParity"));
  9745. fields.push(toBeArray(sig.r));
  9746. fields.push(toBeArray(sig.s));
  9747. }
  9748. return concat(["0x02", encodeRlp(fields)]);
  9749. }
  9750. function _parseEip2930(data) {
  9751. const fields = decodeRlp(getBytes(data).slice(1));
  9752. assertArgument(Array.isArray(fields) && (fields.length === 8 || fields.length === 11), "invalid field count for transaction type: 1", "data", hexlify(data));
  9753. const tx = {
  9754. type: 1,
  9755. chainId: handleUint(fields[0], "chainId"),
  9756. nonce: handleNumber(fields[1], "nonce"),
  9757. gasPrice: handleUint(fields[2], "gasPrice"),
  9758. gasLimit: handleUint(fields[3], "gasLimit"),
  9759. to: handleAddress(fields[4]),
  9760. value: handleUint(fields[5], "value"),
  9761. data: hexlify(fields[6]),
  9762. accessList: handleAccessList(fields[7], "accessList")
  9763. };
  9764. // Unsigned EIP-2930 Transaction
  9765. if (fields.length === 8) {
  9766. return tx;
  9767. }
  9768. //tx.hash = keccak256(data);
  9769. _parseEipSignature(tx, fields.slice(8));
  9770. return tx;
  9771. }
  9772. function _serializeEip2930(tx, sig) {
  9773. const fields = [
  9774. formatNumber(tx.chainId, "chainId"),
  9775. formatNumber(tx.nonce, "nonce"),
  9776. formatNumber(tx.gasPrice || 0, "gasPrice"),
  9777. formatNumber(tx.gasLimit, "gasLimit"),
  9778. (tx.to || "0x"),
  9779. formatNumber(tx.value, "value"),
  9780. tx.data,
  9781. formatAccessList(tx.accessList || [])
  9782. ];
  9783. if (sig) {
  9784. fields.push(formatNumber(sig.yParity, "recoveryParam"));
  9785. fields.push(toBeArray(sig.r));
  9786. fields.push(toBeArray(sig.s));
  9787. }
  9788. return concat(["0x01", encodeRlp(fields)]);
  9789. }
  9790. function _parseEip4844(data) {
  9791. let fields = decodeRlp(getBytes(data).slice(1));
  9792. let typeName = "3";
  9793. let blobs = null;
  9794. // Parse the network format
  9795. if (fields.length === 4 && Array.isArray(fields[0])) {
  9796. typeName = "3 (network format)";
  9797. const fBlobs = fields[1], fCommits = fields[2], fProofs = fields[3];
  9798. assertArgument(Array.isArray(fBlobs), "invalid network format: blobs not an array", "fields[1]", fBlobs);
  9799. assertArgument(Array.isArray(fCommits), "invalid network format: commitments not an array", "fields[2]", fCommits);
  9800. assertArgument(Array.isArray(fProofs), "invalid network format: proofs not an array", "fields[3]", fProofs);
  9801. assertArgument(fBlobs.length === fCommits.length, "invalid network format: blobs/commitments length mismatch", "fields", fields);
  9802. assertArgument(fBlobs.length === fProofs.length, "invalid network format: blobs/proofs length mismatch", "fields", fields);
  9803. blobs = [];
  9804. for (let i = 0; i < fields[1].length; i++) {
  9805. blobs.push({
  9806. data: fBlobs[i],
  9807. commitment: fCommits[i],
  9808. proof: fProofs[i],
  9809. });
  9810. }
  9811. fields = fields[0];
  9812. }
  9813. assertArgument(Array.isArray(fields) && (fields.length === 11 || fields.length === 14), `invalid field count for transaction type: ${typeName}`, "data", hexlify(data));
  9814. const tx = {
  9815. type: 3,
  9816. chainId: handleUint(fields[0], "chainId"),
  9817. nonce: handleNumber(fields[1], "nonce"),
  9818. maxPriorityFeePerGas: handleUint(fields[2], "maxPriorityFeePerGas"),
  9819. maxFeePerGas: handleUint(fields[3], "maxFeePerGas"),
  9820. gasPrice: null,
  9821. gasLimit: handleUint(fields[4], "gasLimit"),
  9822. to: handleAddress(fields[5]),
  9823. value: handleUint(fields[6], "value"),
  9824. data: hexlify(fields[7]),
  9825. accessList: handleAccessList(fields[8], "accessList"),
  9826. maxFeePerBlobGas: handleUint(fields[9], "maxFeePerBlobGas"),
  9827. blobVersionedHashes: fields[10]
  9828. };
  9829. if (blobs) {
  9830. tx.blobs = blobs;
  9831. }
  9832. assertArgument(tx.to != null, `invalid address for transaction type: ${typeName}`, "data", data);
  9833. assertArgument(Array.isArray(tx.blobVersionedHashes), "invalid blobVersionedHashes: must be an array", "data", data);
  9834. for (let i = 0; i < tx.blobVersionedHashes.length; i++) {
  9835. assertArgument(isHexString(tx.blobVersionedHashes[i], 32), `invalid blobVersionedHash at index ${i}: must be length 32`, "data", data);
  9836. }
  9837. // Unsigned EIP-4844 Transaction
  9838. if (fields.length === 11) {
  9839. return tx;
  9840. }
  9841. // @TODO: Do we need to do this? This is only called internally
  9842. // and used to verify hashes; it might save time to not do this
  9843. //tx.hash = keccak256(concat([ "0x03", encodeRlp(fields) ]));
  9844. _parseEipSignature(tx, fields.slice(11));
  9845. return tx;
  9846. }
  9847. function _serializeEip4844(tx, sig, blobs) {
  9848. const fields = [
  9849. formatNumber(tx.chainId, "chainId"),
  9850. formatNumber(tx.nonce, "nonce"),
  9851. formatNumber(tx.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"),
  9852. formatNumber(tx.maxFeePerGas || 0, "maxFeePerGas"),
  9853. formatNumber(tx.gasLimit, "gasLimit"),
  9854. (tx.to || ZeroAddress),
  9855. formatNumber(tx.value, "value"),
  9856. tx.data,
  9857. formatAccessList(tx.accessList || []),
  9858. formatNumber(tx.maxFeePerBlobGas || 0, "maxFeePerBlobGas"),
  9859. formatHashes(tx.blobVersionedHashes || [], "blobVersionedHashes")
  9860. ];
  9861. if (sig) {
  9862. fields.push(formatNumber(sig.yParity, "yParity"));
  9863. fields.push(toBeArray(sig.r));
  9864. fields.push(toBeArray(sig.s));
  9865. // We have blobs; return the network wrapped format
  9866. if (blobs) {
  9867. return concat([
  9868. "0x03",
  9869. encodeRlp([
  9870. fields,
  9871. blobs.map((b) => b.data),
  9872. blobs.map((b) => b.commitment),
  9873. blobs.map((b) => b.proof),
  9874. ])
  9875. ]);
  9876. }
  9877. }
  9878. return concat(["0x03", encodeRlp(fields)]);
  9879. }
  9880. /**
  9881. * A **Transaction** describes an operation to be executed on
  9882. * Ethereum by an Externally Owned Account (EOA). It includes
  9883. * who (the [[to]] address), what (the [[data]]) and how much (the
  9884. * [[value]] in ether) the operation should entail.
  9885. *
  9886. * @example:
  9887. * tx = new Transaction()
  9888. * //_result:
  9889. *
  9890. * tx.data = "0x1234";
  9891. * //_result:
  9892. */
  9893. class Transaction {
  9894. #type;
  9895. #to;
  9896. #data;
  9897. #nonce;
  9898. #gasLimit;
  9899. #gasPrice;
  9900. #maxPriorityFeePerGas;
  9901. #maxFeePerGas;
  9902. #value;
  9903. #chainId;
  9904. #sig;
  9905. #accessList;
  9906. #maxFeePerBlobGas;
  9907. #blobVersionedHashes;
  9908. #kzg;
  9909. #blobs;
  9910. /**
  9911. * The transaction type.
  9912. *
  9913. * If null, the type will be automatically inferred based on
  9914. * explicit properties.
  9915. */
  9916. get type() { return this.#type; }
  9917. set type(value) {
  9918. switch (value) {
  9919. case null:
  9920. this.#type = null;
  9921. break;
  9922. case 0:
  9923. case "legacy":
  9924. this.#type = 0;
  9925. break;
  9926. case 1:
  9927. case "berlin":
  9928. case "eip-2930":
  9929. this.#type = 1;
  9930. break;
  9931. case 2:
  9932. case "london":
  9933. case "eip-1559":
  9934. this.#type = 2;
  9935. break;
  9936. case 3:
  9937. case "cancun":
  9938. case "eip-4844":
  9939. this.#type = 3;
  9940. break;
  9941. default:
  9942. assertArgument(false, "unsupported transaction type", "type", value);
  9943. }
  9944. }
  9945. /**
  9946. * The name of the transaction type.
  9947. */
  9948. get typeName() {
  9949. switch (this.type) {
  9950. case 0: return "legacy";
  9951. case 1: return "eip-2930";
  9952. case 2: return "eip-1559";
  9953. case 3: return "eip-4844";
  9954. }
  9955. return null;
  9956. }
  9957. /**
  9958. * The ``to`` address for the transaction or ``null`` if the
  9959. * transaction is an ``init`` transaction.
  9960. */
  9961. get to() {
  9962. const value = this.#to;
  9963. if (value == null && this.type === 3) {
  9964. return ZeroAddress;
  9965. }
  9966. return value;
  9967. }
  9968. set to(value) {
  9969. this.#to = (value == null) ? null : getAddress(value);
  9970. }
  9971. /**
  9972. * The transaction nonce.
  9973. */
  9974. get nonce() { return this.#nonce; }
  9975. set nonce(value) { this.#nonce = getNumber(value, "value"); }
  9976. /**
  9977. * The gas limit.
  9978. */
  9979. get gasLimit() { return this.#gasLimit; }
  9980. set gasLimit(value) { this.#gasLimit = getBigInt(value); }
  9981. /**
  9982. * The gas price.
  9983. *
  9984. * On legacy networks this defines the fee that will be paid. On
  9985. * EIP-1559 networks, this should be ``null``.
  9986. */
  9987. get gasPrice() {
  9988. const value = this.#gasPrice;
  9989. if (value == null && (this.type === 0 || this.type === 1)) {
  9990. return BN_0$4;
  9991. }
  9992. return value;
  9993. }
  9994. set gasPrice(value) {
  9995. this.#gasPrice = (value == null) ? null : getBigInt(value, "gasPrice");
  9996. }
  9997. /**
  9998. * The maximum priority fee per unit of gas to pay. On legacy
  9999. * networks this should be ``null``.
  10000. */
  10001. get maxPriorityFeePerGas() {
  10002. const value = this.#maxPriorityFeePerGas;
  10003. if (value == null) {
  10004. if (this.type === 2 || this.type === 3) {
  10005. return BN_0$4;
  10006. }
  10007. return null;
  10008. }
  10009. return value;
  10010. }
  10011. set maxPriorityFeePerGas(value) {
  10012. this.#maxPriorityFeePerGas = (value == null) ? null : getBigInt(value, "maxPriorityFeePerGas");
  10013. }
  10014. /**
  10015. * The maximum total fee per unit of gas to pay. On legacy
  10016. * networks this should be ``null``.
  10017. */
  10018. get maxFeePerGas() {
  10019. const value = this.#maxFeePerGas;
  10020. if (value == null) {
  10021. if (this.type === 2 || this.type === 3) {
  10022. return BN_0$4;
  10023. }
  10024. return null;
  10025. }
  10026. return value;
  10027. }
  10028. set maxFeePerGas(value) {
  10029. this.#maxFeePerGas = (value == null) ? null : getBigInt(value, "maxFeePerGas");
  10030. }
  10031. /**
  10032. * The transaction data. For ``init`` transactions this is the
  10033. * deployment code.
  10034. */
  10035. get data() { return this.#data; }
  10036. set data(value) { this.#data = hexlify(value); }
  10037. /**
  10038. * The amount of ether (in wei) to send in this transactions.
  10039. */
  10040. get value() { return this.#value; }
  10041. set value(value) {
  10042. this.#value = getBigInt(value, "value");
  10043. }
  10044. /**
  10045. * The chain ID this transaction is valid on.
  10046. */
  10047. get chainId() { return this.#chainId; }
  10048. set chainId(value) { this.#chainId = getBigInt(value); }
  10049. /**
  10050. * If signed, the signature for this transaction.
  10051. */
  10052. get signature() { return this.#sig || null; }
  10053. set signature(value) {
  10054. this.#sig = (value == null) ? null : Signature.from(value);
  10055. }
  10056. /**
  10057. * The access list.
  10058. *
  10059. * An access list permits discounted (but pre-paid) access to
  10060. * bytecode and state variable access within contract execution.
  10061. */
  10062. get accessList() {
  10063. const value = this.#accessList || null;
  10064. if (value == null) {
  10065. if (this.type === 1 || this.type === 2 || this.type === 3) {
  10066. // @TODO: in v7, this should assign the value or become
  10067. // a live object itself, otherwise mutation is inconsistent
  10068. return [];
  10069. }
  10070. return null;
  10071. }
  10072. return value;
  10073. }
  10074. set accessList(value) {
  10075. this.#accessList = (value == null) ? null : accessListify(value);
  10076. }
  10077. /**
  10078. * The max fee per blob gas for Cancun transactions.
  10079. */
  10080. get maxFeePerBlobGas() {
  10081. const value = this.#maxFeePerBlobGas;
  10082. if (value == null && this.type === 3) {
  10083. return BN_0$4;
  10084. }
  10085. return value;
  10086. }
  10087. set maxFeePerBlobGas(value) {
  10088. this.#maxFeePerBlobGas = (value == null) ? null : getBigInt(value, "maxFeePerBlobGas");
  10089. }
  10090. /**
  10091. * The BLOb versioned hashes for Cancun transactions.
  10092. */
  10093. get blobVersionedHashes() {
  10094. // @TODO: Mutation is inconsistent; if unset, the returned value
  10095. // cannot mutate the object, if set it can
  10096. let value = this.#blobVersionedHashes;
  10097. if (value == null && this.type === 3) {
  10098. return [];
  10099. }
  10100. return value;
  10101. }
  10102. set blobVersionedHashes(value) {
  10103. if (value != null) {
  10104. assertArgument(Array.isArray(value), "blobVersionedHashes must be an Array", "value", value);
  10105. value = value.slice();
  10106. for (let i = 0; i < value.length; i++) {
  10107. assertArgument(isHexString(value[i], 32), "invalid blobVersionedHash", `value[${i}]`, value[i]);
  10108. }
  10109. }
  10110. this.#blobVersionedHashes = value;
  10111. }
  10112. /**
  10113. * The BLObs for the Transaction, if any.
  10114. *
  10115. * If ``blobs`` is non-``null``, then the [[seriailized]]
  10116. * will return the network formatted sidecar, otherwise it
  10117. * will return the standard [[link-eip-2718]] payload. The
  10118. * [[unsignedSerialized]] is unaffected regardless.
  10119. *
  10120. * When setting ``blobs``, either fully valid [[Blob]] objects
  10121. * may be specified (i.e. correctly padded, with correct
  10122. * committments and proofs) or a raw [[BytesLike]] may
  10123. * be provided.
  10124. *
  10125. * If raw [[BytesLike]] are provided, the [[kzg]] property **must**
  10126. * be already set. The blob will be correctly padded and the
  10127. * [[KzgLibrary]] will be used to compute the committment and
  10128. * proof for the blob.
  10129. *
  10130. * A BLOb is a sequence of field elements, each of which must
  10131. * be within the BLS field modulo, so some additional processing
  10132. * may be required to encode arbitrary data to ensure each 32 byte
  10133. * field is within the valid range.
  10134. *
  10135. * Setting this automatically populates [[blobVersionedHashes]],
  10136. * overwriting any existing values. Setting this to ``null``
  10137. * does **not** remove the [[blobVersionedHashes]], leaving them
  10138. * present.
  10139. */
  10140. get blobs() {
  10141. if (this.#blobs == null) {
  10142. return null;
  10143. }
  10144. return this.#blobs.map((b) => Object.assign({}, b));
  10145. }
  10146. set blobs(_blobs) {
  10147. if (_blobs == null) {
  10148. this.#blobs = null;
  10149. return;
  10150. }
  10151. const blobs = [];
  10152. const versionedHashes = [];
  10153. for (let i = 0; i < _blobs.length; i++) {
  10154. const blob = _blobs[i];
  10155. if (isBytesLike(blob)) {
  10156. assert(this.#kzg, "adding a raw blob requires a KZG library", "UNSUPPORTED_OPERATION", {
  10157. operation: "set blobs()"
  10158. });
  10159. let data = getBytes(blob);
  10160. assertArgument(data.length <= BLOB_SIZE, "blob is too large", `blobs[${i}]`, blob);
  10161. // Pad blob if necessary
  10162. if (data.length !== BLOB_SIZE) {
  10163. const padded = new Uint8Array(BLOB_SIZE);
  10164. padded.set(data);
  10165. data = padded;
  10166. }
  10167. const commit = this.#kzg.blobToKzgCommitment(data);
  10168. const proof = hexlify(this.#kzg.computeBlobKzgProof(data, commit));
  10169. blobs.push({
  10170. data: hexlify(data),
  10171. commitment: hexlify(commit),
  10172. proof
  10173. });
  10174. versionedHashes.push(getVersionedHash(1, commit));
  10175. }
  10176. else {
  10177. const commit = hexlify(blob.commitment);
  10178. blobs.push({
  10179. data: hexlify(blob.data),
  10180. commitment: commit,
  10181. proof: hexlify(blob.proof)
  10182. });
  10183. versionedHashes.push(getVersionedHash(1, commit));
  10184. }
  10185. }
  10186. this.#blobs = blobs;
  10187. this.#blobVersionedHashes = versionedHashes;
  10188. }
  10189. get kzg() { return this.#kzg; }
  10190. set kzg(kzg) {
  10191. this.#kzg = kzg;
  10192. }
  10193. /**
  10194. * Creates a new Transaction with default values.
  10195. */
  10196. constructor() {
  10197. this.#type = null;
  10198. this.#to = null;
  10199. this.#nonce = 0;
  10200. this.#gasLimit = BN_0$4;
  10201. this.#gasPrice = null;
  10202. this.#maxPriorityFeePerGas = null;
  10203. this.#maxFeePerGas = null;
  10204. this.#data = "0x";
  10205. this.#value = BN_0$4;
  10206. this.#chainId = BN_0$4;
  10207. this.#sig = null;
  10208. this.#accessList = null;
  10209. this.#maxFeePerBlobGas = null;
  10210. this.#blobVersionedHashes = null;
  10211. this.#blobs = null;
  10212. this.#kzg = null;
  10213. }
  10214. /**
  10215. * The transaction hash, if signed. Otherwise, ``null``.
  10216. */
  10217. get hash() {
  10218. if (this.signature == null) {
  10219. return null;
  10220. }
  10221. return keccak256(this.#getSerialized(true, false));
  10222. }
  10223. /**
  10224. * The pre-image hash of this transaction.
  10225. *
  10226. * This is the digest that a [[Signer]] must sign to authorize
  10227. * this transaction.
  10228. */
  10229. get unsignedHash() {
  10230. return keccak256(this.unsignedSerialized);
  10231. }
  10232. /**
  10233. * The sending address, if signed. Otherwise, ``null``.
  10234. */
  10235. get from() {
  10236. if (this.signature == null) {
  10237. return null;
  10238. }
  10239. return recoverAddress(this.unsignedHash, this.signature);
  10240. }
  10241. /**
  10242. * The public key of the sender, if signed. Otherwise, ``null``.
  10243. */
  10244. get fromPublicKey() {
  10245. if (this.signature == null) {
  10246. return null;
  10247. }
  10248. return SigningKey.recoverPublicKey(this.unsignedHash, this.signature);
  10249. }
  10250. /**
  10251. * Returns true if signed.
  10252. *
  10253. * This provides a Type Guard that properties requiring a signed
  10254. * transaction are non-null.
  10255. */
  10256. isSigned() {
  10257. return this.signature != null;
  10258. }
  10259. #getSerialized(signed, sidecar) {
  10260. assert(!signed || this.signature != null, "cannot serialize unsigned transaction; maybe you meant .unsignedSerialized", "UNSUPPORTED_OPERATION", { operation: ".serialized" });
  10261. const sig = signed ? this.signature : null;
  10262. switch (this.inferType()) {
  10263. case 0:
  10264. return _serializeLegacy(this, sig);
  10265. case 1:
  10266. return _serializeEip2930(this, sig);
  10267. case 2:
  10268. return _serializeEip1559(this, sig);
  10269. case 3:
  10270. return _serializeEip4844(this, sig, sidecar ? this.blobs : null);
  10271. }
  10272. assert(false, "unsupported transaction type", "UNSUPPORTED_OPERATION", { operation: ".serialized" });
  10273. }
  10274. /**
  10275. * The serialized transaction.
  10276. *
  10277. * This throws if the transaction is unsigned. For the pre-image,
  10278. * use [[unsignedSerialized]].
  10279. */
  10280. get serialized() {
  10281. return this.#getSerialized(true, true);
  10282. }
  10283. /**
  10284. * The transaction pre-image.
  10285. *
  10286. * The hash of this is the digest which needs to be signed to
  10287. * authorize this transaction.
  10288. */
  10289. get unsignedSerialized() {
  10290. return this.#getSerialized(false, false);
  10291. }
  10292. /**
  10293. * Return the most "likely" type; currently the highest
  10294. * supported transaction type.
  10295. */
  10296. inferType() {
  10297. const types = this.inferTypes();
  10298. // Prefer London (EIP-1559) over Cancun (BLOb)
  10299. if (types.indexOf(2) >= 0) {
  10300. return 2;
  10301. }
  10302. // Return the highest inferred type
  10303. return (types.pop());
  10304. }
  10305. /**
  10306. * Validates the explicit properties and returns a list of compatible
  10307. * transaction types.
  10308. */
  10309. inferTypes() {
  10310. // Checks that there are no conflicting properties set
  10311. const hasGasPrice = this.gasPrice != null;
  10312. const hasFee = (this.maxFeePerGas != null || this.maxPriorityFeePerGas != null);
  10313. const hasAccessList = (this.accessList != null);
  10314. const hasBlob = (this.#maxFeePerBlobGas != null || this.#blobVersionedHashes);
  10315. //if (hasGasPrice && hasFee) {
  10316. // throw new Error("transaction cannot have gasPrice and maxFeePerGas");
  10317. //}
  10318. if (this.maxFeePerGas != null && this.maxPriorityFeePerGas != null) {
  10319. assert(this.maxFeePerGas >= this.maxPriorityFeePerGas, "priorityFee cannot be more than maxFee", "BAD_DATA", { value: this });
  10320. }
  10321. //if (this.type === 2 && hasGasPrice) {
  10322. // throw new Error("eip-1559 transaction cannot have gasPrice");
  10323. //}
  10324. assert(!hasFee || (this.type !== 0 && this.type !== 1), "transaction type cannot have maxFeePerGas or maxPriorityFeePerGas", "BAD_DATA", { value: this });
  10325. assert(this.type !== 0 || !hasAccessList, "legacy transaction cannot have accessList", "BAD_DATA", { value: this });
  10326. const types = [];
  10327. // Explicit type
  10328. if (this.type != null) {
  10329. types.push(this.type);
  10330. }
  10331. else {
  10332. if (hasFee) {
  10333. types.push(2);
  10334. }
  10335. else if (hasGasPrice) {
  10336. types.push(1);
  10337. if (!hasAccessList) {
  10338. types.push(0);
  10339. }
  10340. }
  10341. else if (hasAccessList) {
  10342. types.push(1);
  10343. types.push(2);
  10344. }
  10345. else if (hasBlob && this.to) {
  10346. types.push(3);
  10347. }
  10348. else {
  10349. types.push(0);
  10350. types.push(1);
  10351. types.push(2);
  10352. types.push(3);
  10353. }
  10354. }
  10355. types.sort();
  10356. return types;
  10357. }
  10358. /**
  10359. * Returns true if this transaction is a legacy transaction (i.e.
  10360. * ``type === 0``).
  10361. *
  10362. * This provides a Type Guard that the related properties are
  10363. * non-null.
  10364. */
  10365. isLegacy() {
  10366. return (this.type === 0);
  10367. }
  10368. /**
  10369. * Returns true if this transaction is berlin hardform transaction (i.e.
  10370. * ``type === 1``).
  10371. *
  10372. * This provides a Type Guard that the related properties are
  10373. * non-null.
  10374. */
  10375. isBerlin() {
  10376. return (this.type === 1);
  10377. }
  10378. /**
  10379. * Returns true if this transaction is london hardform transaction (i.e.
  10380. * ``type === 2``).
  10381. *
  10382. * This provides a Type Guard that the related properties are
  10383. * non-null.
  10384. */
  10385. isLondon() {
  10386. return (this.type === 2);
  10387. }
  10388. /**
  10389. * Returns true if this transaction is an [[link-eip-4844]] BLOB
  10390. * transaction.
  10391. *
  10392. * This provides a Type Guard that the related properties are
  10393. * non-null.
  10394. */
  10395. isCancun() {
  10396. return (this.type === 3);
  10397. }
  10398. /**
  10399. * Create a copy of this transaciton.
  10400. */
  10401. clone() {
  10402. return Transaction.from(this);
  10403. }
  10404. /**
  10405. * Return a JSON-friendly object.
  10406. */
  10407. toJSON() {
  10408. const s = (v) => {
  10409. if (v == null) {
  10410. return null;
  10411. }
  10412. return v.toString();
  10413. };
  10414. return {
  10415. type: this.type,
  10416. to: this.to,
  10417. // from: this.from,
  10418. data: this.data,
  10419. nonce: this.nonce,
  10420. gasLimit: s(this.gasLimit),
  10421. gasPrice: s(this.gasPrice),
  10422. maxPriorityFeePerGas: s(this.maxPriorityFeePerGas),
  10423. maxFeePerGas: s(this.maxFeePerGas),
  10424. value: s(this.value),
  10425. chainId: s(this.chainId),
  10426. sig: this.signature ? this.signature.toJSON() : null,
  10427. accessList: this.accessList
  10428. };
  10429. }
  10430. /**
  10431. * Create a **Transaction** from a serialized transaction or a
  10432. * Transaction-like object.
  10433. */
  10434. static from(tx) {
  10435. if (tx == null) {
  10436. return new Transaction();
  10437. }
  10438. if (typeof (tx) === "string") {
  10439. const payload = getBytes(tx);
  10440. if (payload[0] >= 0x7f) { // @TODO: > vs >= ??
  10441. return Transaction.from(_parseLegacy(payload));
  10442. }
  10443. switch (payload[0]) {
  10444. case 1: return Transaction.from(_parseEip2930(payload));
  10445. case 2: return Transaction.from(_parseEip1559(payload));
  10446. case 3: return Transaction.from(_parseEip4844(payload));
  10447. }
  10448. assert(false, "unsupported transaction type", "UNSUPPORTED_OPERATION", { operation: "from" });
  10449. }
  10450. const result = new Transaction();
  10451. if (tx.type != null) {
  10452. result.type = tx.type;
  10453. }
  10454. if (tx.to != null) {
  10455. result.to = tx.to;
  10456. }
  10457. if (tx.nonce != null) {
  10458. result.nonce = tx.nonce;
  10459. }
  10460. if (tx.gasLimit != null) {
  10461. result.gasLimit = tx.gasLimit;
  10462. }
  10463. if (tx.gasPrice != null) {
  10464. result.gasPrice = tx.gasPrice;
  10465. }
  10466. if (tx.maxPriorityFeePerGas != null) {
  10467. result.maxPriorityFeePerGas = tx.maxPriorityFeePerGas;
  10468. }
  10469. if (tx.maxFeePerGas != null) {
  10470. result.maxFeePerGas = tx.maxFeePerGas;
  10471. }
  10472. if (tx.maxFeePerBlobGas != null) {
  10473. result.maxFeePerBlobGas = tx.maxFeePerBlobGas;
  10474. }
  10475. if (tx.data != null) {
  10476. result.data = tx.data;
  10477. }
  10478. if (tx.value != null) {
  10479. result.value = tx.value;
  10480. }
  10481. if (tx.chainId != null) {
  10482. result.chainId = tx.chainId;
  10483. }
  10484. if (tx.signature != null) {
  10485. result.signature = Signature.from(tx.signature);
  10486. }
  10487. if (tx.accessList != null) {
  10488. result.accessList = tx.accessList;
  10489. }
  10490. // This will get overwritten by blobs, if present
  10491. if (tx.blobVersionedHashes != null) {
  10492. result.blobVersionedHashes = tx.blobVersionedHashes;
  10493. }
  10494. // Make sure we assign the kzg before assigning blobs, which
  10495. // require the library in the event raw blob data is provided.
  10496. if (tx.kzg != null) {
  10497. result.kzg = tx.kzg;
  10498. }
  10499. if (tx.blobs != null) {
  10500. result.blobs = tx.blobs;
  10501. }
  10502. if (tx.hash != null) {
  10503. assertArgument(result.isSigned(), "unsigned transaction cannot define '.hash'", "tx", tx);
  10504. assertArgument(result.hash === tx.hash, "hash mismatch", "tx", tx);
  10505. }
  10506. if (tx.from != null) {
  10507. assertArgument(result.isSigned(), "unsigned transaction cannot define '.from'", "tx", tx);
  10508. assertArgument(result.from.toLowerCase() === (tx.from || "").toLowerCase(), "from mismatch", "tx", tx);
  10509. }
  10510. return result;
  10511. }
  10512. }
  10513. /**
  10514. * Computes the [[link-eip-191]] personal-sign message digest to sign.
  10515. *
  10516. * This prefixes the message with [[MessagePrefix]] and the decimal length
  10517. * of %%message%% and computes the [[keccak256]] digest.
  10518. *
  10519. * If %%message%% is a string, it is converted to its UTF-8 bytes
  10520. * first. To compute the digest of a [[DataHexString]], it must be converted
  10521. * to [bytes](getBytes).
  10522. *
  10523. * @example:
  10524. * hashMessage("Hello World")
  10525. * //_result:
  10526. *
  10527. * // Hashes the SIX (6) string characters, i.e.
  10528. * // [ "0", "x", "4", "2", "4", "3" ]
  10529. * hashMessage("0x4243")
  10530. * //_result:
  10531. *
  10532. * // Hashes the TWO (2) bytes [ 0x42, 0x43 ]...
  10533. * hashMessage(getBytes("0x4243"))
  10534. * //_result:
  10535. *
  10536. * // ...which is equal to using data
  10537. * hashMessage(new Uint8Array([ 0x42, 0x43 ]))
  10538. * //_result:
  10539. *
  10540. */
  10541. function hashMessage(message) {
  10542. if (typeof (message) === "string") {
  10543. message = toUtf8Bytes(message);
  10544. }
  10545. return keccak256(concat([
  10546. toUtf8Bytes(MessagePrefix),
  10547. toUtf8Bytes(String(message.length)),
  10548. message
  10549. ]));
  10550. }
  10551. /**
  10552. * Return the address of the private key that produced
  10553. * the signature %%sig%% during signing for %%message%%.
  10554. */
  10555. function verifyMessage(message, sig) {
  10556. const digest = hashMessage(message);
  10557. return recoverAddress(digest, sig);
  10558. }
  10559. const regexBytes = new RegExp("^bytes([0-9]+)$");
  10560. const regexNumber = new RegExp("^(u?int)([0-9]*)$");
  10561. const regexArray = new RegExp("^(.*)\\[([0-9]*)\\]$");
  10562. function _pack(type, value, isArray) {
  10563. switch (type) {
  10564. case "address":
  10565. if (isArray) {
  10566. return getBytes(zeroPadValue(value, 32));
  10567. }
  10568. return getBytes(getAddress(value));
  10569. case "string":
  10570. return toUtf8Bytes(value);
  10571. case "bytes":
  10572. return getBytes(value);
  10573. case "bool":
  10574. value = (!!value ? "0x01" : "0x00");
  10575. if (isArray) {
  10576. return getBytes(zeroPadValue(value, 32));
  10577. }
  10578. return getBytes(value);
  10579. }
  10580. let match = type.match(regexNumber);
  10581. if (match) {
  10582. let signed = (match[1] === "int");
  10583. let size = parseInt(match[2] || "256");
  10584. assertArgument((!match[2] || match[2] === String(size)) && (size % 8 === 0) && size !== 0 && size <= 256, "invalid number type", "type", type);
  10585. if (isArray) {
  10586. size = 256;
  10587. }
  10588. if (signed) {
  10589. value = toTwos(value, size);
  10590. }
  10591. return getBytes(zeroPadValue(toBeArray(value), size / 8));
  10592. }
  10593. match = type.match(regexBytes);
  10594. if (match) {
  10595. const size = parseInt(match[1]);
  10596. assertArgument(String(size) === match[1] && size !== 0 && size <= 32, "invalid bytes type", "type", type);
  10597. assertArgument(dataLength(value) === size, `invalid value for ${type}`, "value", value);
  10598. if (isArray) {
  10599. return getBytes(zeroPadBytes(value, 32));
  10600. }
  10601. return value;
  10602. }
  10603. match = type.match(regexArray);
  10604. if (match && Array.isArray(value)) {
  10605. const baseType = match[1];
  10606. const count = parseInt(match[2] || String(value.length));
  10607. assertArgument(count === value.length, `invalid array length for ${type}`, "value", value);
  10608. const result = [];
  10609. value.forEach(function (value) {
  10610. result.push(_pack(baseType, value, true));
  10611. });
  10612. return getBytes(concat(result));
  10613. }
  10614. assertArgument(false, "invalid type", "type", type);
  10615. }
  10616. // @TODO: Array Enum
  10617. /**
  10618. * Computes the [[link-solc-packed]] representation of %%values%%
  10619. * respectively to their %%types%%.
  10620. *
  10621. * @example:
  10622. * addr = "0x8ba1f109551bd432803012645ac136ddd64dba72"
  10623. * solidityPacked([ "address", "uint" ], [ addr, 45 ]);
  10624. * //_result:
  10625. */
  10626. function solidityPacked(types, values) {
  10627. assertArgument(types.length === values.length, "wrong number of values; expected ${ types.length }", "values", values);
  10628. const tight = [];
  10629. types.forEach(function (type, index) {
  10630. tight.push(_pack(type, values[index]));
  10631. });
  10632. return hexlify(concat(tight));
  10633. }
  10634. /**
  10635. * Computes the [[link-solc-packed]] [[keccak256]] hash of %%values%%
  10636. * respectively to their %%types%%.
  10637. *
  10638. * @example:
  10639. * addr = "0x8ba1f109551bd432803012645ac136ddd64dba72"
  10640. * solidityPackedKeccak256([ "address", "uint" ], [ addr, 45 ]);
  10641. * //_result:
  10642. */
  10643. function solidityPackedKeccak256(types, values) {
  10644. return keccak256(solidityPacked(types, values));
  10645. }
  10646. /**
  10647. * Computes the [[link-solc-packed]] [[sha256]] hash of %%values%%
  10648. * respectively to their %%types%%.
  10649. *
  10650. * @example:
  10651. * addr = "0x8ba1f109551bd432803012645ac136ddd64dba72"
  10652. * solidityPackedSha256([ "address", "uint" ], [ addr, 45 ]);
  10653. * //_result:
  10654. */
  10655. function solidityPackedSha256(types, values) {
  10656. return sha256(solidityPacked(types, values));
  10657. }
  10658. //import { TypedDataDomain, TypedDataField } from "@ethersproject/providerabstract-signer";
  10659. const padding = new Uint8Array(32);
  10660. padding.fill(0);
  10661. const BN__1 = BigInt(-1);
  10662. const BN_0$3 = BigInt(0);
  10663. const BN_1$1 = BigInt(1);
  10664. const BN_MAX_UINT256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
  10665. function hexPadRight(value) {
  10666. const bytes = getBytes(value);
  10667. const padOffset = bytes.length % 32;
  10668. if (padOffset) {
  10669. return concat([bytes, padding.slice(padOffset)]);
  10670. }
  10671. return hexlify(bytes);
  10672. }
  10673. const hexTrue = toBeHex(BN_1$1, 32);
  10674. const hexFalse = toBeHex(BN_0$3, 32);
  10675. const domainFieldTypes = {
  10676. name: "string",
  10677. version: "string",
  10678. chainId: "uint256",
  10679. verifyingContract: "address",
  10680. salt: "bytes32"
  10681. };
  10682. const domainFieldNames = [
  10683. "name", "version", "chainId", "verifyingContract", "salt"
  10684. ];
  10685. function checkString(key) {
  10686. return function (value) {
  10687. assertArgument(typeof (value) === "string", `invalid domain value for ${JSON.stringify(key)}`, `domain.${key}`, value);
  10688. return value;
  10689. };
  10690. }
  10691. const domainChecks = {
  10692. name: checkString("name"),
  10693. version: checkString("version"),
  10694. chainId: function (_value) {
  10695. const value = getBigInt(_value, "domain.chainId");
  10696. assertArgument(value >= 0, "invalid chain ID", "domain.chainId", _value);
  10697. if (Number.isSafeInteger(value)) {
  10698. return Number(value);
  10699. }
  10700. return toQuantity(value);
  10701. },
  10702. verifyingContract: function (value) {
  10703. try {
  10704. return getAddress(value).toLowerCase();
  10705. }
  10706. catch (error) { }
  10707. assertArgument(false, `invalid domain value "verifyingContract"`, "domain.verifyingContract", value);
  10708. },
  10709. salt: function (value) {
  10710. const bytes = getBytes(value, "domain.salt");
  10711. assertArgument(bytes.length === 32, `invalid domain value "salt"`, "domain.salt", value);
  10712. return hexlify(bytes);
  10713. }
  10714. };
  10715. function getBaseEncoder(type) {
  10716. // intXX and uintXX
  10717. {
  10718. const match = type.match(/^(u?)int(\d+)$/);
  10719. if (match) {
  10720. const signed = (match[1] === "");
  10721. const width = parseInt(match[2]);
  10722. assertArgument(width % 8 === 0 && width !== 0 && width <= 256 && match[2] === String(width), "invalid numeric width", "type", type);
  10723. const boundsUpper = mask(BN_MAX_UINT256, signed ? (width - 1) : width);
  10724. const boundsLower = signed ? ((boundsUpper + BN_1$1) * BN__1) : BN_0$3;
  10725. return function (_value) {
  10726. const value = getBigInt(_value, "value");
  10727. assertArgument(value >= boundsLower && value <= boundsUpper, `value out-of-bounds for ${type}`, "value", value);
  10728. return toBeHex(signed ? toTwos(value, 256) : value, 32);
  10729. };
  10730. }
  10731. }
  10732. // bytesXX
  10733. {
  10734. const match = type.match(/^bytes(\d+)$/);
  10735. if (match) {
  10736. const width = parseInt(match[1]);
  10737. assertArgument(width !== 0 && width <= 32 && match[1] === String(width), "invalid bytes width", "type", type);
  10738. return function (value) {
  10739. const bytes = getBytes(value);
  10740. assertArgument(bytes.length === width, `invalid length for ${type}`, "value", value);
  10741. return hexPadRight(value);
  10742. };
  10743. }
  10744. }
  10745. switch (type) {
  10746. case "address": return function (value) {
  10747. return zeroPadValue(getAddress(value), 32);
  10748. };
  10749. case "bool": return function (value) {
  10750. return ((!value) ? hexFalse : hexTrue);
  10751. };
  10752. case "bytes": return function (value) {
  10753. return keccak256(value);
  10754. };
  10755. case "string": return function (value) {
  10756. return id(value);
  10757. };
  10758. }
  10759. return null;
  10760. }
  10761. function encodeType(name, fields) {
  10762. return `${name}(${fields.map(({ name, type }) => (type + " " + name)).join(",")})`;
  10763. }
  10764. // foo[][3] => { base: "foo", index: "[][3]", array: {
  10765. // base: "foo", prefix: "foo[]", count: 3 } }
  10766. function splitArray(type) {
  10767. const match = type.match(/^([^\x5b]*)((\x5b\d*\x5d)*)(\x5b(\d*)\x5d)$/);
  10768. if (match) {
  10769. return {
  10770. base: match[1],
  10771. index: (match[2] + match[4]),
  10772. array: {
  10773. base: match[1],
  10774. prefix: (match[1] + match[2]),
  10775. count: (match[5] ? parseInt(match[5]) : -1),
  10776. }
  10777. };
  10778. }
  10779. return { base: type };
  10780. }
  10781. /**
  10782. * A **TypedDataEncode** prepares and encodes [[link-eip-712]] payloads
  10783. * for signed typed data.
  10784. *
  10785. * This is useful for those that wish to compute various components of a
  10786. * typed data hash, primary types, or sub-components, but generally the
  10787. * higher level [[Signer-signTypedData]] is more useful.
  10788. */
  10789. class TypedDataEncoder {
  10790. /**
  10791. * The primary type for the structured [[types]].
  10792. *
  10793. * This is derived automatically from the [[types]], since no
  10794. * recursion is possible, once the DAG for the types is consturcted
  10795. * internally, the primary type must be the only remaining type with
  10796. * no parent nodes.
  10797. */
  10798. primaryType;
  10799. #types;
  10800. /**
  10801. * The types.
  10802. */
  10803. get types() {
  10804. return JSON.parse(this.#types);
  10805. }
  10806. #fullTypes;
  10807. #encoderCache;
  10808. /**
  10809. * Create a new **TypedDataEncoder** for %%types%%.
  10810. *
  10811. * This performs all necessary checking that types are valid and
  10812. * do not violate the [[link-eip-712]] structural constraints as
  10813. * well as computes the [[primaryType]].
  10814. */
  10815. constructor(_types) {
  10816. this.#fullTypes = new Map();
  10817. this.#encoderCache = new Map();
  10818. // Link struct types to their direct child structs
  10819. const links = new Map();
  10820. // Link structs to structs which contain them as a child
  10821. const parents = new Map();
  10822. // Link all subtypes within a given struct
  10823. const subtypes = new Map();
  10824. const types = {};
  10825. Object.keys(_types).forEach((type) => {
  10826. types[type] = _types[type].map(({ name, type }) => {
  10827. // Normalize the base type (unless name conflict)
  10828. let { base, index } = splitArray(type);
  10829. if (base === "int" && !_types["int"]) {
  10830. base = "int256";
  10831. }
  10832. if (base === "uint" && !_types["uint"]) {
  10833. base = "uint256";
  10834. }
  10835. return { name, type: (base + (index || "")) };
  10836. });
  10837. links.set(type, new Set());
  10838. parents.set(type, []);
  10839. subtypes.set(type, new Set());
  10840. });
  10841. this.#types = JSON.stringify(types);
  10842. for (const name in types) {
  10843. const uniqueNames = new Set();
  10844. for (const field of types[name]) {
  10845. // Check each field has a unique name
  10846. assertArgument(!uniqueNames.has(field.name), `duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name)}`, "types", _types);
  10847. uniqueNames.add(field.name);
  10848. // Get the base type (drop any array specifiers)
  10849. const baseType = splitArray(field.type).base;
  10850. assertArgument(baseType !== name, `circular type reference to ${JSON.stringify(baseType)}`, "types", _types);
  10851. // Is this a base encoding type?
  10852. const encoder = getBaseEncoder(baseType);
  10853. if (encoder) {
  10854. continue;
  10855. }
  10856. assertArgument(parents.has(baseType), `unknown type ${JSON.stringify(baseType)}`, "types", _types);
  10857. // Add linkage
  10858. parents.get(baseType).push(name);
  10859. links.get(name).add(baseType);
  10860. }
  10861. }
  10862. // Deduce the primary type
  10863. const primaryTypes = Array.from(parents.keys()).filter((n) => (parents.get(n).length === 0));
  10864. assertArgument(primaryTypes.length !== 0, "missing primary type", "types", _types);
  10865. assertArgument(primaryTypes.length === 1, `ambiguous primary types or unused types: ${primaryTypes.map((t) => (JSON.stringify(t))).join(", ")}`, "types", _types);
  10866. defineProperties(this, { primaryType: primaryTypes[0] });
  10867. // Check for circular type references
  10868. function checkCircular(type, found) {
  10869. assertArgument(!found.has(type), `circular type reference to ${JSON.stringify(type)}`, "types", _types);
  10870. found.add(type);
  10871. for (const child of links.get(type)) {
  10872. if (!parents.has(child)) {
  10873. continue;
  10874. }
  10875. // Recursively check children
  10876. checkCircular(child, found);
  10877. // Mark all ancestors as having this decendant
  10878. for (const subtype of found) {
  10879. subtypes.get(subtype).add(child);
  10880. }
  10881. }
  10882. found.delete(type);
  10883. }
  10884. checkCircular(this.primaryType, new Set());
  10885. // Compute each fully describe type
  10886. for (const [name, set] of subtypes) {
  10887. const st = Array.from(set);
  10888. st.sort();
  10889. this.#fullTypes.set(name, encodeType(name, types[name]) + st.map((t) => encodeType(t, types[t])).join(""));
  10890. }
  10891. }
  10892. /**
  10893. * Returnthe encoder for the specific %%type%%.
  10894. */
  10895. getEncoder(type) {
  10896. let encoder = this.#encoderCache.get(type);
  10897. if (!encoder) {
  10898. encoder = this.#getEncoder(type);
  10899. this.#encoderCache.set(type, encoder);
  10900. }
  10901. return encoder;
  10902. }
  10903. #getEncoder(type) {
  10904. // Basic encoder type (address, bool, uint256, etc)
  10905. {
  10906. const encoder = getBaseEncoder(type);
  10907. if (encoder) {
  10908. return encoder;
  10909. }
  10910. }
  10911. // Array
  10912. const array = splitArray(type).array;
  10913. if (array) {
  10914. const subtype = array.prefix;
  10915. const subEncoder = this.getEncoder(subtype);
  10916. return (value) => {
  10917. assertArgument(array.count === -1 || array.count === value.length, `array length mismatch; expected length ${array.count}`, "value", value);
  10918. let result = value.map(subEncoder);
  10919. if (this.#fullTypes.has(subtype)) {
  10920. result = result.map(keccak256);
  10921. }
  10922. return keccak256(concat(result));
  10923. };
  10924. }
  10925. // Struct
  10926. const fields = this.types[type];
  10927. if (fields) {
  10928. const encodedType = id(this.#fullTypes.get(type));
  10929. return (value) => {
  10930. const values = fields.map(({ name, type }) => {
  10931. const result = this.getEncoder(type)(value[name]);
  10932. if (this.#fullTypes.has(type)) {
  10933. return keccak256(result);
  10934. }
  10935. return result;
  10936. });
  10937. values.unshift(encodedType);
  10938. return concat(values);
  10939. };
  10940. }
  10941. assertArgument(false, `unknown type: ${type}`, "type", type);
  10942. }
  10943. /**
  10944. * Return the full type for %%name%%.
  10945. */
  10946. encodeType(name) {
  10947. const result = this.#fullTypes.get(name);
  10948. assertArgument(result, `unknown type: ${JSON.stringify(name)}`, "name", name);
  10949. return result;
  10950. }
  10951. /**
  10952. * Return the encoded %%value%% for the %%type%%.
  10953. */
  10954. encodeData(type, value) {
  10955. return this.getEncoder(type)(value);
  10956. }
  10957. /**
  10958. * Returns the hash of %%value%% for the type of %%name%%.
  10959. */
  10960. hashStruct(name, value) {
  10961. return keccak256(this.encodeData(name, value));
  10962. }
  10963. /**
  10964. * Return the fulled encoded %%value%% for the [[types]].
  10965. */
  10966. encode(value) {
  10967. return this.encodeData(this.primaryType, value);
  10968. }
  10969. /**
  10970. * Return the hash of the fully encoded %%value%% for the [[types]].
  10971. */
  10972. hash(value) {
  10973. return this.hashStruct(this.primaryType, value);
  10974. }
  10975. /**
  10976. * @_ignore:
  10977. */
  10978. _visit(type, value, callback) {
  10979. // Basic encoder type (address, bool, uint256, etc)
  10980. {
  10981. const encoder = getBaseEncoder(type);
  10982. if (encoder) {
  10983. return callback(type, value);
  10984. }
  10985. }
  10986. // Array
  10987. const array = splitArray(type).array;
  10988. if (array) {
  10989. assertArgument(array.count === -1 || array.count === value.length, `array length mismatch; expected length ${array.count}`, "value", value);
  10990. return value.map((v) => this._visit(array.prefix, v, callback));
  10991. }
  10992. // Struct
  10993. const fields = this.types[type];
  10994. if (fields) {
  10995. return fields.reduce((accum, { name, type }) => {
  10996. accum[name] = this._visit(type, value[name], callback);
  10997. return accum;
  10998. }, {});
  10999. }
  11000. assertArgument(false, `unknown type: ${type}`, "type", type);
  11001. }
  11002. /**
  11003. * Call %%calback%% for each value in %%value%%, passing the type and
  11004. * component within %%value%%.
  11005. *
  11006. * This is useful for replacing addresses or other transformation that
  11007. * may be desired on each component, based on its type.
  11008. */
  11009. visit(value, callback) {
  11010. return this._visit(this.primaryType, value, callback);
  11011. }
  11012. /**
  11013. * Create a new **TypedDataEncoder** for %%types%%.
  11014. */
  11015. static from(types) {
  11016. return new TypedDataEncoder(types);
  11017. }
  11018. /**
  11019. * Return the primary type for %%types%%.
  11020. */
  11021. static getPrimaryType(types) {
  11022. return TypedDataEncoder.from(types).primaryType;
  11023. }
  11024. /**
  11025. * Return the hashed struct for %%value%% using %%types%% and %%name%%.
  11026. */
  11027. static hashStruct(name, types, value) {
  11028. return TypedDataEncoder.from(types).hashStruct(name, value);
  11029. }
  11030. /**
  11031. * Return the domain hash for %%domain%%.
  11032. */
  11033. static hashDomain(domain) {
  11034. const domainFields = [];
  11035. for (const name in domain) {
  11036. if (domain[name] == null) {
  11037. continue;
  11038. }
  11039. const type = domainFieldTypes[name];
  11040. assertArgument(type, `invalid typed-data domain key: ${JSON.stringify(name)}`, "domain", domain);
  11041. domainFields.push({ name, type });
  11042. }
  11043. domainFields.sort((a, b) => {
  11044. return domainFieldNames.indexOf(a.name) - domainFieldNames.indexOf(b.name);
  11045. });
  11046. return TypedDataEncoder.hashStruct("EIP712Domain", { EIP712Domain: domainFields }, domain);
  11047. }
  11048. /**
  11049. * Return the fully encoded [[link-eip-712]] %%value%% for %%types%% with %%domain%%.
  11050. */
  11051. static encode(domain, types, value) {
  11052. return concat([
  11053. "0x1901",
  11054. TypedDataEncoder.hashDomain(domain),
  11055. TypedDataEncoder.from(types).hash(value)
  11056. ]);
  11057. }
  11058. /**
  11059. * Return the hash of the fully encoded [[link-eip-712]] %%value%% for %%types%% with %%domain%%.
  11060. */
  11061. static hash(domain, types, value) {
  11062. return keccak256(TypedDataEncoder.encode(domain, types, value));
  11063. }
  11064. // Replaces all address types with ENS names with their looked up address
  11065. /**
  11066. * Resolves to the value from resolving all addresses in %%value%% for
  11067. * %%types%% and the %%domain%%.
  11068. */
  11069. static async resolveNames(domain, types, value, resolveName) {
  11070. // Make a copy to isolate it from the object passed in
  11071. domain = Object.assign({}, domain);
  11072. // Allow passing null to ignore value
  11073. for (const key in domain) {
  11074. if (domain[key] == null) {
  11075. delete domain[key];
  11076. }
  11077. }
  11078. // Look up all ENS names
  11079. const ensCache = {};
  11080. // Do we need to look up the domain's verifyingContract?
  11081. if (domain.verifyingContract && !isHexString(domain.verifyingContract, 20)) {
  11082. ensCache[domain.verifyingContract] = "0x";
  11083. }
  11084. // We are going to use the encoder to visit all the base values
  11085. const encoder = TypedDataEncoder.from(types);
  11086. // Get a list of all the addresses
  11087. encoder.visit(value, (type, value) => {
  11088. if (type === "address" && !isHexString(value, 20)) {
  11089. ensCache[value] = "0x";
  11090. }
  11091. return value;
  11092. });
  11093. // Lookup each name
  11094. for (const name in ensCache) {
  11095. ensCache[name] = await resolveName(name);
  11096. }
  11097. // Replace the domain verifyingContract if needed
  11098. if (domain.verifyingContract && ensCache[domain.verifyingContract]) {
  11099. domain.verifyingContract = ensCache[domain.verifyingContract];
  11100. }
  11101. // Replace all ENS names with their address
  11102. value = encoder.visit(value, (type, value) => {
  11103. if (type === "address" && ensCache[value]) {
  11104. return ensCache[value];
  11105. }
  11106. return value;
  11107. });
  11108. return { domain, value };
  11109. }
  11110. /**
  11111. * Returns the JSON-encoded payload expected by nodes which implement
  11112. * the JSON-RPC [[link-eip-712]] method.
  11113. */
  11114. static getPayload(domain, types, value) {
  11115. // Validate the domain fields
  11116. TypedDataEncoder.hashDomain(domain);
  11117. // Derive the EIP712Domain Struct reference type
  11118. const domainValues = {};
  11119. const domainTypes = [];
  11120. domainFieldNames.forEach((name) => {
  11121. const value = domain[name];
  11122. if (value == null) {
  11123. return;
  11124. }
  11125. domainValues[name] = domainChecks[name](value);
  11126. domainTypes.push({ name, type: domainFieldTypes[name] });
  11127. });
  11128. const encoder = TypedDataEncoder.from(types);
  11129. // Get the normalized types
  11130. types = encoder.types;
  11131. const typesWithDomain = Object.assign({}, types);
  11132. assertArgument(typesWithDomain.EIP712Domain == null, "types must not contain EIP712Domain type", "types.EIP712Domain", types);
  11133. typesWithDomain.EIP712Domain = domainTypes;
  11134. // Validate the data structures and types
  11135. encoder.encode(value);
  11136. return {
  11137. types: typesWithDomain,
  11138. domain: domainValues,
  11139. primaryType: encoder.primaryType,
  11140. message: encoder.visit(value, (type, value) => {
  11141. // bytes
  11142. if (type.match(/^bytes(\d*)/)) {
  11143. return hexlify(getBytes(value));
  11144. }
  11145. // uint or int
  11146. if (type.match(/^u?int/)) {
  11147. return getBigInt(value).toString();
  11148. }
  11149. switch (type) {
  11150. case "address":
  11151. return value.toLowerCase();
  11152. case "bool":
  11153. return !!value;
  11154. case "string":
  11155. assertArgument(typeof (value) === "string", "invalid string", "value", value);
  11156. return value;
  11157. }
  11158. assertArgument(false, "unsupported type", "type", type);
  11159. })
  11160. };
  11161. }
  11162. }
  11163. /**
  11164. * Compute the address used to sign the typed data for the %%signature%%.
  11165. */
  11166. function verifyTypedData(domain, types, value, signature) {
  11167. return recoverAddress(TypedDataEncoder.hash(domain, types, value), signature);
  11168. }
  11169. /**
  11170. * A fragment is a single item from an ABI, which may represent any of:
  11171. *
  11172. * - [Functions](FunctionFragment)
  11173. * - [Events](EventFragment)
  11174. * - [Constructors](ConstructorFragment)
  11175. * - Custom [Errors](ErrorFragment)
  11176. * - [Fallback or Receive](FallbackFragment) functions
  11177. *
  11178. * @_subsection api/abi/abi-coder:Fragments [about-fragments]
  11179. */
  11180. // [ "a", "b" ] => { "a": 1, "b": 1 }
  11181. function setify(items) {
  11182. const result = new Set();
  11183. items.forEach((k) => result.add(k));
  11184. return Object.freeze(result);
  11185. }
  11186. const _kwVisibDeploy = "external public payable override";
  11187. const KwVisibDeploy = setify(_kwVisibDeploy.split(" "));
  11188. // Visibility Keywords
  11189. const _kwVisib = "constant external internal payable private public pure view override";
  11190. const KwVisib = setify(_kwVisib.split(" "));
  11191. const _kwTypes = "constructor error event fallback function receive struct";
  11192. const KwTypes = setify(_kwTypes.split(" "));
  11193. const _kwModifiers = "calldata memory storage payable indexed";
  11194. const KwModifiers = setify(_kwModifiers.split(" "));
  11195. const _kwOther = "tuple returns";
  11196. // All Keywords
  11197. const _keywords = [_kwTypes, _kwModifiers, _kwOther, _kwVisib].join(" ");
  11198. const Keywords = setify(_keywords.split(" "));
  11199. // Single character tokens
  11200. const SimpleTokens = {
  11201. "(": "OPEN_PAREN", ")": "CLOSE_PAREN",
  11202. "[": "OPEN_BRACKET", "]": "CLOSE_BRACKET",
  11203. ",": "COMMA", "@": "AT"
  11204. };
  11205. // Parser regexes to consume the next token
  11206. const regexWhitespacePrefix = new RegExp("^(\\s*)");
  11207. const regexNumberPrefix = new RegExp("^([0-9]+)");
  11208. const regexIdPrefix = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)");
  11209. // Parser regexs to check validity
  11210. const regexId = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$");
  11211. const regexType = new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$");
  11212. class TokenString {
  11213. #offset;
  11214. #tokens;
  11215. get offset() { return this.#offset; }
  11216. get length() { return this.#tokens.length - this.#offset; }
  11217. constructor(tokens) {
  11218. this.#offset = 0;
  11219. this.#tokens = tokens.slice();
  11220. }
  11221. clone() { return new TokenString(this.#tokens); }
  11222. reset() { this.#offset = 0; }
  11223. #subTokenString(from = 0, to = 0) {
  11224. return new TokenString(this.#tokens.slice(from, to).map((t) => {
  11225. return Object.freeze(Object.assign({}, t, {
  11226. match: (t.match - from),
  11227. linkBack: (t.linkBack - from),
  11228. linkNext: (t.linkNext - from),
  11229. }));
  11230. }));
  11231. }
  11232. // Pops and returns the value of the next token, if it is a keyword in allowed; throws if out of tokens
  11233. popKeyword(allowed) {
  11234. const top = this.peek();
  11235. if (top.type !== "KEYWORD" || !allowed.has(top.text)) {
  11236. throw new Error(`expected keyword ${top.text}`);
  11237. }
  11238. return this.pop().text;
  11239. }
  11240. // Pops and returns the value of the next token if it is `type`; throws if out of tokens
  11241. popType(type) {
  11242. if (this.peek().type !== type) {
  11243. const top = this.peek();
  11244. throw new Error(`expected ${type}; got ${top.type} ${JSON.stringify(top.text)}`);
  11245. }
  11246. return this.pop().text;
  11247. }
  11248. // Pops and returns a "(" TOKENS ")"
  11249. popParen() {
  11250. const top = this.peek();
  11251. if (top.type !== "OPEN_PAREN") {
  11252. throw new Error("bad start");
  11253. }
  11254. const result = this.#subTokenString(this.#offset + 1, top.match + 1);
  11255. this.#offset = top.match + 1;
  11256. return result;
  11257. }
  11258. // Pops and returns the items within "(" ITEM1 "," ITEM2 "," ... ")"
  11259. popParams() {
  11260. const top = this.peek();
  11261. if (top.type !== "OPEN_PAREN") {
  11262. throw new Error("bad start");
  11263. }
  11264. const result = [];
  11265. while (this.#offset < top.match - 1) {
  11266. const link = this.peek().linkNext;
  11267. result.push(this.#subTokenString(this.#offset + 1, link));
  11268. this.#offset = link;
  11269. }
  11270. this.#offset = top.match + 1;
  11271. return result;
  11272. }
  11273. // Returns the top Token, throwing if out of tokens
  11274. peek() {
  11275. if (this.#offset >= this.#tokens.length) {
  11276. throw new Error("out-of-bounds");
  11277. }
  11278. return this.#tokens[this.#offset];
  11279. }
  11280. // Returns the next value, if it is a keyword in `allowed`
  11281. peekKeyword(allowed) {
  11282. const top = this.peekType("KEYWORD");
  11283. return (top != null && allowed.has(top)) ? top : null;
  11284. }
  11285. // Returns the value of the next token if it is `type`
  11286. peekType(type) {
  11287. if (this.length === 0) {
  11288. return null;
  11289. }
  11290. const top = this.peek();
  11291. return (top.type === type) ? top.text : null;
  11292. }
  11293. // Returns the next token; throws if out of tokens
  11294. pop() {
  11295. const result = this.peek();
  11296. this.#offset++;
  11297. return result;
  11298. }
  11299. toString() {
  11300. const tokens = [];
  11301. for (let i = this.#offset; i < this.#tokens.length; i++) {
  11302. const token = this.#tokens[i];
  11303. tokens.push(`${token.type}:${token.text}`);
  11304. }
  11305. return `<TokenString ${tokens.join(" ")}>`;
  11306. }
  11307. }
  11308. function lex(text) {
  11309. const tokens = [];
  11310. const throwError = (message) => {
  11311. const token = (offset < text.length) ? JSON.stringify(text[offset]) : "$EOI";
  11312. throw new Error(`invalid token ${token} at ${offset}: ${message}`);
  11313. };
  11314. let brackets = [];
  11315. let commas = [];
  11316. let offset = 0;
  11317. while (offset < text.length) {
  11318. // Strip off any leading whitespace
  11319. let cur = text.substring(offset);
  11320. let match = cur.match(regexWhitespacePrefix);
  11321. if (match) {
  11322. offset += match[1].length;
  11323. cur = text.substring(offset);
  11324. }
  11325. const token = { depth: brackets.length, linkBack: -1, linkNext: -1, match: -1, type: "", text: "", offset, value: -1 };
  11326. tokens.push(token);
  11327. let type = (SimpleTokens[cur[0]] || "");
  11328. if (type) {
  11329. token.type = type;
  11330. token.text = cur[0];
  11331. offset++;
  11332. if (type === "OPEN_PAREN") {
  11333. brackets.push(tokens.length - 1);
  11334. commas.push(tokens.length - 1);
  11335. }
  11336. else if (type == "CLOSE_PAREN") {
  11337. if (brackets.length === 0) {
  11338. throwError("no matching open bracket");
  11339. }
  11340. token.match = brackets.pop();
  11341. (tokens[token.match]).match = tokens.length - 1;
  11342. token.depth--;
  11343. token.linkBack = commas.pop();
  11344. (tokens[token.linkBack]).linkNext = tokens.length - 1;
  11345. }
  11346. else if (type === "COMMA") {
  11347. token.linkBack = commas.pop();
  11348. (tokens[token.linkBack]).linkNext = tokens.length - 1;
  11349. commas.push(tokens.length - 1);
  11350. }
  11351. else if (type === "OPEN_BRACKET") {
  11352. token.type = "BRACKET";
  11353. }
  11354. else if (type === "CLOSE_BRACKET") {
  11355. // Remove the CLOSE_BRACKET
  11356. let suffix = tokens.pop().text;
  11357. if (tokens.length > 0 && tokens[tokens.length - 1].type === "NUMBER") {
  11358. const value = tokens.pop().text;
  11359. suffix = value + suffix;
  11360. (tokens[tokens.length - 1]).value = getNumber(value);
  11361. }
  11362. if (tokens.length === 0 || tokens[tokens.length - 1].type !== "BRACKET") {
  11363. throw new Error("missing opening bracket");
  11364. }
  11365. (tokens[tokens.length - 1]).text += suffix;
  11366. }
  11367. continue;
  11368. }
  11369. match = cur.match(regexIdPrefix);
  11370. if (match) {
  11371. token.text = match[1];
  11372. offset += token.text.length;
  11373. if (Keywords.has(token.text)) {
  11374. token.type = "KEYWORD";
  11375. continue;
  11376. }
  11377. if (token.text.match(regexType)) {
  11378. token.type = "TYPE";
  11379. continue;
  11380. }
  11381. token.type = "ID";
  11382. continue;
  11383. }
  11384. match = cur.match(regexNumberPrefix);
  11385. if (match) {
  11386. token.text = match[1];
  11387. token.type = "NUMBER";
  11388. offset += token.text.length;
  11389. continue;
  11390. }
  11391. throw new Error(`unexpected token ${JSON.stringify(cur[0])} at position ${offset}`);
  11392. }
  11393. return new TokenString(tokens.map((t) => Object.freeze(t)));
  11394. }
  11395. // Check only one of `allowed` is in `set`
  11396. function allowSingle(set, allowed) {
  11397. let included = [];
  11398. for (const key in allowed.keys()) {
  11399. if (set.has(key)) {
  11400. included.push(key);
  11401. }
  11402. }
  11403. if (included.length > 1) {
  11404. throw new Error(`conflicting types: ${included.join(", ")}`);
  11405. }
  11406. }
  11407. // Functions to process a Solidity Signature TokenString from left-to-right for...
  11408. // ...the name with an optional type, returning the name
  11409. function consumeName(type, tokens) {
  11410. if (tokens.peekKeyword(KwTypes)) {
  11411. const keyword = tokens.pop().text;
  11412. if (keyword !== type) {
  11413. throw new Error(`expected ${type}, got ${keyword}`);
  11414. }
  11415. }
  11416. return tokens.popType("ID");
  11417. }
  11418. // ...all keywords matching allowed, returning the keywords
  11419. function consumeKeywords(tokens, allowed) {
  11420. const keywords = new Set();
  11421. while (true) {
  11422. const keyword = tokens.peekType("KEYWORD");
  11423. if (keyword == null || (allowed && !allowed.has(keyword))) {
  11424. break;
  11425. }
  11426. tokens.pop();
  11427. if (keywords.has(keyword)) {
  11428. throw new Error(`duplicate keywords: ${JSON.stringify(keyword)}`);
  11429. }
  11430. keywords.add(keyword);
  11431. }
  11432. return Object.freeze(keywords);
  11433. }
  11434. // ...all visibility keywords, returning the coalesced mutability
  11435. function consumeMutability(tokens) {
  11436. let modifiers = consumeKeywords(tokens, KwVisib);
  11437. // Detect conflicting modifiers
  11438. allowSingle(modifiers, setify("constant payable nonpayable".split(" ")));
  11439. allowSingle(modifiers, setify("pure view payable nonpayable".split(" ")));
  11440. // Process mutability states
  11441. if (modifiers.has("view")) {
  11442. return "view";
  11443. }
  11444. if (modifiers.has("pure")) {
  11445. return "pure";
  11446. }
  11447. if (modifiers.has("payable")) {
  11448. return "payable";
  11449. }
  11450. if (modifiers.has("nonpayable")) {
  11451. return "nonpayable";
  11452. }
  11453. // Process legacy `constant` last
  11454. if (modifiers.has("constant")) {
  11455. return "view";
  11456. }
  11457. return "nonpayable";
  11458. }
  11459. // ...a parameter list, returning the ParamType list
  11460. function consumeParams(tokens, allowIndexed) {
  11461. return tokens.popParams().map((t) => ParamType.from(t, allowIndexed));
  11462. }
  11463. // ...a gas limit, returning a BigNumber or null if none
  11464. function consumeGas(tokens) {
  11465. if (tokens.peekType("AT")) {
  11466. tokens.pop();
  11467. if (tokens.peekType("NUMBER")) {
  11468. return getBigInt(tokens.pop().text);
  11469. }
  11470. throw new Error("invalid gas");
  11471. }
  11472. return null;
  11473. }
  11474. function consumeEoi(tokens) {
  11475. if (tokens.length) {
  11476. throw new Error(`unexpected tokens at offset ${tokens.offset}: ${tokens.toString()}`);
  11477. }
  11478. }
  11479. const regexArrayType = new RegExp(/^(.*)\[([0-9]*)\]$/);
  11480. function verifyBasicType(type) {
  11481. const match = type.match(regexType);
  11482. assertArgument(match, "invalid type", "type", type);
  11483. if (type === "uint") {
  11484. return "uint256";
  11485. }
  11486. if (type === "int") {
  11487. return "int256";
  11488. }
  11489. if (match[2]) {
  11490. // bytesXX
  11491. const length = parseInt(match[2]);
  11492. assertArgument(length !== 0 && length <= 32, "invalid bytes length", "type", type);
  11493. }
  11494. else if (match[3]) {
  11495. // intXX or uintXX
  11496. const size = parseInt(match[3]);
  11497. assertArgument(size !== 0 && size <= 256 && (size % 8) === 0, "invalid numeric width", "type", type);
  11498. }
  11499. return type;
  11500. }
  11501. // Make the Fragment constructors effectively private
  11502. const _guard$2 = {};
  11503. const internal$1 = Symbol.for("_ethers_internal");
  11504. const ParamTypeInternal = "_ParamTypeInternal";
  11505. const ErrorFragmentInternal = "_ErrorInternal";
  11506. const EventFragmentInternal = "_EventInternal";
  11507. const ConstructorFragmentInternal = "_ConstructorInternal";
  11508. const FallbackFragmentInternal = "_FallbackInternal";
  11509. const FunctionFragmentInternal = "_FunctionInternal";
  11510. const StructFragmentInternal = "_StructInternal";
  11511. /**
  11512. * Each input and output of a [[Fragment]] is an Array of **ParamType**.
  11513. */
  11514. class ParamType {
  11515. /**
  11516. * The local name of the parameter (or ``""`` if unbound)
  11517. */
  11518. name;
  11519. /**
  11520. * The fully qualified type (e.g. ``"address"``, ``"tuple(address)"``,
  11521. * ``"uint256[3][]"``)
  11522. */
  11523. type;
  11524. /**
  11525. * The base type (e.g. ``"address"``, ``"tuple"``, ``"array"``)
  11526. */
  11527. baseType;
  11528. /**
  11529. * True if the parameters is indexed.
  11530. *
  11531. * For non-indexable types this is ``null``.
  11532. */
  11533. indexed;
  11534. /**
  11535. * The components for the tuple.
  11536. *
  11537. * For non-tuple types this is ``null``.
  11538. */
  11539. components;
  11540. /**
  11541. * The array length, or ``-1`` for dynamic-lengthed arrays.
  11542. *
  11543. * For non-array types this is ``null``.
  11544. */
  11545. arrayLength;
  11546. /**
  11547. * The type of each child in the array.
  11548. *
  11549. * For non-array types this is ``null``.
  11550. */
  11551. arrayChildren;
  11552. /**
  11553. * @private
  11554. */
  11555. constructor(guard, name, type, baseType, indexed, components, arrayLength, arrayChildren) {
  11556. assertPrivate(guard, _guard$2, "ParamType");
  11557. Object.defineProperty(this, internal$1, { value: ParamTypeInternal });
  11558. if (components) {
  11559. components = Object.freeze(components.slice());
  11560. }
  11561. if (baseType === "array") {
  11562. if (arrayLength == null || arrayChildren == null) {
  11563. throw new Error("");
  11564. }
  11565. }
  11566. else if (arrayLength != null || arrayChildren != null) {
  11567. throw new Error("");
  11568. }
  11569. if (baseType === "tuple") {
  11570. if (components == null) {
  11571. throw new Error("");
  11572. }
  11573. }
  11574. else if (components != null) {
  11575. throw new Error("");
  11576. }
  11577. defineProperties(this, {
  11578. name, type, baseType, indexed, components, arrayLength, arrayChildren
  11579. });
  11580. }
  11581. /**
  11582. * Return a string representation of this type.
  11583. *
  11584. * For example,
  11585. *
  11586. * ``sighash" => "(uint256,address)"``
  11587. *
  11588. * ``"minimal" => "tuple(uint256,address) indexed"``
  11589. *
  11590. * ``"full" => "tuple(uint256 foo, address bar) indexed baz"``
  11591. */
  11592. format(format) {
  11593. if (format == null) {
  11594. format = "sighash";
  11595. }
  11596. if (format === "json") {
  11597. const name = this.name || "";
  11598. if (this.isArray()) {
  11599. const result = JSON.parse(this.arrayChildren.format("json"));
  11600. result.name = name;
  11601. result.type += `[${(this.arrayLength < 0 ? "" : String(this.arrayLength))}]`;
  11602. return JSON.stringify(result);
  11603. }
  11604. const result = {
  11605. type: ((this.baseType === "tuple") ? "tuple" : this.type),
  11606. name
  11607. };
  11608. if (typeof (this.indexed) === "boolean") {
  11609. result.indexed = this.indexed;
  11610. }
  11611. if (this.isTuple()) {
  11612. result.components = this.components.map((c) => JSON.parse(c.format(format)));
  11613. }
  11614. return JSON.stringify(result);
  11615. }
  11616. let result = "";
  11617. // Array
  11618. if (this.isArray()) {
  11619. result += this.arrayChildren.format(format);
  11620. result += `[${(this.arrayLength < 0 ? "" : String(this.arrayLength))}]`;
  11621. }
  11622. else {
  11623. if (this.isTuple()) {
  11624. result += "(" + this.components.map((comp) => comp.format(format)).join((format === "full") ? ", " : ",") + ")";
  11625. }
  11626. else {
  11627. result += this.type;
  11628. }
  11629. }
  11630. if (format !== "sighash") {
  11631. if (this.indexed === true) {
  11632. result += " indexed";
  11633. }
  11634. if (format === "full" && this.name) {
  11635. result += " " + this.name;
  11636. }
  11637. }
  11638. return result;
  11639. }
  11640. /**
  11641. * Returns true if %%this%% is an Array type.
  11642. *
  11643. * This provides a type gaurd ensuring that [[arrayChildren]]
  11644. * and [[arrayLength]] are non-null.
  11645. */
  11646. isArray() {
  11647. return (this.baseType === "array");
  11648. }
  11649. /**
  11650. * Returns true if %%this%% is a Tuple type.
  11651. *
  11652. * This provides a type gaurd ensuring that [[components]]
  11653. * is non-null.
  11654. */
  11655. isTuple() {
  11656. return (this.baseType === "tuple");
  11657. }
  11658. /**
  11659. * Returns true if %%this%% is an Indexable type.
  11660. *
  11661. * This provides a type gaurd ensuring that [[indexed]]
  11662. * is non-null.
  11663. */
  11664. isIndexable() {
  11665. return (this.indexed != null);
  11666. }
  11667. /**
  11668. * Walks the **ParamType** with %%value%%, calling %%process%%
  11669. * on each type, destructing the %%value%% recursively.
  11670. */
  11671. walk(value, process) {
  11672. if (this.isArray()) {
  11673. if (!Array.isArray(value)) {
  11674. throw new Error("invalid array value");
  11675. }
  11676. if (this.arrayLength !== -1 && value.length !== this.arrayLength) {
  11677. throw new Error("array is wrong length");
  11678. }
  11679. const _this = this;
  11680. return value.map((v) => (_this.arrayChildren.walk(v, process)));
  11681. }
  11682. if (this.isTuple()) {
  11683. if (!Array.isArray(value)) {
  11684. throw new Error("invalid tuple value");
  11685. }
  11686. if (value.length !== this.components.length) {
  11687. throw new Error("array is wrong length");
  11688. }
  11689. const _this = this;
  11690. return value.map((v, i) => (_this.components[i].walk(v, process)));
  11691. }
  11692. return process(this.type, value);
  11693. }
  11694. #walkAsync(promises, value, process, setValue) {
  11695. if (this.isArray()) {
  11696. if (!Array.isArray(value)) {
  11697. throw new Error("invalid array value");
  11698. }
  11699. if (this.arrayLength !== -1 && value.length !== this.arrayLength) {
  11700. throw new Error("array is wrong length");
  11701. }
  11702. const childType = this.arrayChildren;
  11703. const result = value.slice();
  11704. result.forEach((value, index) => {
  11705. childType.#walkAsync(promises, value, process, (value) => {
  11706. result[index] = value;
  11707. });
  11708. });
  11709. setValue(result);
  11710. return;
  11711. }
  11712. if (this.isTuple()) {
  11713. const components = this.components;
  11714. // Convert the object into an array
  11715. let result;
  11716. if (Array.isArray(value)) {
  11717. result = value.slice();
  11718. }
  11719. else {
  11720. if (value == null || typeof (value) !== "object") {
  11721. throw new Error("invalid tuple value");
  11722. }
  11723. result = components.map((param) => {
  11724. if (!param.name) {
  11725. throw new Error("cannot use object value with unnamed components");
  11726. }
  11727. if (!(param.name in value)) {
  11728. throw new Error(`missing value for component ${param.name}`);
  11729. }
  11730. return value[param.name];
  11731. });
  11732. }
  11733. if (result.length !== this.components.length) {
  11734. throw new Error("array is wrong length");
  11735. }
  11736. result.forEach((value, index) => {
  11737. components[index].#walkAsync(promises, value, process, (value) => {
  11738. result[index] = value;
  11739. });
  11740. });
  11741. setValue(result);
  11742. return;
  11743. }
  11744. const result = process(this.type, value);
  11745. if (result.then) {
  11746. promises.push((async function () { setValue(await result); })());
  11747. }
  11748. else {
  11749. setValue(result);
  11750. }
  11751. }
  11752. /**
  11753. * Walks the **ParamType** with %%value%%, asynchronously calling
  11754. * %%process%% on each type, destructing the %%value%% recursively.
  11755. *
  11756. * This can be used to resolve ENS names by walking and resolving each
  11757. * ``"address"`` type.
  11758. */
  11759. async walkAsync(value, process) {
  11760. const promises = [];
  11761. const result = [value];
  11762. this.#walkAsync(promises, value, process, (value) => {
  11763. result[0] = value;
  11764. });
  11765. if (promises.length) {
  11766. await Promise.all(promises);
  11767. }
  11768. return result[0];
  11769. }
  11770. /**
  11771. * Creates a new **ParamType** for %%obj%%.
  11772. *
  11773. * If %%allowIndexed%% then the ``indexed`` keyword is permitted,
  11774. * otherwise the ``indexed`` keyword will throw an error.
  11775. */
  11776. static from(obj, allowIndexed) {
  11777. if (ParamType.isParamType(obj)) {
  11778. return obj;
  11779. }
  11780. if (typeof (obj) === "string") {
  11781. try {
  11782. return ParamType.from(lex(obj), allowIndexed);
  11783. }
  11784. catch (error) {
  11785. assertArgument(false, "invalid param type", "obj", obj);
  11786. }
  11787. }
  11788. else if (obj instanceof TokenString) {
  11789. let type = "", baseType = "";
  11790. let comps = null;
  11791. if (consumeKeywords(obj, setify(["tuple"])).has("tuple") || obj.peekType("OPEN_PAREN")) {
  11792. // Tuple
  11793. baseType = "tuple";
  11794. comps = obj.popParams().map((t) => ParamType.from(t));
  11795. type = `tuple(${comps.map((c) => c.format()).join(",")})`;
  11796. }
  11797. else {
  11798. // Normal
  11799. type = verifyBasicType(obj.popType("TYPE"));
  11800. baseType = type;
  11801. }
  11802. // Check for Array
  11803. let arrayChildren = null;
  11804. let arrayLength = null;
  11805. while (obj.length && obj.peekType("BRACKET")) {
  11806. const bracket = obj.pop(); //arrays[i];
  11807. arrayChildren = new ParamType(_guard$2, "", type, baseType, null, comps, arrayLength, arrayChildren);
  11808. arrayLength = bracket.value;
  11809. type += bracket.text;
  11810. baseType = "array";
  11811. comps = null;
  11812. }
  11813. let indexed = null;
  11814. const keywords = consumeKeywords(obj, KwModifiers);
  11815. if (keywords.has("indexed")) {
  11816. if (!allowIndexed) {
  11817. throw new Error("");
  11818. }
  11819. indexed = true;
  11820. }
  11821. const name = (obj.peekType("ID") ? obj.pop().text : "");
  11822. if (obj.length) {
  11823. throw new Error("leftover tokens");
  11824. }
  11825. return new ParamType(_guard$2, name, type, baseType, indexed, comps, arrayLength, arrayChildren);
  11826. }
  11827. const name = obj.name;
  11828. assertArgument(!name || (typeof (name) === "string" && name.match(regexId)), "invalid name", "obj.name", name);
  11829. let indexed = obj.indexed;
  11830. if (indexed != null) {
  11831. assertArgument(allowIndexed, "parameter cannot be indexed", "obj.indexed", obj.indexed);
  11832. indexed = !!indexed;
  11833. }
  11834. let type = obj.type;
  11835. let arrayMatch = type.match(regexArrayType);
  11836. if (arrayMatch) {
  11837. const arrayLength = parseInt(arrayMatch[2] || "-1");
  11838. const arrayChildren = ParamType.from({
  11839. type: arrayMatch[1],
  11840. components: obj.components
  11841. });
  11842. return new ParamType(_guard$2, name || "", type, "array", indexed, null, arrayLength, arrayChildren);
  11843. }
  11844. if (type === "tuple" || type.startsWith("tuple(" /* fix: ) */) || type.startsWith("(" /* fix: ) */)) {
  11845. const comps = (obj.components != null) ? obj.components.map((c) => ParamType.from(c)) : null;
  11846. const tuple = new ParamType(_guard$2, name || "", type, "tuple", indexed, comps, null, null);
  11847. // @TODO: use lexer to validate and normalize type
  11848. return tuple;
  11849. }
  11850. type = verifyBasicType(obj.type);
  11851. return new ParamType(_guard$2, name || "", type, type, indexed, null, null, null);
  11852. }
  11853. /**
  11854. * Returns true if %%value%% is a **ParamType**.
  11855. */
  11856. static isParamType(value) {
  11857. return (value && value[internal$1] === ParamTypeInternal);
  11858. }
  11859. }
  11860. /**
  11861. * An abstract class to represent An individual fragment from a parse ABI.
  11862. */
  11863. class Fragment {
  11864. /**
  11865. * The type of the fragment.
  11866. */
  11867. type;
  11868. /**
  11869. * The inputs for the fragment.
  11870. */
  11871. inputs;
  11872. /**
  11873. * @private
  11874. */
  11875. constructor(guard, type, inputs) {
  11876. assertPrivate(guard, _guard$2, "Fragment");
  11877. inputs = Object.freeze(inputs.slice());
  11878. defineProperties(this, { type, inputs });
  11879. }
  11880. /**
  11881. * Creates a new **Fragment** for %%obj%%, wich can be any supported
  11882. * ABI frgament type.
  11883. */
  11884. static from(obj) {
  11885. if (typeof (obj) === "string") {
  11886. // Try parsing JSON...
  11887. try {
  11888. Fragment.from(JSON.parse(obj));
  11889. }
  11890. catch (e) { }
  11891. // ...otherwise, use the human-readable lexer
  11892. return Fragment.from(lex(obj));
  11893. }
  11894. if (obj instanceof TokenString) {
  11895. // Human-readable ABI (already lexed)
  11896. const type = obj.peekKeyword(KwTypes);
  11897. switch (type) {
  11898. case "constructor": return ConstructorFragment.from(obj);
  11899. case "error": return ErrorFragment.from(obj);
  11900. case "event": return EventFragment.from(obj);
  11901. case "fallback":
  11902. case "receive":
  11903. return FallbackFragment.from(obj);
  11904. case "function": return FunctionFragment.from(obj);
  11905. case "struct": return StructFragment.from(obj);
  11906. }
  11907. }
  11908. else if (typeof (obj) === "object") {
  11909. // JSON ABI
  11910. switch (obj.type) {
  11911. case "constructor": return ConstructorFragment.from(obj);
  11912. case "error": return ErrorFragment.from(obj);
  11913. case "event": return EventFragment.from(obj);
  11914. case "fallback":
  11915. case "receive":
  11916. return FallbackFragment.from(obj);
  11917. case "function": return FunctionFragment.from(obj);
  11918. case "struct": return StructFragment.from(obj);
  11919. }
  11920. assert(false, `unsupported type: ${obj.type}`, "UNSUPPORTED_OPERATION", {
  11921. operation: "Fragment.from"
  11922. });
  11923. }
  11924. assertArgument(false, "unsupported frgament object", "obj", obj);
  11925. }
  11926. /**
  11927. * Returns true if %%value%% is a [[ConstructorFragment]].
  11928. */
  11929. static isConstructor(value) {
  11930. return ConstructorFragment.isFragment(value);
  11931. }
  11932. /**
  11933. * Returns true if %%value%% is an [[ErrorFragment]].
  11934. */
  11935. static isError(value) {
  11936. return ErrorFragment.isFragment(value);
  11937. }
  11938. /**
  11939. * Returns true if %%value%% is an [[EventFragment]].
  11940. */
  11941. static isEvent(value) {
  11942. return EventFragment.isFragment(value);
  11943. }
  11944. /**
  11945. * Returns true if %%value%% is a [[FunctionFragment]].
  11946. */
  11947. static isFunction(value) {
  11948. return FunctionFragment.isFragment(value);
  11949. }
  11950. /**
  11951. * Returns true if %%value%% is a [[StructFragment]].
  11952. */
  11953. static isStruct(value) {
  11954. return StructFragment.isFragment(value);
  11955. }
  11956. }
  11957. /**
  11958. * An abstract class to represent An individual fragment
  11959. * which has a name from a parse ABI.
  11960. */
  11961. class NamedFragment extends Fragment {
  11962. /**
  11963. * The name of the fragment.
  11964. */
  11965. name;
  11966. /**
  11967. * @private
  11968. */
  11969. constructor(guard, type, name, inputs) {
  11970. super(guard, type, inputs);
  11971. assertArgument(typeof (name) === "string" && name.match(regexId), "invalid identifier", "name", name);
  11972. inputs = Object.freeze(inputs.slice());
  11973. defineProperties(this, { name });
  11974. }
  11975. }
  11976. function joinParams(format, params) {
  11977. return "(" + params.map((p) => p.format(format)).join((format === "full") ? ", " : ",") + ")";
  11978. }
  11979. /**
  11980. * A Fragment which represents a //Custom Error//.
  11981. */
  11982. class ErrorFragment extends NamedFragment {
  11983. /**
  11984. * @private
  11985. */
  11986. constructor(guard, name, inputs) {
  11987. super(guard, "error", name, inputs);
  11988. Object.defineProperty(this, internal$1, { value: ErrorFragmentInternal });
  11989. }
  11990. /**
  11991. * The Custom Error selector.
  11992. */
  11993. get selector() {
  11994. return id(this.format("sighash")).substring(0, 10);
  11995. }
  11996. /**
  11997. * Returns a string representation of this fragment as %%format%%.
  11998. */
  11999. format(format) {
  12000. if (format == null) {
  12001. format = "sighash";
  12002. }
  12003. if (format === "json") {
  12004. return JSON.stringify({
  12005. type: "error",
  12006. name: this.name,
  12007. inputs: this.inputs.map((input) => JSON.parse(input.format(format))),
  12008. });
  12009. }
  12010. const result = [];
  12011. if (format !== "sighash") {
  12012. result.push("error");
  12013. }
  12014. result.push(this.name + joinParams(format, this.inputs));
  12015. return result.join(" ");
  12016. }
  12017. /**
  12018. * Returns a new **ErrorFragment** for %%obj%%.
  12019. */
  12020. static from(obj) {
  12021. if (ErrorFragment.isFragment(obj)) {
  12022. return obj;
  12023. }
  12024. if (typeof (obj) === "string") {
  12025. return ErrorFragment.from(lex(obj));
  12026. }
  12027. else if (obj instanceof TokenString) {
  12028. const name = consumeName("error", obj);
  12029. const inputs = consumeParams(obj);
  12030. consumeEoi(obj);
  12031. return new ErrorFragment(_guard$2, name, inputs);
  12032. }
  12033. return new ErrorFragment(_guard$2, obj.name, obj.inputs ? obj.inputs.map(ParamType.from) : []);
  12034. }
  12035. /**
  12036. * Returns ``true`` and provides a type guard if %%value%% is an
  12037. * **ErrorFragment**.
  12038. */
  12039. static isFragment(value) {
  12040. return (value && value[internal$1] === ErrorFragmentInternal);
  12041. }
  12042. }
  12043. /**
  12044. * A Fragment which represents an Event.
  12045. */
  12046. class EventFragment extends NamedFragment {
  12047. /**
  12048. * Whether this event is anonymous.
  12049. */
  12050. anonymous;
  12051. /**
  12052. * @private
  12053. */
  12054. constructor(guard, name, inputs, anonymous) {
  12055. super(guard, "event", name, inputs);
  12056. Object.defineProperty(this, internal$1, { value: EventFragmentInternal });
  12057. defineProperties(this, { anonymous });
  12058. }
  12059. /**
  12060. * The Event topic hash.
  12061. */
  12062. get topicHash() {
  12063. return id(this.format("sighash"));
  12064. }
  12065. /**
  12066. * Returns a string representation of this event as %%format%%.
  12067. */
  12068. format(format) {
  12069. if (format == null) {
  12070. format = "sighash";
  12071. }
  12072. if (format === "json") {
  12073. return JSON.stringify({
  12074. type: "event",
  12075. anonymous: this.anonymous,
  12076. name: this.name,
  12077. inputs: this.inputs.map((i) => JSON.parse(i.format(format)))
  12078. });
  12079. }
  12080. const result = [];
  12081. if (format !== "sighash") {
  12082. result.push("event");
  12083. }
  12084. result.push(this.name + joinParams(format, this.inputs));
  12085. if (format !== "sighash" && this.anonymous) {
  12086. result.push("anonymous");
  12087. }
  12088. return result.join(" ");
  12089. }
  12090. /**
  12091. * Return the topic hash for an event with %%name%% and %%params%%.
  12092. */
  12093. static getTopicHash(name, params) {
  12094. params = (params || []).map((p) => ParamType.from(p));
  12095. const fragment = new EventFragment(_guard$2, name, params, false);
  12096. return fragment.topicHash;
  12097. }
  12098. /**
  12099. * Returns a new **EventFragment** for %%obj%%.
  12100. */
  12101. static from(obj) {
  12102. if (EventFragment.isFragment(obj)) {
  12103. return obj;
  12104. }
  12105. if (typeof (obj) === "string") {
  12106. try {
  12107. return EventFragment.from(lex(obj));
  12108. }
  12109. catch (error) {
  12110. assertArgument(false, "invalid event fragment", "obj", obj);
  12111. }
  12112. }
  12113. else if (obj instanceof TokenString) {
  12114. const name = consumeName("event", obj);
  12115. const inputs = consumeParams(obj, true);
  12116. const anonymous = !!consumeKeywords(obj, setify(["anonymous"])).has("anonymous");
  12117. consumeEoi(obj);
  12118. return new EventFragment(_guard$2, name, inputs, anonymous);
  12119. }
  12120. return new EventFragment(_guard$2, obj.name, obj.inputs ? obj.inputs.map((p) => ParamType.from(p, true)) : [], !!obj.anonymous);
  12121. }
  12122. /**
  12123. * Returns ``true`` and provides a type guard if %%value%% is an
  12124. * **EventFragment**.
  12125. */
  12126. static isFragment(value) {
  12127. return (value && value[internal$1] === EventFragmentInternal);
  12128. }
  12129. }
  12130. /**
  12131. * A Fragment which represents a constructor.
  12132. */
  12133. class ConstructorFragment extends Fragment {
  12134. /**
  12135. * Whether the constructor can receive an endowment.
  12136. */
  12137. payable;
  12138. /**
  12139. * The recommended gas limit for deployment or ``null``.
  12140. */
  12141. gas;
  12142. /**
  12143. * @private
  12144. */
  12145. constructor(guard, type, inputs, payable, gas) {
  12146. super(guard, type, inputs);
  12147. Object.defineProperty(this, internal$1, { value: ConstructorFragmentInternal });
  12148. defineProperties(this, { payable, gas });
  12149. }
  12150. /**
  12151. * Returns a string representation of this constructor as %%format%%.
  12152. */
  12153. format(format) {
  12154. assert(format != null && format !== "sighash", "cannot format a constructor for sighash", "UNSUPPORTED_OPERATION", { operation: "format(sighash)" });
  12155. if (format === "json") {
  12156. return JSON.stringify({
  12157. type: "constructor",
  12158. stateMutability: (this.payable ? "payable" : "undefined"),
  12159. payable: this.payable,
  12160. gas: ((this.gas != null) ? this.gas : undefined),
  12161. inputs: this.inputs.map((i) => JSON.parse(i.format(format)))
  12162. });
  12163. }
  12164. const result = [`constructor${joinParams(format, this.inputs)}`];
  12165. if (this.payable) {
  12166. result.push("payable");
  12167. }
  12168. if (this.gas != null) {
  12169. result.push(`@${this.gas.toString()}`);
  12170. }
  12171. return result.join(" ");
  12172. }
  12173. /**
  12174. * Returns a new **ConstructorFragment** for %%obj%%.
  12175. */
  12176. static from(obj) {
  12177. if (ConstructorFragment.isFragment(obj)) {
  12178. return obj;
  12179. }
  12180. if (typeof (obj) === "string") {
  12181. try {
  12182. return ConstructorFragment.from(lex(obj));
  12183. }
  12184. catch (error) {
  12185. assertArgument(false, "invalid constuctor fragment", "obj", obj);
  12186. }
  12187. }
  12188. else if (obj instanceof TokenString) {
  12189. consumeKeywords(obj, setify(["constructor"]));
  12190. const inputs = consumeParams(obj);
  12191. const payable = !!consumeKeywords(obj, KwVisibDeploy).has("payable");
  12192. const gas = consumeGas(obj);
  12193. consumeEoi(obj);
  12194. return new ConstructorFragment(_guard$2, "constructor", inputs, payable, gas);
  12195. }
  12196. return new ConstructorFragment(_guard$2, "constructor", obj.inputs ? obj.inputs.map(ParamType.from) : [], !!obj.payable, (obj.gas != null) ? obj.gas : null);
  12197. }
  12198. /**
  12199. * Returns ``true`` and provides a type guard if %%value%% is a
  12200. * **ConstructorFragment**.
  12201. */
  12202. static isFragment(value) {
  12203. return (value && value[internal$1] === ConstructorFragmentInternal);
  12204. }
  12205. }
  12206. /**
  12207. * A Fragment which represents a method.
  12208. */
  12209. class FallbackFragment extends Fragment {
  12210. /**
  12211. * If the function can be sent value during invocation.
  12212. */
  12213. payable;
  12214. constructor(guard, inputs, payable) {
  12215. super(guard, "fallback", inputs);
  12216. Object.defineProperty(this, internal$1, { value: FallbackFragmentInternal });
  12217. defineProperties(this, { payable });
  12218. }
  12219. /**
  12220. * Returns a string representation of this fallback as %%format%%.
  12221. */
  12222. format(format) {
  12223. const type = ((this.inputs.length === 0) ? "receive" : "fallback");
  12224. if (format === "json") {
  12225. const stateMutability = (this.payable ? "payable" : "nonpayable");
  12226. return JSON.stringify({ type, stateMutability });
  12227. }
  12228. return `${type}()${this.payable ? " payable" : ""}`;
  12229. }
  12230. /**
  12231. * Returns a new **FallbackFragment** for %%obj%%.
  12232. */
  12233. static from(obj) {
  12234. if (FallbackFragment.isFragment(obj)) {
  12235. return obj;
  12236. }
  12237. if (typeof (obj) === "string") {
  12238. try {
  12239. return FallbackFragment.from(lex(obj));
  12240. }
  12241. catch (error) {
  12242. assertArgument(false, "invalid fallback fragment", "obj", obj);
  12243. }
  12244. }
  12245. else if (obj instanceof TokenString) {
  12246. const errorObj = obj.toString();
  12247. const topIsValid = obj.peekKeyword(setify(["fallback", "receive"]));
  12248. assertArgument(topIsValid, "type must be fallback or receive", "obj", errorObj);
  12249. const type = obj.popKeyword(setify(["fallback", "receive"]));
  12250. // receive()
  12251. if (type === "receive") {
  12252. const inputs = consumeParams(obj);
  12253. assertArgument(inputs.length === 0, `receive cannot have arguments`, "obj.inputs", inputs);
  12254. consumeKeywords(obj, setify(["payable"]));
  12255. consumeEoi(obj);
  12256. return new FallbackFragment(_guard$2, [], true);
  12257. }
  12258. // fallback() [payable]
  12259. // fallback(bytes) [payable] returns (bytes)
  12260. let inputs = consumeParams(obj);
  12261. if (inputs.length) {
  12262. assertArgument(inputs.length === 1 && inputs[0].type === "bytes", "invalid fallback inputs", "obj.inputs", inputs.map((i) => i.format("minimal")).join(", "));
  12263. }
  12264. else {
  12265. inputs = [ParamType.from("bytes")];
  12266. }
  12267. const mutability = consumeMutability(obj);
  12268. assertArgument(mutability === "nonpayable" || mutability === "payable", "fallback cannot be constants", "obj.stateMutability", mutability);
  12269. if (consumeKeywords(obj, setify(["returns"])).has("returns")) {
  12270. const outputs = consumeParams(obj);
  12271. assertArgument(outputs.length === 1 && outputs[0].type === "bytes", "invalid fallback outputs", "obj.outputs", outputs.map((i) => i.format("minimal")).join(", "));
  12272. }
  12273. consumeEoi(obj);
  12274. return new FallbackFragment(_guard$2, inputs, mutability === "payable");
  12275. }
  12276. if (obj.type === "receive") {
  12277. return new FallbackFragment(_guard$2, [], true);
  12278. }
  12279. if (obj.type === "fallback") {
  12280. const inputs = [ParamType.from("bytes")];
  12281. const payable = (obj.stateMutability === "payable");
  12282. return new FallbackFragment(_guard$2, inputs, payable);
  12283. }
  12284. assertArgument(false, "invalid fallback description", "obj", obj);
  12285. }
  12286. /**
  12287. * Returns ``true`` and provides a type guard if %%value%% is a
  12288. * **FallbackFragment**.
  12289. */
  12290. static isFragment(value) {
  12291. return (value && value[internal$1] === FallbackFragmentInternal);
  12292. }
  12293. }
  12294. /**
  12295. * A Fragment which represents a method.
  12296. */
  12297. class FunctionFragment extends NamedFragment {
  12298. /**
  12299. * If the function is constant (e.g. ``pure`` or ``view`` functions).
  12300. */
  12301. constant;
  12302. /**
  12303. * The returned types for the result of calling this function.
  12304. */
  12305. outputs;
  12306. /**
  12307. * The state mutability (e.g. ``payable``, ``nonpayable``, ``view``
  12308. * or ``pure``)
  12309. */
  12310. stateMutability;
  12311. /**
  12312. * If the function can be sent value during invocation.
  12313. */
  12314. payable;
  12315. /**
  12316. * The recommended gas limit to send when calling this function.
  12317. */
  12318. gas;
  12319. /**
  12320. * @private
  12321. */
  12322. constructor(guard, name, stateMutability, inputs, outputs, gas) {
  12323. super(guard, "function", name, inputs);
  12324. Object.defineProperty(this, internal$1, { value: FunctionFragmentInternal });
  12325. outputs = Object.freeze(outputs.slice());
  12326. const constant = (stateMutability === "view" || stateMutability === "pure");
  12327. const payable = (stateMutability === "payable");
  12328. defineProperties(this, { constant, gas, outputs, payable, stateMutability });
  12329. }
  12330. /**
  12331. * The Function selector.
  12332. */
  12333. get selector() {
  12334. return id(this.format("sighash")).substring(0, 10);
  12335. }
  12336. /**
  12337. * Returns a string representation of this function as %%format%%.
  12338. */
  12339. format(format) {
  12340. if (format == null) {
  12341. format = "sighash";
  12342. }
  12343. if (format === "json") {
  12344. return JSON.stringify({
  12345. type: "function",
  12346. name: this.name,
  12347. constant: this.constant,
  12348. stateMutability: ((this.stateMutability !== "nonpayable") ? this.stateMutability : undefined),
  12349. payable: this.payable,
  12350. gas: ((this.gas != null) ? this.gas : undefined),
  12351. inputs: this.inputs.map((i) => JSON.parse(i.format(format))),
  12352. outputs: this.outputs.map((o) => JSON.parse(o.format(format))),
  12353. });
  12354. }
  12355. const result = [];
  12356. if (format !== "sighash") {
  12357. result.push("function");
  12358. }
  12359. result.push(this.name + joinParams(format, this.inputs));
  12360. if (format !== "sighash") {
  12361. if (this.stateMutability !== "nonpayable") {
  12362. result.push(this.stateMutability);
  12363. }
  12364. if (this.outputs && this.outputs.length) {
  12365. result.push("returns");
  12366. result.push(joinParams(format, this.outputs));
  12367. }
  12368. if (this.gas != null) {
  12369. result.push(`@${this.gas.toString()}`);
  12370. }
  12371. }
  12372. return result.join(" ");
  12373. }
  12374. /**
  12375. * Return the selector for a function with %%name%% and %%params%%.
  12376. */
  12377. static getSelector(name, params) {
  12378. params = (params || []).map((p) => ParamType.from(p));
  12379. const fragment = new FunctionFragment(_guard$2, name, "view", params, [], null);
  12380. return fragment.selector;
  12381. }
  12382. /**
  12383. * Returns a new **FunctionFragment** for %%obj%%.
  12384. */
  12385. static from(obj) {
  12386. if (FunctionFragment.isFragment(obj)) {
  12387. return obj;
  12388. }
  12389. if (typeof (obj) === "string") {
  12390. try {
  12391. return FunctionFragment.from(lex(obj));
  12392. }
  12393. catch (error) {
  12394. assertArgument(false, "invalid function fragment", "obj", obj);
  12395. }
  12396. }
  12397. else if (obj instanceof TokenString) {
  12398. const name = consumeName("function", obj);
  12399. const inputs = consumeParams(obj);
  12400. const mutability = consumeMutability(obj);
  12401. let outputs = [];
  12402. if (consumeKeywords(obj, setify(["returns"])).has("returns")) {
  12403. outputs = consumeParams(obj);
  12404. }
  12405. const gas = consumeGas(obj);
  12406. consumeEoi(obj);
  12407. return new FunctionFragment(_guard$2, name, mutability, inputs, outputs, gas);
  12408. }
  12409. let stateMutability = obj.stateMutability;
  12410. // Use legacy Solidity ABI logic if stateMutability is missing
  12411. if (stateMutability == null) {
  12412. stateMutability = "payable";
  12413. if (typeof (obj.constant) === "boolean") {
  12414. stateMutability = "view";
  12415. if (!obj.constant) {
  12416. stateMutability = "payable";
  12417. if (typeof (obj.payable) === "boolean" && !obj.payable) {
  12418. stateMutability = "nonpayable";
  12419. }
  12420. }
  12421. }
  12422. else if (typeof (obj.payable) === "boolean" && !obj.payable) {
  12423. stateMutability = "nonpayable";
  12424. }
  12425. }
  12426. // @TODO: verifyState for stateMutability (e.g. throw if
  12427. // payable: false but stateMutability is "nonpayable")
  12428. 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);
  12429. }
  12430. /**
  12431. * Returns ``true`` and provides a type guard if %%value%% is a
  12432. * **FunctionFragment**.
  12433. */
  12434. static isFragment(value) {
  12435. return (value && value[internal$1] === FunctionFragmentInternal);
  12436. }
  12437. }
  12438. /**
  12439. * A Fragment which represents a structure.
  12440. */
  12441. class StructFragment extends NamedFragment {
  12442. /**
  12443. * @private
  12444. */
  12445. constructor(guard, name, inputs) {
  12446. super(guard, "struct", name, inputs);
  12447. Object.defineProperty(this, internal$1, { value: StructFragmentInternal });
  12448. }
  12449. /**
  12450. * Returns a string representation of this struct as %%format%%.
  12451. */
  12452. format() {
  12453. throw new Error("@TODO");
  12454. }
  12455. /**
  12456. * Returns a new **StructFragment** for %%obj%%.
  12457. */
  12458. static from(obj) {
  12459. if (typeof (obj) === "string") {
  12460. try {
  12461. return StructFragment.from(lex(obj));
  12462. }
  12463. catch (error) {
  12464. assertArgument(false, "invalid struct fragment", "obj", obj);
  12465. }
  12466. }
  12467. else if (obj instanceof TokenString) {
  12468. const name = consumeName("struct", obj);
  12469. const inputs = consumeParams(obj);
  12470. consumeEoi(obj);
  12471. return new StructFragment(_guard$2, name, inputs);
  12472. }
  12473. return new StructFragment(_guard$2, obj.name, obj.inputs ? obj.inputs.map(ParamType.from) : []);
  12474. }
  12475. // @TODO: fix this return type
  12476. /**
  12477. * Returns ``true`` and provides a type guard if %%value%% is a
  12478. * **StructFragment**.
  12479. */
  12480. static isFragment(value) {
  12481. return (value && value[internal$1] === StructFragmentInternal);
  12482. }
  12483. }
  12484. /**
  12485. * When sending values to or receiving values from a [[Contract]], the
  12486. * data is generally encoded using the [ABI standard](link-solc-abi).
  12487. *
  12488. * The AbiCoder provides a utility to encode values to ABI data and
  12489. * decode values from ABI data.
  12490. *
  12491. * Most of the time, developers should favour the [[Contract]] class,
  12492. * which further abstracts a lot of the finer details of ABI data.
  12493. *
  12494. * @_section api/abi/abi-coder:ABI Encoding
  12495. */
  12496. // See: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI
  12497. // https://docs.soliditylang.org/en/v0.8.17/control-structures.html
  12498. const PanicReasons$1 = new Map();
  12499. PanicReasons$1.set(0x00, "GENERIC_PANIC");
  12500. PanicReasons$1.set(0x01, "ASSERT_FALSE");
  12501. PanicReasons$1.set(0x11, "OVERFLOW");
  12502. PanicReasons$1.set(0x12, "DIVIDE_BY_ZERO");
  12503. PanicReasons$1.set(0x21, "ENUM_RANGE_ERROR");
  12504. PanicReasons$1.set(0x22, "BAD_STORAGE_DATA");
  12505. PanicReasons$1.set(0x31, "STACK_UNDERFLOW");
  12506. PanicReasons$1.set(0x32, "ARRAY_RANGE_ERROR");
  12507. PanicReasons$1.set(0x41, "OUT_OF_MEMORY");
  12508. PanicReasons$1.set(0x51, "UNINITIALIZED_FUNCTION_CALL");
  12509. const paramTypeBytes = new RegExp(/^bytes([0-9]*)$/);
  12510. const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/);
  12511. let defaultCoder = null;
  12512. let defaultMaxInflation = 1024;
  12513. function getBuiltinCallException(action, tx, data, abiCoder) {
  12514. let message = "missing revert data";
  12515. let reason = null;
  12516. const invocation = null;
  12517. let revert = null;
  12518. if (data) {
  12519. message = "execution reverted";
  12520. const bytes = getBytes(data);
  12521. data = hexlify(data);
  12522. if (bytes.length === 0) {
  12523. message += " (no data present; likely require(false) occurred";
  12524. reason = "require(false)";
  12525. }
  12526. else if (bytes.length % 32 !== 4) {
  12527. message += " (could not decode reason; invalid data length)";
  12528. }
  12529. else if (hexlify(bytes.slice(0, 4)) === "0x08c379a0") {
  12530. // Error(string)
  12531. try {
  12532. reason = abiCoder.decode(["string"], bytes.slice(4))[0];
  12533. revert = {
  12534. signature: "Error(string)",
  12535. name: "Error",
  12536. args: [reason]
  12537. };
  12538. message += `: ${JSON.stringify(reason)}`;
  12539. }
  12540. catch (error) {
  12541. message += " (could not decode reason; invalid string data)";
  12542. }
  12543. }
  12544. else if (hexlify(bytes.slice(0, 4)) === "0x4e487b71") {
  12545. // Panic(uint256)
  12546. try {
  12547. const code = Number(abiCoder.decode(["uint256"], bytes.slice(4))[0]);
  12548. revert = {
  12549. signature: "Panic(uint256)",
  12550. name: "Panic",
  12551. args: [code]
  12552. };
  12553. reason = `Panic due to ${PanicReasons$1.get(code) || "UNKNOWN"}(${code})`;
  12554. message += `: ${reason}`;
  12555. }
  12556. catch (error) {
  12557. message += " (could not decode panic code)";
  12558. }
  12559. }
  12560. else {
  12561. message += " (unknown custom error)";
  12562. }
  12563. }
  12564. const transaction = {
  12565. to: (tx.to ? getAddress(tx.to) : null),
  12566. data: (tx.data || "0x")
  12567. };
  12568. if (tx.from) {
  12569. transaction.from = getAddress(tx.from);
  12570. }
  12571. return makeError(message, "CALL_EXCEPTION", {
  12572. action, data, reason, transaction, invocation, revert
  12573. });
  12574. }
  12575. /**
  12576. * The **AbiCoder** is a low-level class responsible for encoding JavaScript
  12577. * values into binary data and decoding binary data into JavaScript values.
  12578. */
  12579. class AbiCoder {
  12580. #getCoder(param) {
  12581. if (param.isArray()) {
  12582. return new ArrayCoder(this.#getCoder(param.arrayChildren), param.arrayLength, param.name);
  12583. }
  12584. if (param.isTuple()) {
  12585. return new TupleCoder(param.components.map((c) => this.#getCoder(c)), param.name);
  12586. }
  12587. switch (param.baseType) {
  12588. case "address":
  12589. return new AddressCoder(param.name);
  12590. case "bool":
  12591. return new BooleanCoder(param.name);
  12592. case "string":
  12593. return new StringCoder(param.name);
  12594. case "bytes":
  12595. return new BytesCoder(param.name);
  12596. case "":
  12597. return new NullCoder(param.name);
  12598. }
  12599. // u?int[0-9]*
  12600. let match = param.type.match(paramTypeNumber);
  12601. if (match) {
  12602. let size = parseInt(match[2] || "256");
  12603. assertArgument(size !== 0 && size <= 256 && (size % 8) === 0, "invalid " + match[1] + " bit length", "param", param);
  12604. return new NumberCoder(size / 8, (match[1] === "int"), param.name);
  12605. }
  12606. // bytes[0-9]+
  12607. match = param.type.match(paramTypeBytes);
  12608. if (match) {
  12609. let size = parseInt(match[1]);
  12610. assertArgument(size !== 0 && size <= 32, "invalid bytes length", "param", param);
  12611. return new FixedBytesCoder(size, param.name);
  12612. }
  12613. assertArgument(false, "invalid type", "type", param.type);
  12614. }
  12615. /**
  12616. * Get the default values for the given %%types%%.
  12617. *
  12618. * For example, a ``uint`` is by default ``0`` and ``bool``
  12619. * is by default ``false``.
  12620. */
  12621. getDefaultValue(types) {
  12622. const coders = types.map((type) => this.#getCoder(ParamType.from(type)));
  12623. const coder = new TupleCoder(coders, "_");
  12624. return coder.defaultValue();
  12625. }
  12626. /**
  12627. * Encode the %%values%% as the %%types%% into ABI data.
  12628. *
  12629. * @returns DataHexstring
  12630. */
  12631. encode(types, values) {
  12632. assertArgumentCount(values.length, types.length, "types/values length mismatch");
  12633. const coders = types.map((type) => this.#getCoder(ParamType.from(type)));
  12634. const coder = (new TupleCoder(coders, "_"));
  12635. const writer = new Writer();
  12636. coder.encode(writer, values);
  12637. return writer.data;
  12638. }
  12639. /**
  12640. * Decode the ABI %%data%% as the %%types%% into values.
  12641. *
  12642. * If %%loose%% decoding is enabled, then strict padding is
  12643. * not enforced. Some older versions of Solidity incorrectly
  12644. * padded event data emitted from ``external`` functions.
  12645. */
  12646. decode(types, data, loose) {
  12647. const coders = types.map((type) => this.#getCoder(ParamType.from(type)));
  12648. const coder = new TupleCoder(coders, "_");
  12649. return coder.decode(new Reader(data, loose, defaultMaxInflation));
  12650. }
  12651. static _setDefaultMaxInflation(value) {
  12652. assertArgument(typeof (value) === "number" && Number.isInteger(value), "invalid defaultMaxInflation factor", "value", value);
  12653. defaultMaxInflation = value;
  12654. }
  12655. /**
  12656. * Returns the shared singleton instance of a default [[AbiCoder]].
  12657. *
  12658. * On the first call, the instance is created internally.
  12659. */
  12660. static defaultAbiCoder() {
  12661. if (defaultCoder == null) {
  12662. defaultCoder = new AbiCoder();
  12663. }
  12664. return defaultCoder;
  12665. }
  12666. /**
  12667. * Returns an ethers-compatible [[CallExceptionError]] Error for the given
  12668. * result %%data%% for the [[CallExceptionAction]] %%action%% against
  12669. * the Transaction %%tx%%.
  12670. */
  12671. static getBuiltinCallException(action, tx, data) {
  12672. return getBuiltinCallException(action, tx, data, AbiCoder.defaultAbiCoder());
  12673. }
  12674. }
  12675. /**
  12676. * About bytes32 strings...
  12677. *
  12678. * @_docloc: api/utils:Bytes32 Strings
  12679. */
  12680. /**
  12681. * Encodes %%text%% as a Bytes32 string.
  12682. */
  12683. function encodeBytes32String(text) {
  12684. // Get the bytes
  12685. const bytes = toUtf8Bytes(text);
  12686. // Check we have room for null-termination
  12687. if (bytes.length > 31) {
  12688. throw new Error("bytes32 string must be less than 32 bytes");
  12689. }
  12690. // Zero-pad (implicitly null-terminates)
  12691. return zeroPadBytes(bytes, 32);
  12692. }
  12693. /**
  12694. * Encodes the Bytes32-encoded %%bytes%% into a string.
  12695. */
  12696. function decodeBytes32String(_bytes) {
  12697. const data = getBytes(_bytes, "bytes");
  12698. // Must be 32 bytes with a null-termination
  12699. if (data.length !== 32) {
  12700. throw new Error("invalid bytes32 - not 32 bytes long");
  12701. }
  12702. if (data[31] !== 0) {
  12703. throw new Error("invalid bytes32 string - no null terminator");
  12704. }
  12705. // Find the null termination
  12706. let length = 31;
  12707. while (data[length - 1] === 0) {
  12708. length--;
  12709. }
  12710. // Determine the string value
  12711. return toUtf8String(data.slice(0, length));
  12712. }
  12713. /**
  12714. * The Interface class is a low-level class that accepts an
  12715. * ABI and provides all the necessary functionality to encode
  12716. * and decode paramaters to and results from methods, events
  12717. * and errors.
  12718. *
  12719. * It also provides several convenience methods to automatically
  12720. * search and find matching transactions and events to parse them.
  12721. *
  12722. * @_subsection api/abi:Interfaces [interfaces]
  12723. */
  12724. /**
  12725. * When using the [[Interface-parseLog]] to automatically match a Log to its event
  12726. * for parsing, a **LogDescription** is returned.
  12727. */
  12728. class LogDescription {
  12729. /**
  12730. * The matching fragment for the ``topic0``.
  12731. */
  12732. fragment;
  12733. /**
  12734. * The name of the Event.
  12735. */
  12736. name;
  12737. /**
  12738. * The full Event signature.
  12739. */
  12740. signature;
  12741. /**
  12742. * The topic hash for the Event.
  12743. */
  12744. topic;
  12745. /**
  12746. * The arguments passed into the Event with ``emit``.
  12747. */
  12748. args;
  12749. /**
  12750. * @_ignore:
  12751. */
  12752. constructor(fragment, topic, args) {
  12753. const name = fragment.name, signature = fragment.format();
  12754. defineProperties(this, {
  12755. fragment, name, signature, topic, args
  12756. });
  12757. }
  12758. }
  12759. /**
  12760. * When using the [[Interface-parseTransaction]] to automatically match
  12761. * a transaction data to its function for parsing,
  12762. * a **TransactionDescription** is returned.
  12763. */
  12764. class TransactionDescription {
  12765. /**
  12766. * The matching fragment from the transaction ``data``.
  12767. */
  12768. fragment;
  12769. /**
  12770. * The name of the Function from the transaction ``data``.
  12771. */
  12772. name;
  12773. /**
  12774. * The arguments passed to the Function from the transaction ``data``.
  12775. */
  12776. args;
  12777. /**
  12778. * The full Function signature from the transaction ``data``.
  12779. */
  12780. signature;
  12781. /**
  12782. * The selector for the Function from the transaction ``data``.
  12783. */
  12784. selector;
  12785. /**
  12786. * The ``value`` (in wei) from the transaction.
  12787. */
  12788. value;
  12789. /**
  12790. * @_ignore:
  12791. */
  12792. constructor(fragment, selector, args, value) {
  12793. const name = fragment.name, signature = fragment.format();
  12794. defineProperties(this, {
  12795. fragment, name, args, signature, selector, value
  12796. });
  12797. }
  12798. }
  12799. /**
  12800. * When using the [[Interface-parseError]] to automatically match an
  12801. * error for a call result for parsing, an **ErrorDescription** is returned.
  12802. */
  12803. class ErrorDescription {
  12804. /**
  12805. * The matching fragment.
  12806. */
  12807. fragment;
  12808. /**
  12809. * The name of the Error.
  12810. */
  12811. name;
  12812. /**
  12813. * The arguments passed to the Error with ``revert``.
  12814. */
  12815. args;
  12816. /**
  12817. * The full Error signature.
  12818. */
  12819. signature;
  12820. /**
  12821. * The selector for the Error.
  12822. */
  12823. selector;
  12824. /**
  12825. * @_ignore:
  12826. */
  12827. constructor(fragment, selector, args) {
  12828. const name = fragment.name, signature = fragment.format();
  12829. defineProperties(this, {
  12830. fragment, name, args, signature, selector
  12831. });
  12832. }
  12833. }
  12834. /**
  12835. * An **Indexed** is used as a value when a value that does not
  12836. * fit within a topic (i.e. not a fixed-length, 32-byte type). It
  12837. * is the ``keccak256`` of the value, and used for types such as
  12838. * arrays, tuples, bytes and strings.
  12839. */
  12840. class Indexed {
  12841. /**
  12842. * The ``keccak256`` of the value logged.
  12843. */
  12844. hash;
  12845. /**
  12846. * @_ignore:
  12847. */
  12848. _isIndexed;
  12849. /**
  12850. * Returns ``true`` if %%value%% is an **Indexed**.
  12851. *
  12852. * This provides a Type Guard for property access.
  12853. */
  12854. static isIndexed(value) {
  12855. return !!(value && value._isIndexed);
  12856. }
  12857. /**
  12858. * @_ignore:
  12859. */
  12860. constructor(hash) {
  12861. defineProperties(this, { hash, _isIndexed: true });
  12862. }
  12863. }
  12864. // https://docs.soliditylang.org/en/v0.8.13/control-structures.html?highlight=panic#panic-via-assert-and-error-via-require
  12865. const PanicReasons = {
  12866. "0": "generic panic",
  12867. "1": "assert(false)",
  12868. "17": "arithmetic overflow",
  12869. "18": "division or modulo by zero",
  12870. "33": "enum overflow",
  12871. "34": "invalid encoded storage byte array accessed",
  12872. "49": "out-of-bounds array access; popping on an empty array",
  12873. "50": "out-of-bounds access of an array or bytesN",
  12874. "65": "out of memory",
  12875. "81": "uninitialized function",
  12876. };
  12877. const BuiltinErrors = {
  12878. "0x08c379a0": {
  12879. signature: "Error(string)",
  12880. name: "Error",
  12881. inputs: ["string"],
  12882. reason: (message) => {
  12883. return `reverted with reason string ${JSON.stringify(message)}`;
  12884. }
  12885. },
  12886. "0x4e487b71": {
  12887. signature: "Panic(uint256)",
  12888. name: "Panic",
  12889. inputs: ["uint256"],
  12890. reason: (code) => {
  12891. let reason = "unknown panic code";
  12892. if (code >= 0 && code <= 0xff && PanicReasons[code.toString()]) {
  12893. reason = PanicReasons[code.toString()];
  12894. }
  12895. return `reverted with panic code 0x${code.toString(16)} (${reason})`;
  12896. }
  12897. }
  12898. };
  12899. /**
  12900. * An Interface abstracts many of the low-level details for
  12901. * encoding and decoding the data on the blockchain.
  12902. *
  12903. * An ABI provides information on how to encode data to send to
  12904. * a Contract, how to decode the results and events and how to
  12905. * interpret revert errors.
  12906. *
  12907. * The ABI can be specified by [any supported format](InterfaceAbi).
  12908. */
  12909. class Interface {
  12910. /**
  12911. * All the Contract ABI members (i.e. methods, events, errors, etc).
  12912. */
  12913. fragments;
  12914. /**
  12915. * The Contract constructor.
  12916. */
  12917. deploy;
  12918. /**
  12919. * The Fallback method, if any.
  12920. */
  12921. fallback;
  12922. /**
  12923. * If receiving ether is supported.
  12924. */
  12925. receive;
  12926. #errors;
  12927. #events;
  12928. #functions;
  12929. // #structs: Map<string, StructFragment>;
  12930. #abiCoder;
  12931. /**
  12932. * Create a new Interface for the %%fragments%%.
  12933. */
  12934. constructor(fragments) {
  12935. let abi = [];
  12936. if (typeof (fragments) === "string") {
  12937. abi = JSON.parse(fragments);
  12938. }
  12939. else {
  12940. abi = fragments;
  12941. }
  12942. this.#functions = new Map();
  12943. this.#errors = new Map();
  12944. this.#events = new Map();
  12945. // this.#structs = new Map();
  12946. const frags = [];
  12947. for (const a of abi) {
  12948. try {
  12949. frags.push(Fragment.from(a));
  12950. }
  12951. catch (error) {
  12952. console.log(`[Warning] Invalid Fragment ${JSON.stringify(a)}:`, error.message);
  12953. }
  12954. }
  12955. defineProperties(this, {
  12956. fragments: Object.freeze(frags)
  12957. });
  12958. let fallback = null;
  12959. let receive = false;
  12960. this.#abiCoder = this.getAbiCoder();
  12961. // Add all fragments by their signature
  12962. this.fragments.forEach((fragment, index) => {
  12963. let bucket;
  12964. switch (fragment.type) {
  12965. case "constructor":
  12966. if (this.deploy) {
  12967. console.log("duplicate definition - constructor");
  12968. return;
  12969. }
  12970. //checkNames(fragment, "input", fragment.inputs);
  12971. defineProperties(this, { deploy: fragment });
  12972. return;
  12973. case "fallback":
  12974. if (fragment.inputs.length === 0) {
  12975. receive = true;
  12976. }
  12977. else {
  12978. assertArgument(!fallback || fragment.payable !== fallback.payable, "conflicting fallback fragments", `fragments[${index}]`, fragment);
  12979. fallback = fragment;
  12980. receive = fallback.payable;
  12981. }
  12982. return;
  12983. case "function":
  12984. //checkNames(fragment, "input", fragment.inputs);
  12985. //checkNames(fragment, "output", (<FunctionFragment>fragment).outputs);
  12986. bucket = this.#functions;
  12987. break;
  12988. case "event":
  12989. //checkNames(fragment, "input", fragment.inputs);
  12990. bucket = this.#events;
  12991. break;
  12992. case "error":
  12993. bucket = this.#errors;
  12994. break;
  12995. default:
  12996. return;
  12997. }
  12998. // Two identical entries; ignore it
  12999. const signature = fragment.format();
  13000. if (bucket.has(signature)) {
  13001. return;
  13002. }
  13003. bucket.set(signature, fragment);
  13004. });
  13005. // If we do not have a constructor add a default
  13006. if (!this.deploy) {
  13007. defineProperties(this, {
  13008. deploy: ConstructorFragment.from("constructor()")
  13009. });
  13010. }
  13011. defineProperties(this, { fallback, receive });
  13012. }
  13013. /**
  13014. * Returns the entire Human-Readable ABI, as an array of
  13015. * signatures, optionally as %%minimal%% strings, which
  13016. * removes parameter names and unneceesary spaces.
  13017. */
  13018. format(minimal) {
  13019. const format = (minimal ? "minimal" : "full");
  13020. const abi = this.fragments.map((f) => f.format(format));
  13021. return abi;
  13022. }
  13023. /**
  13024. * Return the JSON-encoded ABI. This is the format Solidiy
  13025. * returns.
  13026. */
  13027. formatJson() {
  13028. const abi = this.fragments.map((f) => f.format("json"));
  13029. // We need to re-bundle the JSON fragments a bit
  13030. return JSON.stringify(abi.map((j) => JSON.parse(j)));
  13031. }
  13032. /**
  13033. * The ABI coder that will be used to encode and decode binary
  13034. * data.
  13035. */
  13036. getAbiCoder() {
  13037. return AbiCoder.defaultAbiCoder();
  13038. }
  13039. // Find a function definition by any means necessary (unless it is ambiguous)
  13040. #getFunction(key, values, forceUnique) {
  13041. // Selector
  13042. if (isHexString(key)) {
  13043. const selector = key.toLowerCase();
  13044. for (const fragment of this.#functions.values()) {
  13045. if (selector === fragment.selector) {
  13046. return fragment;
  13047. }
  13048. }
  13049. return null;
  13050. }
  13051. // It is a bare name, look up the function (will return null if ambiguous)
  13052. if (key.indexOf("(") === -1) {
  13053. const matching = [];
  13054. for (const [name, fragment] of this.#functions) {
  13055. if (name.split("(" /* fix:) */)[0] === key) {
  13056. matching.push(fragment);
  13057. }
  13058. }
  13059. if (values) {
  13060. const lastValue = (values.length > 0) ? values[values.length - 1] : null;
  13061. let valueLength = values.length;
  13062. let allowOptions = true;
  13063. if (Typed.isTyped(lastValue) && lastValue.type === "overrides") {
  13064. allowOptions = false;
  13065. valueLength--;
  13066. }
  13067. // Remove all matches that don't have a compatible length. The args
  13068. // may contain an overrides, so the match may have n or n - 1 parameters
  13069. for (let i = matching.length - 1; i >= 0; i--) {
  13070. const inputs = matching[i].inputs.length;
  13071. if (inputs !== valueLength && (!allowOptions || inputs !== valueLength - 1)) {
  13072. matching.splice(i, 1);
  13073. }
  13074. }
  13075. // Remove all matches that don't match the Typed signature
  13076. for (let i = matching.length - 1; i >= 0; i--) {
  13077. const inputs = matching[i].inputs;
  13078. for (let j = 0; j < values.length; j++) {
  13079. // Not a typed value
  13080. if (!Typed.isTyped(values[j])) {
  13081. continue;
  13082. }
  13083. // We are past the inputs
  13084. if (j >= inputs.length) {
  13085. if (values[j].type === "overrides") {
  13086. continue;
  13087. }
  13088. matching.splice(i, 1);
  13089. break;
  13090. }
  13091. // Make sure the value type matches the input type
  13092. if (values[j].type !== inputs[j].baseType) {
  13093. matching.splice(i, 1);
  13094. break;
  13095. }
  13096. }
  13097. }
  13098. }
  13099. // We found a single matching signature with an overrides, but the
  13100. // last value is something that cannot possibly be an options
  13101. if (matching.length === 1 && values && values.length !== matching[0].inputs.length) {
  13102. const lastArg = values[values.length - 1];
  13103. if (lastArg == null || Array.isArray(lastArg) || typeof (lastArg) !== "object") {
  13104. matching.splice(0, 1);
  13105. }
  13106. }
  13107. if (matching.length === 0) {
  13108. return null;
  13109. }
  13110. if (matching.length > 1 && forceUnique) {
  13111. const matchStr = matching.map((m) => JSON.stringify(m.format())).join(", ");
  13112. assertArgument(false, `ambiguous function description (i.e. matches ${matchStr})`, "key", key);
  13113. }
  13114. return matching[0];
  13115. }
  13116. // Normalize the signature and lookup the function
  13117. const result = this.#functions.get(FunctionFragment.from(key).format());
  13118. if (result) {
  13119. return result;
  13120. }
  13121. return null;
  13122. }
  13123. /**
  13124. * Get the function name for %%key%%, which may be a function selector,
  13125. * function name or function signature that belongs to the ABI.
  13126. */
  13127. getFunctionName(key) {
  13128. const fragment = this.#getFunction(key, null, false);
  13129. assertArgument(fragment, "no matching function", "key", key);
  13130. return fragment.name;
  13131. }
  13132. /**
  13133. * Returns true if %%key%% (a function selector, function name or
  13134. * function signature) is present in the ABI.
  13135. *
  13136. * In the case of a function name, the name may be ambiguous, so
  13137. * accessing the [[FunctionFragment]] may require refinement.
  13138. */
  13139. hasFunction(key) {
  13140. return !!this.#getFunction(key, null, false);
  13141. }
  13142. /**
  13143. * Get the [[FunctionFragment]] for %%key%%, which may be a function
  13144. * selector, function name or function signature that belongs to the ABI.
  13145. *
  13146. * If %%values%% is provided, it will use the Typed API to handle
  13147. * ambiguous cases where multiple functions match by name.
  13148. *
  13149. * If the %%key%% and %%values%% do not refine to a single function in
  13150. * the ABI, this will throw.
  13151. */
  13152. getFunction(key, values) {
  13153. return this.#getFunction(key, values || null, true);
  13154. }
  13155. /**
  13156. * Iterate over all functions, calling %%callback%%, sorted by their name.
  13157. */
  13158. forEachFunction(callback) {
  13159. const names = Array.from(this.#functions.keys());
  13160. names.sort((a, b) => a.localeCompare(b));
  13161. for (let i = 0; i < names.length; i++) {
  13162. const name = names[i];
  13163. callback((this.#functions.get(name)), i);
  13164. }
  13165. }
  13166. // Find an event definition by any means necessary (unless it is ambiguous)
  13167. #getEvent(key, values, forceUnique) {
  13168. // EventTopic
  13169. if (isHexString(key)) {
  13170. const eventTopic = key.toLowerCase();
  13171. for (const fragment of this.#events.values()) {
  13172. if (eventTopic === fragment.topicHash) {
  13173. return fragment;
  13174. }
  13175. }
  13176. return null;
  13177. }
  13178. // It is a bare name, look up the function (will return null if ambiguous)
  13179. if (key.indexOf("(") === -1) {
  13180. const matching = [];
  13181. for (const [name, fragment] of this.#events) {
  13182. if (name.split("(" /* fix:) */)[0] === key) {
  13183. matching.push(fragment);
  13184. }
  13185. }
  13186. if (values) {
  13187. // Remove all matches that don't have a compatible length.
  13188. for (let i = matching.length - 1; i >= 0; i--) {
  13189. if (matching[i].inputs.length < values.length) {
  13190. matching.splice(i, 1);
  13191. }
  13192. }
  13193. // Remove all matches that don't match the Typed signature
  13194. for (let i = matching.length - 1; i >= 0; i--) {
  13195. const inputs = matching[i].inputs;
  13196. for (let j = 0; j < values.length; j++) {
  13197. // Not a typed value
  13198. if (!Typed.isTyped(values[j])) {
  13199. continue;
  13200. }
  13201. // Make sure the value type matches the input type
  13202. if (values[j].type !== inputs[j].baseType) {
  13203. matching.splice(i, 1);
  13204. break;
  13205. }
  13206. }
  13207. }
  13208. }
  13209. if (matching.length === 0) {
  13210. return null;
  13211. }
  13212. if (matching.length > 1 && forceUnique) {
  13213. const matchStr = matching.map((m) => JSON.stringify(m.format())).join(", ");
  13214. assertArgument(false, `ambiguous event description (i.e. matches ${matchStr})`, "key", key);
  13215. }
  13216. return matching[0];
  13217. }
  13218. // Normalize the signature and lookup the function
  13219. const result = this.#events.get(EventFragment.from(key).format());
  13220. if (result) {
  13221. return result;
  13222. }
  13223. return null;
  13224. }
  13225. /**
  13226. * Get the event name for %%key%%, which may be a topic hash,
  13227. * event name or event signature that belongs to the ABI.
  13228. */
  13229. getEventName(key) {
  13230. const fragment = this.#getEvent(key, null, false);
  13231. assertArgument(fragment, "no matching event", "key", key);
  13232. return fragment.name;
  13233. }
  13234. /**
  13235. * Returns true if %%key%% (an event topic hash, event name or
  13236. * event signature) is present in the ABI.
  13237. *
  13238. * In the case of an event name, the name may be ambiguous, so
  13239. * accessing the [[EventFragment]] may require refinement.
  13240. */
  13241. hasEvent(key) {
  13242. return !!this.#getEvent(key, null, false);
  13243. }
  13244. /**
  13245. * Get the [[EventFragment]] for %%key%%, which may be a topic hash,
  13246. * event name or event signature that belongs to the ABI.
  13247. *
  13248. * If %%values%% is provided, it will use the Typed API to handle
  13249. * ambiguous cases where multiple events match by name.
  13250. *
  13251. * If the %%key%% and %%values%% do not refine to a single event in
  13252. * the ABI, this will throw.
  13253. */
  13254. getEvent(key, values) {
  13255. return this.#getEvent(key, values || null, true);
  13256. }
  13257. /**
  13258. * Iterate over all events, calling %%callback%%, sorted by their name.
  13259. */
  13260. forEachEvent(callback) {
  13261. const names = Array.from(this.#events.keys());
  13262. names.sort((a, b) => a.localeCompare(b));
  13263. for (let i = 0; i < names.length; i++) {
  13264. const name = names[i];
  13265. callback((this.#events.get(name)), i);
  13266. }
  13267. }
  13268. /**
  13269. * Get the [[ErrorFragment]] for %%key%%, which may be an error
  13270. * selector, error name or error signature that belongs to the ABI.
  13271. *
  13272. * If %%values%% is provided, it will use the Typed API to handle
  13273. * ambiguous cases where multiple errors match by name.
  13274. *
  13275. * If the %%key%% and %%values%% do not refine to a single error in
  13276. * the ABI, this will throw.
  13277. */
  13278. getError(key, values) {
  13279. if (isHexString(key)) {
  13280. const selector = key.toLowerCase();
  13281. if (BuiltinErrors[selector]) {
  13282. return ErrorFragment.from(BuiltinErrors[selector].signature);
  13283. }
  13284. for (const fragment of this.#errors.values()) {
  13285. if (selector === fragment.selector) {
  13286. return fragment;
  13287. }
  13288. }
  13289. return null;
  13290. }
  13291. // It is a bare name, look up the function (will return null if ambiguous)
  13292. if (key.indexOf("(") === -1) {
  13293. const matching = [];
  13294. for (const [name, fragment] of this.#errors) {
  13295. if (name.split("(" /* fix:) */)[0] === key) {
  13296. matching.push(fragment);
  13297. }
  13298. }
  13299. if (matching.length === 0) {
  13300. if (key === "Error") {
  13301. return ErrorFragment.from("error Error(string)");
  13302. }
  13303. if (key === "Panic") {
  13304. return ErrorFragment.from("error Panic(uint256)");
  13305. }
  13306. return null;
  13307. }
  13308. else if (matching.length > 1) {
  13309. const matchStr = matching.map((m) => JSON.stringify(m.format())).join(", ");
  13310. assertArgument(false, `ambiguous error description (i.e. ${matchStr})`, "name", key);
  13311. }
  13312. return matching[0];
  13313. }
  13314. // Normalize the signature and lookup the function
  13315. key = ErrorFragment.from(key).format();
  13316. if (key === "Error(string)") {
  13317. return ErrorFragment.from("error Error(string)");
  13318. }
  13319. if (key === "Panic(uint256)") {
  13320. return ErrorFragment.from("error Panic(uint256)");
  13321. }
  13322. const result = this.#errors.get(key);
  13323. if (result) {
  13324. return result;
  13325. }
  13326. return null;
  13327. }
  13328. /**
  13329. * Iterate over all errors, calling %%callback%%, sorted by their name.
  13330. */
  13331. forEachError(callback) {
  13332. const names = Array.from(this.#errors.keys());
  13333. names.sort((a, b) => a.localeCompare(b));
  13334. for (let i = 0; i < names.length; i++) {
  13335. const name = names[i];
  13336. callback((this.#errors.get(name)), i);
  13337. }
  13338. }
  13339. // Get the 4-byte selector used by Solidity to identify a function
  13340. /*
  13341. getSelector(fragment: ErrorFragment | FunctionFragment): string {
  13342. if (typeof(fragment) === "string") {
  13343. const matches: Array<Fragment> = [ ];
  13344. try { matches.push(this.getFunction(fragment)); } catch (error) { }
  13345. try { matches.push(this.getError(<string>fragment)); } catch (_) { }
  13346. if (matches.length === 0) {
  13347. logger.throwArgumentError("unknown fragment", "key", fragment);
  13348. } else if (matches.length > 1) {
  13349. logger.throwArgumentError("ambiguous fragment matches function and error", "key", fragment);
  13350. }
  13351. fragment = matches[0];
  13352. }
  13353. return dataSlice(id(fragment.format()), 0, 4);
  13354. }
  13355. */
  13356. // Get the 32-byte topic hash used by Solidity to identify an event
  13357. /*
  13358. getEventTopic(fragment: EventFragment): string {
  13359. //if (typeof(fragment) === "string") { fragment = this.getEvent(eventFragment); }
  13360. return id(fragment.format());
  13361. }
  13362. */
  13363. _decodeParams(params, data) {
  13364. return this.#abiCoder.decode(params, data);
  13365. }
  13366. _encodeParams(params, values) {
  13367. return this.#abiCoder.encode(params, values);
  13368. }
  13369. /**
  13370. * Encodes a ``tx.data`` object for deploying the Contract with
  13371. * the %%values%% as the constructor arguments.
  13372. */
  13373. encodeDeploy(values) {
  13374. return this._encodeParams(this.deploy.inputs, values || []);
  13375. }
  13376. /**
  13377. * Decodes the result %%data%% (e.g. from an ``eth_call``) for the
  13378. * specified error (see [[getError]] for valid values for
  13379. * %%key%%).
  13380. *
  13381. * Most developers should prefer the [[parseCallResult]] method instead,
  13382. * which will automatically detect a ``CALL_EXCEPTION`` and throw the
  13383. * corresponding error.
  13384. */
  13385. decodeErrorResult(fragment, data) {
  13386. if (typeof (fragment) === "string") {
  13387. const f = this.getError(fragment);
  13388. assertArgument(f, "unknown error", "fragment", fragment);
  13389. fragment = f;
  13390. }
  13391. assertArgument(dataSlice(data, 0, 4) === fragment.selector, `data signature does not match error ${fragment.name}.`, "data", data);
  13392. return this._decodeParams(fragment.inputs, dataSlice(data, 4));
  13393. }
  13394. /**
  13395. * Encodes the transaction revert data for a call result that
  13396. * reverted from the the Contract with the sepcified %%error%%
  13397. * (see [[getError]] for valid values for %%fragment%%) with the %%values%%.
  13398. *
  13399. * This is generally not used by most developers, unless trying to mock
  13400. * a result from a Contract.
  13401. */
  13402. encodeErrorResult(fragment, values) {
  13403. if (typeof (fragment) === "string") {
  13404. const f = this.getError(fragment);
  13405. assertArgument(f, "unknown error", "fragment", fragment);
  13406. fragment = f;
  13407. }
  13408. return concat([
  13409. fragment.selector,
  13410. this._encodeParams(fragment.inputs, values || [])
  13411. ]);
  13412. }
  13413. /**
  13414. * Decodes the %%data%% from a transaction ``tx.data`` for
  13415. * the function specified (see [[getFunction]] for valid values
  13416. * for %%fragment%%).
  13417. *
  13418. * Most developers should prefer the [[parseTransaction]] method
  13419. * instead, which will automatically detect the fragment.
  13420. */
  13421. decodeFunctionData(fragment, data) {
  13422. if (typeof (fragment) === "string") {
  13423. const f = this.getFunction(fragment);
  13424. assertArgument(f, "unknown function", "fragment", fragment);
  13425. fragment = f;
  13426. }
  13427. assertArgument(dataSlice(data, 0, 4) === fragment.selector, `data signature does not match function ${fragment.name}.`, "data", data);
  13428. return this._decodeParams(fragment.inputs, dataSlice(data, 4));
  13429. }
  13430. /**
  13431. * Encodes the ``tx.data`` for a transaction that calls the function
  13432. * specified (see [[getFunction]] for valid values for %%fragment%%) with
  13433. * the %%values%%.
  13434. */
  13435. encodeFunctionData(fragment, values) {
  13436. if (typeof (fragment) === "string") {
  13437. const f = this.getFunction(fragment);
  13438. assertArgument(f, "unknown function", "fragment", fragment);
  13439. fragment = f;
  13440. }
  13441. return concat([
  13442. fragment.selector,
  13443. this._encodeParams(fragment.inputs, values || [])
  13444. ]);
  13445. }
  13446. /**
  13447. * Decodes the result %%data%% (e.g. from an ``eth_call``) for the
  13448. * specified function (see [[getFunction]] for valid values for
  13449. * %%key%%).
  13450. *
  13451. * Most developers should prefer the [[parseCallResult]] method instead,
  13452. * which will automatically detect a ``CALL_EXCEPTION`` and throw the
  13453. * corresponding error.
  13454. */
  13455. decodeFunctionResult(fragment, data) {
  13456. if (typeof (fragment) === "string") {
  13457. const f = this.getFunction(fragment);
  13458. assertArgument(f, "unknown function", "fragment", fragment);
  13459. fragment = f;
  13460. }
  13461. let message = "invalid length for result data";
  13462. const bytes = getBytesCopy(data);
  13463. if ((bytes.length % 32) === 0) {
  13464. try {
  13465. return this.#abiCoder.decode(fragment.outputs, bytes);
  13466. }
  13467. catch (error) {
  13468. message = "could not decode result data";
  13469. }
  13470. }
  13471. // Call returned data with no error, but the data is junk
  13472. assert(false, message, "BAD_DATA", {
  13473. value: hexlify(bytes),
  13474. info: { method: fragment.name, signature: fragment.format() }
  13475. });
  13476. }
  13477. makeError(_data, tx) {
  13478. const data = getBytes(_data, "data");
  13479. const error = AbiCoder.getBuiltinCallException("call", tx, data);
  13480. // Not a built-in error; try finding a custom error
  13481. const customPrefix = "execution reverted (unknown custom error)";
  13482. if (error.message.startsWith(customPrefix)) {
  13483. const selector = hexlify(data.slice(0, 4));
  13484. const ef = this.getError(selector);
  13485. if (ef) {
  13486. try {
  13487. const args = this.#abiCoder.decode(ef.inputs, data.slice(4));
  13488. error.revert = {
  13489. name: ef.name, signature: ef.format(), args
  13490. };
  13491. error.reason = error.revert.signature;
  13492. error.message = `execution reverted: ${error.reason}`;
  13493. }
  13494. catch (e) {
  13495. error.message = `execution reverted (coult not decode custom error)`;
  13496. }
  13497. }
  13498. }
  13499. // Add the invocation, if available
  13500. const parsed = this.parseTransaction(tx);
  13501. if (parsed) {
  13502. error.invocation = {
  13503. method: parsed.name,
  13504. signature: parsed.signature,
  13505. args: parsed.args
  13506. };
  13507. }
  13508. return error;
  13509. }
  13510. /**
  13511. * Encodes the result data (e.g. from an ``eth_call``) for the
  13512. * specified function (see [[getFunction]] for valid values
  13513. * for %%fragment%%) with %%values%%.
  13514. *
  13515. * This is generally not used by most developers, unless trying to mock
  13516. * a result from a Contract.
  13517. */
  13518. encodeFunctionResult(fragment, values) {
  13519. if (typeof (fragment) === "string") {
  13520. const f = this.getFunction(fragment);
  13521. assertArgument(f, "unknown function", "fragment", fragment);
  13522. fragment = f;
  13523. }
  13524. return hexlify(this.#abiCoder.encode(fragment.outputs, values || []));
  13525. }
  13526. /*
  13527. spelunk(inputs: Array<ParamType>, values: ReadonlyArray<any>, processfunc: (type: string, value: any) => Promise<any>): Promise<Array<any>> {
  13528. const promises: Array<Promise<>> = [ ];
  13529. const process = function(type: ParamType, value: any): any {
  13530. if (type.baseType === "array") {
  13531. return descend(type.child
  13532. }
  13533. if (type. === "address") {
  13534. }
  13535. };
  13536. const descend = function (inputs: Array<ParamType>, values: ReadonlyArray<any>) {
  13537. if (inputs.length !== values.length) { throw new Error("length mismatch"); }
  13538. };
  13539. const result: Array<any> = [ ];
  13540. values.forEach((value, index) => {
  13541. if (value == null) {
  13542. topics.push(null);
  13543. } else if (param.baseType === "array" || param.baseType === "tuple") {
  13544. logger.throwArgumentError("filtering with tuples or arrays not supported", ("contract." + param.name), value);
  13545. } else if (Array.isArray(value)) {
  13546. topics.push(value.map((value) => encodeTopic(param, value)));
  13547. } else {
  13548. topics.push(encodeTopic(param, value));
  13549. }
  13550. });
  13551. }
  13552. */
  13553. // Create the filter for the event with search criteria (e.g. for eth_filterLog)
  13554. encodeFilterTopics(fragment, values) {
  13555. if (typeof (fragment) === "string") {
  13556. const f = this.getEvent(fragment);
  13557. assertArgument(f, "unknown event", "eventFragment", fragment);
  13558. fragment = f;
  13559. }
  13560. assert(values.length <= fragment.inputs.length, `too many arguments for ${fragment.format()}`, "UNEXPECTED_ARGUMENT", { count: values.length, expectedCount: fragment.inputs.length });
  13561. const topics = [];
  13562. if (!fragment.anonymous) {
  13563. topics.push(fragment.topicHash);
  13564. }
  13565. // @TODO: Use the coders for this; to properly support tuples, etc.
  13566. const encodeTopic = (param, value) => {
  13567. if (param.type === "string") {
  13568. return id(value);
  13569. }
  13570. else if (param.type === "bytes") {
  13571. return keccak256(hexlify(value));
  13572. }
  13573. if (param.type === "bool" && typeof (value) === "boolean") {
  13574. value = (value ? "0x01" : "0x00");
  13575. }
  13576. else if (param.type.match(/^u?int/)) {
  13577. value = toBeHex(value); // @TODO: Should this toTwos??
  13578. }
  13579. else if (param.type.match(/^bytes/)) {
  13580. value = zeroPadBytes(value, 32);
  13581. }
  13582. else if (param.type === "address") {
  13583. // Check addresses are valid
  13584. this.#abiCoder.encode(["address"], [value]);
  13585. }
  13586. return zeroPadValue(hexlify(value), 32);
  13587. };
  13588. values.forEach((value, index) => {
  13589. const param = fragment.inputs[index];
  13590. if (!param.indexed) {
  13591. assertArgument(value == null, "cannot filter non-indexed parameters; must be null", ("contract." + param.name), value);
  13592. return;
  13593. }
  13594. if (value == null) {
  13595. topics.push(null);
  13596. }
  13597. else if (param.baseType === "array" || param.baseType === "tuple") {
  13598. assertArgument(false, "filtering with tuples or arrays not supported", ("contract." + param.name), value);
  13599. }
  13600. else if (Array.isArray(value)) {
  13601. topics.push(value.map((value) => encodeTopic(param, value)));
  13602. }
  13603. else {
  13604. topics.push(encodeTopic(param, value));
  13605. }
  13606. });
  13607. // Trim off trailing nulls
  13608. while (topics.length && topics[topics.length - 1] === null) {
  13609. topics.pop();
  13610. }
  13611. return topics;
  13612. }
  13613. encodeEventLog(fragment, values) {
  13614. if (typeof (fragment) === "string") {
  13615. const f = this.getEvent(fragment);
  13616. assertArgument(f, "unknown event", "eventFragment", fragment);
  13617. fragment = f;
  13618. }
  13619. const topics = [];
  13620. const dataTypes = [];
  13621. const dataValues = [];
  13622. if (!fragment.anonymous) {
  13623. topics.push(fragment.topicHash);
  13624. }
  13625. assertArgument(values.length === fragment.inputs.length, "event arguments/values mismatch", "values", values);
  13626. fragment.inputs.forEach((param, index) => {
  13627. const value = values[index];
  13628. if (param.indexed) {
  13629. if (param.type === "string") {
  13630. topics.push(id(value));
  13631. }
  13632. else if (param.type === "bytes") {
  13633. topics.push(keccak256(value));
  13634. }
  13635. else if (param.baseType === "tuple" || param.baseType === "array") {
  13636. // @TODO
  13637. throw new Error("not implemented");
  13638. }
  13639. else {
  13640. topics.push(this.#abiCoder.encode([param.type], [value]));
  13641. }
  13642. }
  13643. else {
  13644. dataTypes.push(param);
  13645. dataValues.push(value);
  13646. }
  13647. });
  13648. return {
  13649. data: this.#abiCoder.encode(dataTypes, dataValues),
  13650. topics: topics
  13651. };
  13652. }
  13653. // Decode a filter for the event and the search criteria
  13654. decodeEventLog(fragment, data, topics) {
  13655. if (typeof (fragment) === "string") {
  13656. const f = this.getEvent(fragment);
  13657. assertArgument(f, "unknown event", "eventFragment", fragment);
  13658. fragment = f;
  13659. }
  13660. if (topics != null && !fragment.anonymous) {
  13661. const eventTopic = fragment.topicHash;
  13662. assertArgument(isHexString(topics[0], 32) && topics[0].toLowerCase() === eventTopic, "fragment/topic mismatch", "topics[0]", topics[0]);
  13663. topics = topics.slice(1);
  13664. }
  13665. const indexed = [];
  13666. const nonIndexed = [];
  13667. const dynamic = [];
  13668. fragment.inputs.forEach((param, index) => {
  13669. if (param.indexed) {
  13670. if (param.type === "string" || param.type === "bytes" || param.baseType === "tuple" || param.baseType === "array") {
  13671. indexed.push(ParamType.from({ type: "bytes32", name: param.name }));
  13672. dynamic.push(true);
  13673. }
  13674. else {
  13675. indexed.push(param);
  13676. dynamic.push(false);
  13677. }
  13678. }
  13679. else {
  13680. nonIndexed.push(param);
  13681. dynamic.push(false);
  13682. }
  13683. });
  13684. const resultIndexed = (topics != null) ? this.#abiCoder.decode(indexed, concat(topics)) : null;
  13685. const resultNonIndexed = this.#abiCoder.decode(nonIndexed, data, true);
  13686. //const result: (Array<any> & { [ key: string ]: any }) = [ ];
  13687. const values = [];
  13688. const keys = [];
  13689. let nonIndexedIndex = 0, indexedIndex = 0;
  13690. fragment.inputs.forEach((param, index) => {
  13691. let value = null;
  13692. if (param.indexed) {
  13693. if (resultIndexed == null) {
  13694. value = new Indexed(null);
  13695. }
  13696. else if (dynamic[index]) {
  13697. value = new Indexed(resultIndexed[indexedIndex++]);
  13698. }
  13699. else {
  13700. try {
  13701. value = resultIndexed[indexedIndex++];
  13702. }
  13703. catch (error) {
  13704. value = error;
  13705. }
  13706. }
  13707. }
  13708. else {
  13709. try {
  13710. value = resultNonIndexed[nonIndexedIndex++];
  13711. }
  13712. catch (error) {
  13713. value = error;
  13714. }
  13715. }
  13716. values.push(value);
  13717. keys.push(param.name || null);
  13718. });
  13719. return Result.fromItems(values, keys);
  13720. }
  13721. /**
  13722. * Parses a transaction, finding the matching function and extracts
  13723. * the parameter values along with other useful function details.
  13724. *
  13725. * If the matching function cannot be found, return null.
  13726. */
  13727. parseTransaction(tx) {
  13728. const data = getBytes(tx.data, "tx.data");
  13729. const value = getBigInt((tx.value != null) ? tx.value : 0, "tx.value");
  13730. const fragment = this.getFunction(hexlify(data.slice(0, 4)));
  13731. if (!fragment) {
  13732. return null;
  13733. }
  13734. const args = this.#abiCoder.decode(fragment.inputs, data.slice(4));
  13735. return new TransactionDescription(fragment, fragment.selector, args, value);
  13736. }
  13737. parseCallResult(data) {
  13738. throw new Error("@TODO");
  13739. }
  13740. /**
  13741. * Parses a receipt log, finding the matching event and extracts
  13742. * the parameter values along with other useful event details.
  13743. *
  13744. * If the matching event cannot be found, returns null.
  13745. */
  13746. parseLog(log) {
  13747. const fragment = this.getEvent(log.topics[0]);
  13748. if (!fragment || fragment.anonymous) {
  13749. return null;
  13750. }
  13751. // @TODO: If anonymous, and the only method, and the input count matches, should we parse?
  13752. // Probably not, because just because it is the only event in the ABI does
  13753. // not mean we have the full ABI; maybe just a fragment?
  13754. return new LogDescription(fragment, fragment.topicHash, this.decodeEventLog(fragment, log.data, log.topics));
  13755. }
  13756. /**
  13757. * Parses a revert data, finding the matching error and extracts
  13758. * the parameter values along with other useful error details.
  13759. *
  13760. * If the matching error cannot be found, returns null.
  13761. */
  13762. parseError(data) {
  13763. const hexData = hexlify(data);
  13764. const fragment = this.getError(dataSlice(hexData, 0, 4));
  13765. if (!fragment) {
  13766. return null;
  13767. }
  13768. const args = this.#abiCoder.decode(fragment.inputs, dataSlice(hexData, 4));
  13769. return new ErrorDescription(fragment, fragment.selector, args);
  13770. }
  13771. /**
  13772. * Creates a new [[Interface]] from the ABI %%value%%.
  13773. *
  13774. * The %%value%% may be provided as an existing [[Interface]] object,
  13775. * a JSON-encoded ABI or any Human-Readable ABI format.
  13776. */
  13777. static from(value) {
  13778. // Already an Interface, which is immutable
  13779. if (value instanceof Interface) {
  13780. return value;
  13781. }
  13782. // JSON
  13783. if (typeof (value) === "string") {
  13784. return new Interface(JSON.parse(value));
  13785. }
  13786. // An Interface; possibly from another v6 instance
  13787. if (typeof (value.formatJson) === "function") {
  13788. return new Interface(value.formatJson());
  13789. }
  13790. // A legacy Interface; from an older version
  13791. if (typeof (value.format) === "function") {
  13792. return new Interface(value.format("json"));
  13793. }
  13794. // Array of fragments
  13795. return new Interface(value);
  13796. }
  13797. }
  13798. //import { resolveAddress } from "@ethersproject/address";
  13799. const BN_0$2 = BigInt(0);
  13800. // -----------------------
  13801. function getValue(value) {
  13802. if (value == null) {
  13803. return null;
  13804. }
  13805. return value;
  13806. }
  13807. function toJson(value) {
  13808. if (value == null) {
  13809. return null;
  13810. }
  13811. return value.toString();
  13812. }
  13813. // @TODO? <T extends FeeData = { }> implements Required<T>
  13814. /**
  13815. * A **FeeData** wraps all the fee-related values associated with
  13816. * the network.
  13817. */
  13818. class FeeData {
  13819. /**
  13820. * The gas price for legacy networks.
  13821. */
  13822. gasPrice;
  13823. /**
  13824. * The maximum fee to pay per gas.
  13825. *
  13826. * The base fee per gas is defined by the network and based on
  13827. * congestion, increasing the cost during times of heavy load
  13828. * and lowering when less busy.
  13829. *
  13830. * The actual fee per gas will be the base fee for the block
  13831. * and the priority fee, up to the max fee per gas.
  13832. *
  13833. * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559))
  13834. */
  13835. maxFeePerGas;
  13836. /**
  13837. * The additional amout to pay per gas to encourage a validator
  13838. * to include the transaction.
  13839. *
  13840. * The purpose of this is to compensate the validator for the
  13841. * adjusted risk for including a given transaction.
  13842. *
  13843. * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559))
  13844. */
  13845. maxPriorityFeePerGas;
  13846. /**
  13847. * Creates a new FeeData for %%gasPrice%%, %%maxFeePerGas%% and
  13848. * %%maxPriorityFeePerGas%%.
  13849. */
  13850. constructor(gasPrice, maxFeePerGas, maxPriorityFeePerGas) {
  13851. defineProperties(this, {
  13852. gasPrice: getValue(gasPrice),
  13853. maxFeePerGas: getValue(maxFeePerGas),
  13854. maxPriorityFeePerGas: getValue(maxPriorityFeePerGas)
  13855. });
  13856. }
  13857. /**
  13858. * Returns a JSON-friendly value.
  13859. */
  13860. toJSON() {
  13861. const { gasPrice, maxFeePerGas, maxPriorityFeePerGas } = this;
  13862. return {
  13863. _type: "FeeData",
  13864. gasPrice: toJson(gasPrice),
  13865. maxFeePerGas: toJson(maxFeePerGas),
  13866. maxPriorityFeePerGas: toJson(maxPriorityFeePerGas),
  13867. };
  13868. }
  13869. }
  13870. /**
  13871. * Returns a copy of %%req%% with all properties coerced to their strict
  13872. * types.
  13873. */
  13874. function copyRequest(req) {
  13875. const result = {};
  13876. // These could be addresses, ENS names or Addressables
  13877. if (req.to) {
  13878. result.to = req.to;
  13879. }
  13880. if (req.from) {
  13881. result.from = req.from;
  13882. }
  13883. if (req.data) {
  13884. result.data = hexlify(req.data);
  13885. }
  13886. const bigIntKeys = "chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/);
  13887. for (const key of bigIntKeys) {
  13888. if (!(key in req) || req[key] == null) {
  13889. continue;
  13890. }
  13891. result[key] = getBigInt(req[key], `request.${key}`);
  13892. }
  13893. const numberKeys = "type,nonce".split(/,/);
  13894. for (const key of numberKeys) {
  13895. if (!(key in req) || req[key] == null) {
  13896. continue;
  13897. }
  13898. result[key] = getNumber(req[key], `request.${key}`);
  13899. }
  13900. if (req.accessList) {
  13901. result.accessList = accessListify(req.accessList);
  13902. }
  13903. if ("blockTag" in req) {
  13904. result.blockTag = req.blockTag;
  13905. }
  13906. if ("enableCcipRead" in req) {
  13907. result.enableCcipRead = !!req.enableCcipRead;
  13908. }
  13909. if ("customData" in req) {
  13910. result.customData = req.customData;
  13911. }
  13912. if ("blobVersionedHashes" in req && req.blobVersionedHashes) {
  13913. result.blobVersionedHashes = req.blobVersionedHashes.slice();
  13914. }
  13915. if ("kzg" in req) {
  13916. result.kzg = req.kzg;
  13917. }
  13918. if ("blobs" in req && req.blobs) {
  13919. result.blobs = req.blobs.map((b) => {
  13920. if (isBytesLike(b)) {
  13921. return hexlify(b);
  13922. }
  13923. return Object.assign({}, b);
  13924. });
  13925. }
  13926. return result;
  13927. }
  13928. /**
  13929. * A **Block** represents the data associated with a full block on
  13930. * Ethereum.
  13931. */
  13932. class Block {
  13933. /**
  13934. * The provider connected to the block used to fetch additional details
  13935. * if necessary.
  13936. */
  13937. provider;
  13938. /**
  13939. * The block number, sometimes called the block height. This is a
  13940. * sequential number that is one higher than the parent block.
  13941. */
  13942. number;
  13943. /**
  13944. * The block hash.
  13945. *
  13946. * This hash includes all properties, so can be safely used to identify
  13947. * an exact set of block properties.
  13948. */
  13949. hash;
  13950. /**
  13951. * The timestamp for this block, which is the number of seconds since
  13952. * epoch that this block was included.
  13953. */
  13954. timestamp;
  13955. /**
  13956. * The block hash of the parent block.
  13957. */
  13958. parentHash;
  13959. /**
  13960. * The hash tree root of the parent beacon block for the given
  13961. * execution block. See [[link-eip-4788]].
  13962. */
  13963. parentBeaconBlockRoot;
  13964. /**
  13965. * The nonce.
  13966. *
  13967. * On legacy networks, this is the random number inserted which
  13968. * permitted the difficulty target to be reached.
  13969. */
  13970. nonce;
  13971. /**
  13972. * The difficulty target.
  13973. *
  13974. * On legacy networks, this is the proof-of-work target required
  13975. * for a block to meet the protocol rules to be included.
  13976. *
  13977. * On modern networks, this is a random number arrived at using
  13978. * randao. @TODO: Find links?
  13979. */
  13980. difficulty;
  13981. /**
  13982. * The total gas limit for this block.
  13983. */
  13984. gasLimit;
  13985. /**
  13986. * The total gas used in this block.
  13987. */
  13988. gasUsed;
  13989. /**
  13990. * The root hash for the global state after applying changes
  13991. * in this block.
  13992. */
  13993. stateRoot;
  13994. /**
  13995. * The hash of the transaction receipts trie.
  13996. */
  13997. receiptsRoot;
  13998. /**
  13999. * The total amount of blob gas consumed by the transactions
  14000. * within the block. See [[link-eip-4844]].
  14001. */
  14002. blobGasUsed;
  14003. /**
  14004. * The running total of blob gas consumed in excess of the
  14005. * target, prior to the block. See [[link-eip-4844]].
  14006. */
  14007. excessBlobGas;
  14008. /**
  14009. * The miner coinbase address, wihch receives any subsidies for
  14010. * including this block.
  14011. */
  14012. miner;
  14013. /**
  14014. * The latest RANDAO mix of the post beacon state of
  14015. * the previous block.
  14016. */
  14017. prevRandao;
  14018. /**
  14019. * Any extra data the validator wished to include.
  14020. */
  14021. extraData;
  14022. /**
  14023. * The base fee per gas that all transactions in this block were
  14024. * charged.
  14025. *
  14026. * This adjusts after each block, depending on how congested the network
  14027. * is.
  14028. */
  14029. baseFeePerGas;
  14030. #transactions;
  14031. /**
  14032. * Create a new **Block** object.
  14033. *
  14034. * This should generally not be necessary as the unless implementing a
  14035. * low-level library.
  14036. */
  14037. constructor(block, provider) {
  14038. this.#transactions = block.transactions.map((tx) => {
  14039. if (typeof (tx) !== "string") {
  14040. return new TransactionResponse(tx, provider);
  14041. }
  14042. return tx;
  14043. });
  14044. defineProperties(this, {
  14045. provider,
  14046. hash: getValue(block.hash),
  14047. number: block.number,
  14048. timestamp: block.timestamp,
  14049. parentHash: block.parentHash,
  14050. parentBeaconBlockRoot: block.parentBeaconBlockRoot,
  14051. nonce: block.nonce,
  14052. difficulty: block.difficulty,
  14053. gasLimit: block.gasLimit,
  14054. gasUsed: block.gasUsed,
  14055. blobGasUsed: block.blobGasUsed,
  14056. excessBlobGas: block.excessBlobGas,
  14057. miner: block.miner,
  14058. prevRandao: getValue(block.prevRandao),
  14059. extraData: block.extraData,
  14060. baseFeePerGas: getValue(block.baseFeePerGas),
  14061. stateRoot: block.stateRoot,
  14062. receiptsRoot: block.receiptsRoot,
  14063. });
  14064. }
  14065. /**
  14066. * Returns the list of transaction hashes, in the order
  14067. * they were executed within the block.
  14068. */
  14069. get transactions() {
  14070. return this.#transactions.map((tx) => {
  14071. if (typeof (tx) === "string") {
  14072. return tx;
  14073. }
  14074. return tx.hash;
  14075. });
  14076. }
  14077. /**
  14078. * Returns the complete transactions, in the order they
  14079. * were executed within the block.
  14080. *
  14081. * This is only available for blocks which prefetched
  14082. * transactions, by passing ``true`` to %%prefetchTxs%%
  14083. * into [[Provider-getBlock]].
  14084. */
  14085. get prefetchedTransactions() {
  14086. const txs = this.#transactions.slice();
  14087. // Doesn't matter...
  14088. if (txs.length === 0) {
  14089. return [];
  14090. }
  14091. // Make sure we prefetched the transactions
  14092. assert(typeof (txs[0]) === "object", "transactions were not prefetched with block request", "UNSUPPORTED_OPERATION", {
  14093. operation: "transactionResponses()"
  14094. });
  14095. return txs;
  14096. }
  14097. /**
  14098. * Returns a JSON-friendly value.
  14099. */
  14100. toJSON() {
  14101. const { baseFeePerGas, difficulty, extraData, gasLimit, gasUsed, hash, miner, prevRandao, nonce, number, parentHash, parentBeaconBlockRoot, stateRoot, receiptsRoot, timestamp, transactions } = this;
  14102. return {
  14103. _type: "Block",
  14104. baseFeePerGas: toJson(baseFeePerGas),
  14105. difficulty: toJson(difficulty),
  14106. extraData,
  14107. gasLimit: toJson(gasLimit),
  14108. gasUsed: toJson(gasUsed),
  14109. blobGasUsed: toJson(this.blobGasUsed),
  14110. excessBlobGas: toJson(this.excessBlobGas),
  14111. hash, miner, prevRandao, nonce, number, parentHash, timestamp,
  14112. parentBeaconBlockRoot, stateRoot, receiptsRoot,
  14113. transactions,
  14114. };
  14115. }
  14116. [Symbol.iterator]() {
  14117. let index = 0;
  14118. const txs = this.transactions;
  14119. return {
  14120. next: () => {
  14121. if (index < this.length) {
  14122. return {
  14123. value: txs[index++], done: false
  14124. };
  14125. }
  14126. return { value: undefined, done: true };
  14127. }
  14128. };
  14129. }
  14130. /**
  14131. * The number of transactions in this block.
  14132. */
  14133. get length() { return this.#transactions.length; }
  14134. /**
  14135. * The [[link-js-date]] this block was included at.
  14136. */
  14137. get date() {
  14138. if (this.timestamp == null) {
  14139. return null;
  14140. }
  14141. return new Date(this.timestamp * 1000);
  14142. }
  14143. /**
  14144. * Get the transaction at %%indexe%% within this block.
  14145. */
  14146. async getTransaction(indexOrHash) {
  14147. // Find the internal value by its index or hash
  14148. let tx = undefined;
  14149. if (typeof (indexOrHash) === "number") {
  14150. tx = this.#transactions[indexOrHash];
  14151. }
  14152. else {
  14153. const hash = indexOrHash.toLowerCase();
  14154. for (const v of this.#transactions) {
  14155. if (typeof (v) === "string") {
  14156. if (v !== hash) {
  14157. continue;
  14158. }
  14159. tx = v;
  14160. break;
  14161. }
  14162. else {
  14163. if (v.hash !== hash) {
  14164. continue;
  14165. }
  14166. tx = v;
  14167. break;
  14168. }
  14169. }
  14170. }
  14171. if (tx == null) {
  14172. throw new Error("no such tx");
  14173. }
  14174. if (typeof (tx) === "string") {
  14175. return (await this.provider.getTransaction(tx));
  14176. }
  14177. else {
  14178. return tx;
  14179. }
  14180. }
  14181. /**
  14182. * If a **Block** was fetched with a request to include the transactions
  14183. * this will allow synchronous access to those transactions.
  14184. *
  14185. * If the transactions were not prefetched, this will throw.
  14186. */
  14187. getPrefetchedTransaction(indexOrHash) {
  14188. const txs = this.prefetchedTransactions;
  14189. if (typeof (indexOrHash) === "number") {
  14190. return txs[indexOrHash];
  14191. }
  14192. indexOrHash = indexOrHash.toLowerCase();
  14193. for (const tx of txs) {
  14194. if (tx.hash === indexOrHash) {
  14195. return tx;
  14196. }
  14197. }
  14198. assertArgument(false, "no matching transaction", "indexOrHash", indexOrHash);
  14199. }
  14200. /**
  14201. * Returns true if this block been mined. This provides a type guard
  14202. * for all properties on a [[MinedBlock]].
  14203. */
  14204. isMined() { return !!this.hash; }
  14205. /**
  14206. * Returns true if this block is an [[link-eip-2930]] block.
  14207. */
  14208. isLondon() {
  14209. return !!this.baseFeePerGas;
  14210. }
  14211. /**
  14212. * @_ignore:
  14213. */
  14214. orphanedEvent() {
  14215. if (!this.isMined()) {
  14216. throw new Error("");
  14217. }
  14218. return createOrphanedBlockFilter(this);
  14219. }
  14220. }
  14221. //////////////////////
  14222. // Log
  14223. /**
  14224. * A **Log** in Ethereum represents an event that has been included in a
  14225. * transaction using the ``LOG*`` opcodes, which are most commonly used by
  14226. * Solidity's emit for announcing events.
  14227. */
  14228. class Log {
  14229. /**
  14230. * The provider connected to the log used to fetch additional details
  14231. * if necessary.
  14232. */
  14233. provider;
  14234. /**
  14235. * The transaction hash of the transaction this log occurred in. Use the
  14236. * [[Log-getTransaction]] to get the [[TransactionResponse]].
  14237. */
  14238. transactionHash;
  14239. /**
  14240. * The block hash of the block this log occurred in. Use the
  14241. * [[Log-getBlock]] to get the [[Block]].
  14242. */
  14243. blockHash;
  14244. /**
  14245. * The block number of the block this log occurred in. It is preferred
  14246. * to use the [[Block-hash]] when fetching the related [[Block]],
  14247. * since in the case of an orphaned block, the block at that height may
  14248. * have changed.
  14249. */
  14250. blockNumber;
  14251. /**
  14252. * If the **Log** represents a block that was removed due to an orphaned
  14253. * block, this will be true.
  14254. *
  14255. * This can only happen within an orphan event listener.
  14256. */
  14257. removed;
  14258. /**
  14259. * The address of the contract that emitted this log.
  14260. */
  14261. address;
  14262. /**
  14263. * The data included in this log when it was emitted.
  14264. */
  14265. data;
  14266. /**
  14267. * The indexed topics included in this log when it was emitted.
  14268. *
  14269. * All topics are included in the bloom filters, so they can be
  14270. * efficiently filtered using the [[Provider-getLogs]] method.
  14271. */
  14272. topics;
  14273. /**
  14274. * The index within the block this log occurred at. This is generally
  14275. * not useful to developers, but can be used with the various roots
  14276. * to proof inclusion within a block.
  14277. */
  14278. index;
  14279. /**
  14280. * The index within the transaction of this log.
  14281. */
  14282. transactionIndex;
  14283. /**
  14284. * @_ignore:
  14285. */
  14286. constructor(log, provider) {
  14287. this.provider = provider;
  14288. const topics = Object.freeze(log.topics.slice());
  14289. defineProperties(this, {
  14290. transactionHash: log.transactionHash,
  14291. blockHash: log.blockHash,
  14292. blockNumber: log.blockNumber,
  14293. removed: log.removed,
  14294. address: log.address,
  14295. data: log.data,
  14296. topics,
  14297. index: log.index,
  14298. transactionIndex: log.transactionIndex,
  14299. });
  14300. }
  14301. /**
  14302. * Returns a JSON-compatible object.
  14303. */
  14304. toJSON() {
  14305. const { address, blockHash, blockNumber, data, index, removed, topics, transactionHash, transactionIndex } = this;
  14306. return {
  14307. _type: "log",
  14308. address, blockHash, blockNumber, data, index,
  14309. removed, topics, transactionHash, transactionIndex
  14310. };
  14311. }
  14312. /**
  14313. * Returns the block that this log occurred in.
  14314. */
  14315. async getBlock() {
  14316. const block = await this.provider.getBlock(this.blockHash);
  14317. assert(!!block, "failed to find transaction", "UNKNOWN_ERROR", {});
  14318. return block;
  14319. }
  14320. /**
  14321. * Returns the transaction that this log occurred in.
  14322. */
  14323. async getTransaction() {
  14324. const tx = await this.provider.getTransaction(this.transactionHash);
  14325. assert(!!tx, "failed to find transaction", "UNKNOWN_ERROR", {});
  14326. return tx;
  14327. }
  14328. /**
  14329. * Returns the transaction receipt fot the transaction that this
  14330. * log occurred in.
  14331. */
  14332. async getTransactionReceipt() {
  14333. const receipt = await this.provider.getTransactionReceipt(this.transactionHash);
  14334. assert(!!receipt, "failed to find transaction receipt", "UNKNOWN_ERROR", {});
  14335. return receipt;
  14336. }
  14337. /**
  14338. * @_ignore:
  14339. */
  14340. removedEvent() {
  14341. return createRemovedLogFilter(this);
  14342. }
  14343. }
  14344. //////////////////////
  14345. // Transaction Receipt
  14346. /*
  14347. export interface LegacyTransactionReceipt {
  14348. byzantium: false;
  14349. status: null;
  14350. root: string;
  14351. }
  14352. export interface ByzantiumTransactionReceipt {
  14353. byzantium: true;
  14354. status: number;
  14355. root: null;
  14356. }
  14357. */
  14358. /**
  14359. * A **TransactionReceipt** includes additional information about a
  14360. * transaction that is only available after it has been mined.
  14361. */
  14362. class TransactionReceipt {
  14363. /**
  14364. * The provider connected to the log used to fetch additional details
  14365. * if necessary.
  14366. */
  14367. provider;
  14368. /**
  14369. * The address the transaction was sent to.
  14370. */
  14371. to;
  14372. /**
  14373. * The sender of the transaction.
  14374. */
  14375. from;
  14376. /**
  14377. * The address of the contract if the transaction was directly
  14378. * responsible for deploying one.
  14379. *
  14380. * This is non-null **only** if the ``to`` is empty and the ``data``
  14381. * was successfully executed as initcode.
  14382. */
  14383. contractAddress;
  14384. /**
  14385. * The transaction hash.
  14386. */
  14387. hash;
  14388. /**
  14389. * The index of this transaction within the block transactions.
  14390. */
  14391. index;
  14392. /**
  14393. * The block hash of the [[Block]] this transaction was included in.
  14394. */
  14395. blockHash;
  14396. /**
  14397. * The block number of the [[Block]] this transaction was included in.
  14398. */
  14399. blockNumber;
  14400. /**
  14401. * The bloom filter bytes that represent all logs that occurred within
  14402. * this transaction. This is generally not useful for most developers,
  14403. * but can be used to validate the included logs.
  14404. */
  14405. logsBloom;
  14406. /**
  14407. * The actual amount of gas used by this transaction.
  14408. *
  14409. * When creating a transaction, the amount of gas that will be used can
  14410. * only be approximated, but the sender must pay the gas fee for the
  14411. * entire gas limit. After the transaction, the difference is refunded.
  14412. */
  14413. gasUsed;
  14414. /**
  14415. * The gas used for BLObs. See [[link-eip-4844]].
  14416. */
  14417. blobGasUsed;
  14418. /**
  14419. * The amount of gas used by all transactions within the block for this
  14420. * and all transactions with a lower ``index``.
  14421. *
  14422. * This is generally not useful for developers but can be used to
  14423. * validate certain aspects of execution.
  14424. */
  14425. cumulativeGasUsed;
  14426. /**
  14427. * The actual gas price used during execution.
  14428. *
  14429. * Due to the complexity of [[link-eip-1559]] this value can only
  14430. * be caluclated after the transaction has been mined, snce the base
  14431. * fee is protocol-enforced.
  14432. */
  14433. gasPrice;
  14434. /**
  14435. * The price paid per BLOB in gas. See [[link-eip-4844]].
  14436. */
  14437. blobGasPrice;
  14438. /**
  14439. * The [[link-eip-2718]] transaction type.
  14440. */
  14441. type;
  14442. //readonly byzantium!: boolean;
  14443. /**
  14444. * The status of this transaction, indicating success (i.e. ``1``) or
  14445. * a revert (i.e. ``0``).
  14446. *
  14447. * This is available in post-byzantium blocks, but some backends may
  14448. * backfill this value.
  14449. */
  14450. status;
  14451. /**
  14452. * The root hash of this transaction.
  14453. *
  14454. * This is no present and was only included in pre-byzantium blocks, but
  14455. * could be used to validate certain parts of the receipt.
  14456. */
  14457. root;
  14458. #logs;
  14459. /**
  14460. * @_ignore:
  14461. */
  14462. constructor(tx, provider) {
  14463. this.#logs = Object.freeze(tx.logs.map((log) => {
  14464. return new Log(log, provider);
  14465. }));
  14466. let gasPrice = BN_0$2;
  14467. if (tx.effectiveGasPrice != null) {
  14468. gasPrice = tx.effectiveGasPrice;
  14469. }
  14470. else if (tx.gasPrice != null) {
  14471. gasPrice = tx.gasPrice;
  14472. }
  14473. defineProperties(this, {
  14474. provider,
  14475. to: tx.to,
  14476. from: tx.from,
  14477. contractAddress: tx.contractAddress,
  14478. hash: tx.hash,
  14479. index: tx.index,
  14480. blockHash: tx.blockHash,
  14481. blockNumber: tx.blockNumber,
  14482. logsBloom: tx.logsBloom,
  14483. gasUsed: tx.gasUsed,
  14484. cumulativeGasUsed: tx.cumulativeGasUsed,
  14485. blobGasUsed: tx.blobGasUsed,
  14486. gasPrice,
  14487. blobGasPrice: tx.blobGasPrice,
  14488. type: tx.type,
  14489. //byzantium: tx.byzantium,
  14490. status: tx.status,
  14491. root: tx.root
  14492. });
  14493. }
  14494. /**
  14495. * The logs for this transaction.
  14496. */
  14497. get logs() { return this.#logs; }
  14498. /**
  14499. * Returns a JSON-compatible representation.
  14500. */
  14501. toJSON() {
  14502. const { to, from, contractAddress, hash, index, blockHash, blockNumber, logsBloom, logs, //byzantium,
  14503. status, root } = this;
  14504. return {
  14505. _type: "TransactionReceipt",
  14506. blockHash, blockNumber,
  14507. //byzantium,
  14508. contractAddress,
  14509. cumulativeGasUsed: toJson(this.cumulativeGasUsed),
  14510. from,
  14511. gasPrice: toJson(this.gasPrice),
  14512. blobGasUsed: toJson(this.blobGasUsed),
  14513. blobGasPrice: toJson(this.blobGasPrice),
  14514. gasUsed: toJson(this.gasUsed),
  14515. hash, index, logs, logsBloom, root, status, to
  14516. };
  14517. }
  14518. /**
  14519. * @_ignore:
  14520. */
  14521. get length() { return this.logs.length; }
  14522. [Symbol.iterator]() {
  14523. let index = 0;
  14524. return {
  14525. next: () => {
  14526. if (index < this.length) {
  14527. return { value: this.logs[index++], done: false };
  14528. }
  14529. return { value: undefined, done: true };
  14530. }
  14531. };
  14532. }
  14533. /**
  14534. * The total fee for this transaction, in wei.
  14535. */
  14536. get fee() {
  14537. return this.gasUsed * this.gasPrice;
  14538. }
  14539. /**
  14540. * Resolves to the block this transaction occurred in.
  14541. */
  14542. async getBlock() {
  14543. const block = await this.provider.getBlock(this.blockHash);
  14544. if (block == null) {
  14545. throw new Error("TODO");
  14546. }
  14547. return block;
  14548. }
  14549. /**
  14550. * Resolves to the transaction this transaction occurred in.
  14551. */
  14552. async getTransaction() {
  14553. const tx = await this.provider.getTransaction(this.hash);
  14554. if (tx == null) {
  14555. throw new Error("TODO");
  14556. }
  14557. return tx;
  14558. }
  14559. /**
  14560. * Resolves to the return value of the execution of this transaction.
  14561. *
  14562. * Support for this feature is limited, as it requires an archive node
  14563. * with the ``debug_`` or ``trace_`` API enabled.
  14564. */
  14565. async getResult() {
  14566. return (await this.provider.getTransactionResult(this.hash));
  14567. }
  14568. /**
  14569. * Resolves to the number of confirmations this transaction has.
  14570. */
  14571. async confirmations() {
  14572. return (await this.provider.getBlockNumber()) - this.blockNumber + 1;
  14573. }
  14574. /**
  14575. * @_ignore:
  14576. */
  14577. removedEvent() {
  14578. return createRemovedTransactionFilter(this);
  14579. }
  14580. /**
  14581. * @_ignore:
  14582. */
  14583. reorderedEvent(other) {
  14584. assert(!other || other.isMined(), "unmined 'other' transction cannot be orphaned", "UNSUPPORTED_OPERATION", { operation: "reorderedEvent(other)" });
  14585. return createReorderedTransactionFilter(this, other);
  14586. }
  14587. }
  14588. /**
  14589. * A **TransactionResponse** includes all properties about a transaction
  14590. * that was sent to the network, which may or may not be included in a
  14591. * block.
  14592. *
  14593. * The [[TransactionResponse-isMined]] can be used to check if the
  14594. * transaction has been mined as well as type guard that the otherwise
  14595. * possibly ``null`` properties are defined.
  14596. */
  14597. class TransactionResponse {
  14598. /**
  14599. * The provider this is connected to, which will influence how its
  14600. * methods will resolve its async inspection methods.
  14601. */
  14602. provider;
  14603. /**
  14604. * The block number of the block that this transaction was included in.
  14605. *
  14606. * This is ``null`` for pending transactions.
  14607. */
  14608. blockNumber;
  14609. /**
  14610. * The blockHash of the block that this transaction was included in.
  14611. *
  14612. * This is ``null`` for pending transactions.
  14613. */
  14614. blockHash;
  14615. /**
  14616. * The index within the block that this transaction resides at.
  14617. */
  14618. index;
  14619. /**
  14620. * The transaction hash.
  14621. */
  14622. hash;
  14623. /**
  14624. * The [[link-eip-2718]] transaction envelope type. This is
  14625. * ``0`` for legacy transactions types.
  14626. */
  14627. type;
  14628. /**
  14629. * The receiver of this transaction.
  14630. *
  14631. * If ``null``, then the transaction is an initcode transaction.
  14632. * This means the result of executing the [[data]] will be deployed
  14633. * as a new contract on chain (assuming it does not revert) and the
  14634. * address may be computed using [[getCreateAddress]].
  14635. */
  14636. to;
  14637. /**
  14638. * The sender of this transaction. It is implicitly computed
  14639. * from the transaction pre-image hash (as the digest) and the
  14640. * [[signature]] using ecrecover.
  14641. */
  14642. from;
  14643. /**
  14644. * The nonce, which is used to prevent replay attacks and offer
  14645. * a method to ensure transactions from a given sender are explicitly
  14646. * ordered.
  14647. *
  14648. * When sending a transaction, this must be equal to the number of
  14649. * transactions ever sent by [[from]].
  14650. */
  14651. nonce;
  14652. /**
  14653. * The maximum units of gas this transaction can consume. If execution
  14654. * exceeds this, the entries transaction is reverted and the sender
  14655. * is charged for the full amount, despite not state changes being made.
  14656. */
  14657. gasLimit;
  14658. /**
  14659. * The gas price can have various values, depending on the network.
  14660. *
  14661. * In modern networks, for transactions that are included this is
  14662. * the //effective gas price// (the fee per gas that was actually
  14663. * charged), while for transactions that have not been included yet
  14664. * is the [[maxFeePerGas]].
  14665. *
  14666. * For legacy transactions, or transactions on legacy networks, this
  14667. * is the fee that will be charged per unit of gas the transaction
  14668. * consumes.
  14669. */
  14670. gasPrice;
  14671. /**
  14672. * The maximum priority fee (per unit of gas) to allow a
  14673. * validator to charge the sender. This is inclusive of the
  14674. * [[maxFeeFeePerGas]].
  14675. */
  14676. maxPriorityFeePerGas;
  14677. /**
  14678. * The maximum fee (per unit of gas) to allow this transaction
  14679. * to charge the sender.
  14680. */
  14681. maxFeePerGas;
  14682. /**
  14683. * The [[link-eip-4844]] max fee per BLOb gas.
  14684. */
  14685. maxFeePerBlobGas;
  14686. /**
  14687. * The data.
  14688. */
  14689. data;
  14690. /**
  14691. * The value, in wei. Use [[formatEther]] to format this value
  14692. * as ether.
  14693. */
  14694. value;
  14695. /**
  14696. * The chain ID.
  14697. */
  14698. chainId;
  14699. /**
  14700. * The signature.
  14701. */
  14702. signature;
  14703. /**
  14704. * The [[link-eip-2930]] access list for transaction types that
  14705. * support it, otherwise ``null``.
  14706. */
  14707. accessList;
  14708. /**
  14709. * The [[link-eip-4844]] BLOb versioned hashes.
  14710. */
  14711. blobVersionedHashes;
  14712. #startBlock;
  14713. /**
  14714. * @_ignore:
  14715. */
  14716. constructor(tx, provider) {
  14717. this.provider = provider;
  14718. this.blockNumber = (tx.blockNumber != null) ? tx.blockNumber : null;
  14719. this.blockHash = (tx.blockHash != null) ? tx.blockHash : null;
  14720. this.hash = tx.hash;
  14721. this.index = tx.index;
  14722. this.type = tx.type;
  14723. this.from = tx.from;
  14724. this.to = tx.to || null;
  14725. this.gasLimit = tx.gasLimit;
  14726. this.nonce = tx.nonce;
  14727. this.data = tx.data;
  14728. this.value = tx.value;
  14729. this.gasPrice = tx.gasPrice;
  14730. this.maxPriorityFeePerGas = (tx.maxPriorityFeePerGas != null) ? tx.maxPriorityFeePerGas : null;
  14731. this.maxFeePerGas = (tx.maxFeePerGas != null) ? tx.maxFeePerGas : null;
  14732. this.maxFeePerBlobGas = (tx.maxFeePerBlobGas != null) ? tx.maxFeePerBlobGas : null;
  14733. this.chainId = tx.chainId;
  14734. this.signature = tx.signature;
  14735. this.accessList = (tx.accessList != null) ? tx.accessList : null;
  14736. this.blobVersionedHashes = (tx.blobVersionedHashes != null) ? tx.blobVersionedHashes : null;
  14737. this.#startBlock = -1;
  14738. }
  14739. /**
  14740. * Returns a JSON-compatible representation of this transaction.
  14741. */
  14742. toJSON() {
  14743. const { blockNumber, blockHash, index, hash, type, to, from, nonce, data, signature, accessList, blobVersionedHashes } = this;
  14744. return {
  14745. _type: "TransactionResponse",
  14746. accessList, blockNumber, blockHash,
  14747. blobVersionedHashes,
  14748. chainId: toJson(this.chainId),
  14749. data, from,
  14750. gasLimit: toJson(this.gasLimit),
  14751. gasPrice: toJson(this.gasPrice),
  14752. hash,
  14753. maxFeePerGas: toJson(this.maxFeePerGas),
  14754. maxPriorityFeePerGas: toJson(this.maxPriorityFeePerGas),
  14755. maxFeePerBlobGas: toJson(this.maxFeePerBlobGas),
  14756. nonce, signature, to, index, type,
  14757. value: toJson(this.value),
  14758. };
  14759. }
  14760. /**
  14761. * Resolves to the Block that this transaction was included in.
  14762. *
  14763. * This will return null if the transaction has not been included yet.
  14764. */
  14765. async getBlock() {
  14766. let blockNumber = this.blockNumber;
  14767. if (blockNumber == null) {
  14768. const tx = await this.getTransaction();
  14769. if (tx) {
  14770. blockNumber = tx.blockNumber;
  14771. }
  14772. }
  14773. if (blockNumber == null) {
  14774. return null;
  14775. }
  14776. const block = this.provider.getBlock(blockNumber);
  14777. if (block == null) {
  14778. throw new Error("TODO");
  14779. }
  14780. return block;
  14781. }
  14782. /**
  14783. * Resolves to this transaction being re-requested from the
  14784. * provider. This can be used if you have an unmined transaction
  14785. * and wish to get an up-to-date populated instance.
  14786. */
  14787. async getTransaction() {
  14788. return this.provider.getTransaction(this.hash);
  14789. }
  14790. /**
  14791. * Resolve to the number of confirmations this transaction has.
  14792. */
  14793. async confirmations() {
  14794. if (this.blockNumber == null) {
  14795. const { tx, blockNumber } = await resolveProperties({
  14796. tx: this.getTransaction(),
  14797. blockNumber: this.provider.getBlockNumber()
  14798. });
  14799. // Not mined yet...
  14800. if (tx == null || tx.blockNumber == null) {
  14801. return 0;
  14802. }
  14803. return blockNumber - tx.blockNumber + 1;
  14804. }
  14805. const blockNumber = await this.provider.getBlockNumber();
  14806. return blockNumber - this.blockNumber + 1;
  14807. }
  14808. /**
  14809. * Resolves once this transaction has been mined and has
  14810. * %%confirms%% blocks including it (default: ``1``) with an
  14811. * optional %%timeout%%.
  14812. *
  14813. * This can resolve to ``null`` only if %%confirms%% is ``0``
  14814. * and the transaction has not been mined, otherwise this will
  14815. * wait until enough confirmations have completed.
  14816. */
  14817. async wait(_confirms, _timeout) {
  14818. const confirms = (_confirms == null) ? 1 : _confirms;
  14819. const timeout = (_timeout == null) ? 0 : _timeout;
  14820. let startBlock = this.#startBlock;
  14821. let nextScan = -1;
  14822. let stopScanning = (startBlock === -1) ? true : false;
  14823. const checkReplacement = async () => {
  14824. // Get the current transaction count for this sender
  14825. if (stopScanning) {
  14826. return null;
  14827. }
  14828. const { blockNumber, nonce } = await resolveProperties({
  14829. blockNumber: this.provider.getBlockNumber(),
  14830. nonce: this.provider.getTransactionCount(this.from)
  14831. });
  14832. // No transaction or our nonce has not been mined yet; but we
  14833. // can start scanning later when we do start
  14834. if (nonce < this.nonce) {
  14835. startBlock = blockNumber;
  14836. return;
  14837. }
  14838. // We were mined; no replacement
  14839. if (stopScanning) {
  14840. return null;
  14841. }
  14842. const mined = await this.getTransaction();
  14843. if (mined && mined.blockNumber != null) {
  14844. return;
  14845. }
  14846. // We were replaced; start scanning for that transaction
  14847. // Starting to scan; look back a few extra blocks for safety
  14848. if (nextScan === -1) {
  14849. nextScan = startBlock - 3;
  14850. if (nextScan < this.#startBlock) {
  14851. nextScan = this.#startBlock;
  14852. }
  14853. }
  14854. while (nextScan <= blockNumber) {
  14855. // Get the next block to scan
  14856. if (stopScanning) {
  14857. return null;
  14858. }
  14859. const block = await this.provider.getBlock(nextScan, true);
  14860. // This should not happen; but we'll try again shortly
  14861. if (block == null) {
  14862. return;
  14863. }
  14864. // We were mined; no replacement
  14865. for (const hash of block) {
  14866. if (hash === this.hash) {
  14867. return;
  14868. }
  14869. }
  14870. // Search for the transaction that replaced us
  14871. for (let i = 0; i < block.length; i++) {
  14872. const tx = await block.getTransaction(i);
  14873. if (tx.from === this.from && tx.nonce === this.nonce) {
  14874. // Get the receipt
  14875. if (stopScanning) {
  14876. return null;
  14877. }
  14878. const receipt = await this.provider.getTransactionReceipt(tx.hash);
  14879. // This should not happen; but we'll try again shortly
  14880. if (receipt == null) {
  14881. return;
  14882. }
  14883. // We will retry this on the next block (this case could be optimized)
  14884. if ((blockNumber - receipt.blockNumber + 1) < confirms) {
  14885. return;
  14886. }
  14887. // The reason we were replaced
  14888. let reason = "replaced";
  14889. if (tx.data === this.data && tx.to === this.to && tx.value === this.value) {
  14890. reason = "repriced";
  14891. }
  14892. else if (tx.data === "0x" && tx.from === tx.to && tx.value === BN_0$2) {
  14893. reason = "cancelled";
  14894. }
  14895. assert(false, "transaction was replaced", "TRANSACTION_REPLACED", {
  14896. cancelled: (reason === "replaced" || reason === "cancelled"),
  14897. reason,
  14898. replacement: tx.replaceableTransaction(startBlock),
  14899. hash: tx.hash,
  14900. receipt
  14901. });
  14902. }
  14903. }
  14904. nextScan++;
  14905. }
  14906. return;
  14907. };
  14908. const checkReceipt = (receipt) => {
  14909. if (receipt == null || receipt.status !== 0) {
  14910. return receipt;
  14911. }
  14912. assert(false, "transaction execution reverted", "CALL_EXCEPTION", {
  14913. action: "sendTransaction",
  14914. data: null, reason: null, invocation: null, revert: null,
  14915. transaction: {
  14916. to: receipt.to,
  14917. from: receipt.from,
  14918. data: "" // @TODO: in v7, split out sendTransaction properties
  14919. }, receipt
  14920. });
  14921. };
  14922. const receipt = await this.provider.getTransactionReceipt(this.hash);
  14923. if (confirms === 0) {
  14924. return checkReceipt(receipt);
  14925. }
  14926. if (receipt) {
  14927. if ((await receipt.confirmations()) >= confirms) {
  14928. return checkReceipt(receipt);
  14929. }
  14930. }
  14931. else {
  14932. // Check for a replacement; throws if a replacement was found
  14933. await checkReplacement();
  14934. // Allow null only when the confirms is 0
  14935. if (confirms === 0) {
  14936. return null;
  14937. }
  14938. }
  14939. const waiter = new Promise((resolve, reject) => {
  14940. // List of things to cancel when we have a result (one way or the other)
  14941. const cancellers = [];
  14942. const cancel = () => { cancellers.forEach((c) => c()); };
  14943. // On cancel, stop scanning for replacements
  14944. cancellers.push(() => { stopScanning = true; });
  14945. // Set up any timeout requested
  14946. if (timeout > 0) {
  14947. const timer = setTimeout(() => {
  14948. cancel();
  14949. reject(makeError("wait for transaction timeout", "TIMEOUT"));
  14950. }, timeout);
  14951. cancellers.push(() => { clearTimeout(timer); });
  14952. }
  14953. const txListener = async (receipt) => {
  14954. // Done; return it!
  14955. if ((await receipt.confirmations()) >= confirms) {
  14956. cancel();
  14957. try {
  14958. resolve(checkReceipt(receipt));
  14959. }
  14960. catch (error) {
  14961. reject(error);
  14962. }
  14963. }
  14964. };
  14965. cancellers.push(() => { this.provider.off(this.hash, txListener); });
  14966. this.provider.on(this.hash, txListener);
  14967. // We support replacement detection; start checking
  14968. if (startBlock >= 0) {
  14969. const replaceListener = async () => {
  14970. try {
  14971. // Check for a replacement; this throws only if one is found
  14972. await checkReplacement();
  14973. }
  14974. catch (error) {
  14975. // We were replaced (with enough confirms); re-throw the error
  14976. if (isError(error, "TRANSACTION_REPLACED")) {
  14977. cancel();
  14978. reject(error);
  14979. return;
  14980. }
  14981. }
  14982. // Rescheudle a check on the next block
  14983. if (!stopScanning) {
  14984. this.provider.once("block", replaceListener);
  14985. }
  14986. };
  14987. cancellers.push(() => { this.provider.off("block", replaceListener); });
  14988. this.provider.once("block", replaceListener);
  14989. }
  14990. });
  14991. return await waiter;
  14992. }
  14993. /**
  14994. * Returns ``true`` if this transaction has been included.
  14995. *
  14996. * This is effective only as of the time the TransactionResponse
  14997. * was instantiated. To get up-to-date information, use
  14998. * [[getTransaction]].
  14999. *
  15000. * This provides a Type Guard that this transaction will have
  15001. * non-null property values for properties that are null for
  15002. * unmined transactions.
  15003. */
  15004. isMined() {
  15005. return (this.blockHash != null);
  15006. }
  15007. /**
  15008. * Returns true if the transaction is a legacy (i.e. ``type == 0``)
  15009. * transaction.
  15010. *
  15011. * This provides a Type Guard that this transaction will have
  15012. * the ``null``-ness for hardfork-specific properties set correctly.
  15013. */
  15014. isLegacy() {
  15015. return (this.type === 0);
  15016. }
  15017. /**
  15018. * Returns true if the transaction is a Berlin (i.e. ``type == 1``)
  15019. * transaction. See [[link-eip-2070]].
  15020. *
  15021. * This provides a Type Guard that this transaction will have
  15022. * the ``null``-ness for hardfork-specific properties set correctly.
  15023. */
  15024. isBerlin() {
  15025. return (this.type === 1);
  15026. }
  15027. /**
  15028. * Returns true if the transaction is a London (i.e. ``type == 2``)
  15029. * transaction. See [[link-eip-1559]].
  15030. *
  15031. * This provides a Type Guard that this transaction will have
  15032. * the ``null``-ness for hardfork-specific properties set correctly.
  15033. */
  15034. isLondon() {
  15035. return (this.type === 2);
  15036. }
  15037. /**
  15038. * Returns true if hte transaction is a Cancun (i.e. ``type == 3``)
  15039. * transaction. See [[link-eip-4844]].
  15040. */
  15041. isCancun() {
  15042. return (this.type === 3);
  15043. }
  15044. /**
  15045. * Returns a filter which can be used to listen for orphan events
  15046. * that evict this transaction.
  15047. */
  15048. removedEvent() {
  15049. assert(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" });
  15050. return createRemovedTransactionFilter(this);
  15051. }
  15052. /**
  15053. * Returns a filter which can be used to listen for orphan events
  15054. * that re-order this event against %%other%%.
  15055. */
  15056. reorderedEvent(other) {
  15057. assert(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" });
  15058. assert(!other || other.isMined(), "unmined 'other' transaction canot be orphaned", "UNSUPPORTED_OPERATION", { operation: "removeEvent()" });
  15059. return createReorderedTransactionFilter(this, other);
  15060. }
  15061. /**
  15062. * Returns a new TransactionResponse instance which has the ability to
  15063. * detect (and throw an error) if the transaction is replaced, which
  15064. * will begin scanning at %%startBlock%%.
  15065. *
  15066. * This should generally not be used by developers and is intended
  15067. * primarily for internal use. Setting an incorrect %%startBlock%% can
  15068. * have devastating performance consequences if used incorrectly.
  15069. */
  15070. replaceableTransaction(startBlock) {
  15071. assertArgument(Number.isInteger(startBlock) && startBlock >= 0, "invalid startBlock", "startBlock", startBlock);
  15072. const tx = new TransactionResponse(this, this.provider);
  15073. tx.#startBlock = startBlock;
  15074. return tx;
  15075. }
  15076. }
  15077. function createOrphanedBlockFilter(block) {
  15078. return { orphan: "drop-block", hash: block.hash, number: block.number };
  15079. }
  15080. function createReorderedTransactionFilter(tx, other) {
  15081. return { orphan: "reorder-transaction", tx, other };
  15082. }
  15083. function createRemovedTransactionFilter(tx) {
  15084. return { orphan: "drop-transaction", tx };
  15085. }
  15086. function createRemovedLogFilter(log) {
  15087. return { orphan: "drop-log", log: {
  15088. transactionHash: log.transactionHash,
  15089. blockHash: log.blockHash,
  15090. blockNumber: log.blockNumber,
  15091. address: log.address,
  15092. data: log.data,
  15093. topics: Object.freeze(log.topics.slice()),
  15094. index: log.index
  15095. } };
  15096. }
  15097. // import from provider.ts instead of index.ts to prevent circular dep
  15098. // from EtherscanProvider
  15099. /**
  15100. * An **EventLog** contains additional properties parsed from the [[Log]].
  15101. */
  15102. class EventLog extends Log {
  15103. /**
  15104. * The Contract Interface.
  15105. */
  15106. interface;
  15107. /**
  15108. * The matching event.
  15109. */
  15110. fragment;
  15111. /**
  15112. * The parsed arguments passed to the event by ``emit``.
  15113. */
  15114. args;
  15115. /**
  15116. * @_ignore:
  15117. */
  15118. constructor(log, iface, fragment) {
  15119. super(log, log.provider);
  15120. const args = iface.decodeEventLog(fragment, log.data, log.topics);
  15121. defineProperties(this, { args, fragment, interface: iface });
  15122. }
  15123. /**
  15124. * The name of the event.
  15125. */
  15126. get eventName() { return this.fragment.name; }
  15127. /**
  15128. * The signature of the event.
  15129. */
  15130. get eventSignature() { return this.fragment.format(); }
  15131. }
  15132. /**
  15133. * An **EventLog** contains additional properties parsed from the [[Log]].
  15134. */
  15135. class UndecodedEventLog extends Log {
  15136. /**
  15137. * The error encounted when trying to decode the log.
  15138. */
  15139. error;
  15140. /**
  15141. * @_ignore:
  15142. */
  15143. constructor(log, error) {
  15144. super(log, log.provider);
  15145. defineProperties(this, { error });
  15146. }
  15147. }
  15148. /**
  15149. * A **ContractTransactionReceipt** includes the parsed logs from a
  15150. * [[TransactionReceipt]].
  15151. */
  15152. class ContractTransactionReceipt extends TransactionReceipt {
  15153. #iface;
  15154. /**
  15155. * @_ignore:
  15156. */
  15157. constructor(iface, provider, tx) {
  15158. super(tx, provider);
  15159. this.#iface = iface;
  15160. }
  15161. /**
  15162. * The parsed logs for any [[Log]] which has a matching event in the
  15163. * Contract ABI.
  15164. */
  15165. get logs() {
  15166. return super.logs.map((log) => {
  15167. const fragment = log.topics.length ? this.#iface.getEvent(log.topics[0]) : null;
  15168. if (fragment) {
  15169. try {
  15170. return new EventLog(log, this.#iface, fragment);
  15171. }
  15172. catch (error) {
  15173. return new UndecodedEventLog(log, error);
  15174. }
  15175. }
  15176. return log;
  15177. });
  15178. }
  15179. }
  15180. /**
  15181. * A **ContractTransactionResponse** will return a
  15182. * [[ContractTransactionReceipt]] when waited on.
  15183. */
  15184. class ContractTransactionResponse extends TransactionResponse {
  15185. #iface;
  15186. /**
  15187. * @_ignore:
  15188. */
  15189. constructor(iface, provider, tx) {
  15190. super(tx, provider);
  15191. this.#iface = iface;
  15192. }
  15193. /**
  15194. * Resolves once this transaction has been mined and has
  15195. * %%confirms%% blocks including it (default: ``1``) with an
  15196. * optional %%timeout%%.
  15197. *
  15198. * This can resolve to ``null`` only if %%confirms%% is ``0``
  15199. * and the transaction has not been mined, otherwise this will
  15200. * wait until enough confirmations have completed.
  15201. */
  15202. async wait(confirms, timeout) {
  15203. const receipt = await super.wait(confirms, timeout);
  15204. if (receipt == null) {
  15205. return null;
  15206. }
  15207. return new ContractTransactionReceipt(this.#iface, this.provider, receipt);
  15208. }
  15209. }
  15210. /**
  15211. * A **ContractUnknownEventPayload** is included as the last parameter to
  15212. * Contract Events when the event does not match any events in the ABI.
  15213. */
  15214. class ContractUnknownEventPayload extends EventPayload {
  15215. /**
  15216. * The log with no matching events.
  15217. */
  15218. log;
  15219. /**
  15220. * @_event:
  15221. */
  15222. constructor(contract, listener, filter, log) {
  15223. super(contract, listener, filter);
  15224. defineProperties(this, { log });
  15225. }
  15226. /**
  15227. * Resolves to the block the event occured in.
  15228. */
  15229. async getBlock() {
  15230. return await this.log.getBlock();
  15231. }
  15232. /**
  15233. * Resolves to the transaction the event occured in.
  15234. */
  15235. async getTransaction() {
  15236. return await this.log.getTransaction();
  15237. }
  15238. /**
  15239. * Resolves to the transaction receipt the event occured in.
  15240. */
  15241. async getTransactionReceipt() {
  15242. return await this.log.getTransactionReceipt();
  15243. }
  15244. }
  15245. /**
  15246. * A **ContractEventPayload** is included as the last parameter to
  15247. * Contract Events when the event is known.
  15248. */
  15249. class ContractEventPayload extends ContractUnknownEventPayload {
  15250. /**
  15251. * @_ignore:
  15252. */
  15253. constructor(contract, listener, filter, fragment, _log) {
  15254. super(contract, listener, filter, new EventLog(_log, contract.interface, fragment));
  15255. const args = contract.interface.decodeEventLog(fragment, this.log.data, this.log.topics);
  15256. defineProperties(this, { args, fragment });
  15257. }
  15258. /**
  15259. * The event name.
  15260. */
  15261. get eventName() {
  15262. return this.fragment.name;
  15263. }
  15264. /**
  15265. * The event signature.
  15266. */
  15267. get eventSignature() {
  15268. return this.fragment.format();
  15269. }
  15270. }
  15271. const BN_0$1 = BigInt(0);
  15272. function canCall(value) {
  15273. return (value && typeof (value.call) === "function");
  15274. }
  15275. function canEstimate(value) {
  15276. return (value && typeof (value.estimateGas) === "function");
  15277. }
  15278. function canResolve(value) {
  15279. return (value && typeof (value.resolveName) === "function");
  15280. }
  15281. function canSend(value) {
  15282. return (value && typeof (value.sendTransaction) === "function");
  15283. }
  15284. function getResolver(value) {
  15285. if (value != null) {
  15286. if (canResolve(value)) {
  15287. return value;
  15288. }
  15289. if (value.provider) {
  15290. return value.provider;
  15291. }
  15292. }
  15293. return undefined;
  15294. }
  15295. class PreparedTopicFilter {
  15296. #filter;
  15297. fragment;
  15298. constructor(contract, fragment, args) {
  15299. defineProperties(this, { fragment });
  15300. if (fragment.inputs.length < args.length) {
  15301. throw new Error("too many arguments");
  15302. }
  15303. // Recursively descend into args and resolve any addresses
  15304. const runner = getRunner(contract.runner, "resolveName");
  15305. const resolver = canResolve(runner) ? runner : null;
  15306. this.#filter = (async function () {
  15307. const resolvedArgs = await Promise.all(fragment.inputs.map((param, index) => {
  15308. const arg = args[index];
  15309. if (arg == null) {
  15310. return null;
  15311. }
  15312. return param.walkAsync(args[index], (type, value) => {
  15313. if (type === "address") {
  15314. if (Array.isArray(value)) {
  15315. return Promise.all(value.map((v) => resolveAddress(v, resolver)));
  15316. }
  15317. return resolveAddress(value, resolver);
  15318. }
  15319. return value;
  15320. });
  15321. }));
  15322. return contract.interface.encodeFilterTopics(fragment, resolvedArgs);
  15323. })();
  15324. }
  15325. getTopicFilter() {
  15326. return this.#filter;
  15327. }
  15328. }
  15329. // A = Arguments passed in as a tuple
  15330. // R = The result type of the call (i.e. if only one return type,
  15331. // the qualified type, otherwise Result)
  15332. // D = The type the default call will return (i.e. R for view/pure,
  15333. // TransactionResponse otherwise)
  15334. //export interface ContractMethod<A extends Array<any> = Array<any>, R = any, D extends R | ContractTransactionResponse = ContractTransactionResponse> {
  15335. function getRunner(value, feature) {
  15336. if (value == null) {
  15337. return null;
  15338. }
  15339. if (typeof (value[feature]) === "function") {
  15340. return value;
  15341. }
  15342. if (value.provider && typeof (value.provider[feature]) === "function") {
  15343. return value.provider;
  15344. }
  15345. return null;
  15346. }
  15347. function getProvider(value) {
  15348. if (value == null) {
  15349. return null;
  15350. }
  15351. return value.provider || null;
  15352. }
  15353. /**
  15354. * @_ignore:
  15355. */
  15356. async function copyOverrides(arg, allowed) {
  15357. // Make sure the overrides passed in are a valid overrides object
  15358. const _overrides = Typed.dereference(arg, "overrides");
  15359. assertArgument(typeof (_overrides) === "object", "invalid overrides parameter", "overrides", arg);
  15360. // Create a shallow copy (we'll deep-ify anything needed during normalizing)
  15361. const overrides = copyRequest(_overrides);
  15362. assertArgument(overrides.to == null || (allowed || []).indexOf("to") >= 0, "cannot override to", "overrides.to", overrides.to);
  15363. assertArgument(overrides.data == null || (allowed || []).indexOf("data") >= 0, "cannot override data", "overrides.data", overrides.data);
  15364. // Resolve any from
  15365. if (overrides.from) {
  15366. overrides.from = overrides.from;
  15367. }
  15368. return overrides;
  15369. }
  15370. /**
  15371. * @_ignore:
  15372. */
  15373. async function resolveArgs(_runner, inputs, args) {
  15374. // Recursively descend into args and resolve any addresses
  15375. const runner = getRunner(_runner, "resolveName");
  15376. const resolver = canResolve(runner) ? runner : null;
  15377. return await Promise.all(inputs.map((param, index) => {
  15378. return param.walkAsync(args[index], (type, value) => {
  15379. value = Typed.dereference(value, type);
  15380. if (type === "address") {
  15381. return resolveAddress(value, resolver);
  15382. }
  15383. return value;
  15384. });
  15385. }));
  15386. }
  15387. function buildWrappedFallback(contract) {
  15388. const populateTransaction = async function (overrides) {
  15389. // If an overrides was passed in, copy it and normalize the values
  15390. const tx = (await copyOverrides(overrides, ["data"]));
  15391. tx.to = await contract.getAddress();
  15392. if (tx.from) {
  15393. tx.from = await resolveAddress(tx.from, getResolver(contract.runner));
  15394. }
  15395. const iface = contract.interface;
  15396. const noValue = (getBigInt((tx.value || BN_0$1), "overrides.value") === BN_0$1);
  15397. const noData = ((tx.data || "0x") === "0x");
  15398. if (iface.fallback && !iface.fallback.payable && iface.receive && !noData && !noValue) {
  15399. assertArgument(false, "cannot send data to receive or send value to non-payable fallback", "overrides", overrides);
  15400. }
  15401. assertArgument(iface.fallback || noData, "cannot send data to receive-only contract", "overrides.data", tx.data);
  15402. // Only allow payable contracts to set non-zero value
  15403. const payable = iface.receive || (iface.fallback && iface.fallback.payable);
  15404. assertArgument(payable || noValue, "cannot send value to non-payable fallback", "overrides.value", tx.value);
  15405. // Only allow fallback contracts to set non-empty data
  15406. assertArgument(iface.fallback || noData, "cannot send data to receive-only contract", "overrides.data", tx.data);
  15407. return tx;
  15408. };
  15409. const staticCall = async function (overrides) {
  15410. const runner = getRunner(contract.runner, "call");
  15411. assert(canCall(runner), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { operation: "call" });
  15412. const tx = await populateTransaction(overrides);
  15413. try {
  15414. return await runner.call(tx);
  15415. }
  15416. catch (error) {
  15417. if (isCallException(error) && error.data) {
  15418. throw contract.interface.makeError(error.data, tx);
  15419. }
  15420. throw error;
  15421. }
  15422. };
  15423. const send = async function (overrides) {
  15424. const runner = contract.runner;
  15425. assert(canSend(runner), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { operation: "sendTransaction" });
  15426. const tx = await runner.sendTransaction(await populateTransaction(overrides));
  15427. const provider = getProvider(contract.runner);
  15428. // @TODO: the provider can be null; make a custom dummy provider that will throw a
  15429. // meaningful error
  15430. return new ContractTransactionResponse(contract.interface, provider, tx);
  15431. };
  15432. const estimateGas = async function (overrides) {
  15433. const runner = getRunner(contract.runner, "estimateGas");
  15434. assert(canEstimate(runner), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { operation: "estimateGas" });
  15435. return await runner.estimateGas(await populateTransaction(overrides));
  15436. };
  15437. const method = async (overrides) => {
  15438. return await send(overrides);
  15439. };
  15440. defineProperties(method, {
  15441. _contract: contract,
  15442. estimateGas,
  15443. populateTransaction,
  15444. send, staticCall
  15445. });
  15446. return method;
  15447. }
  15448. function buildWrappedMethod(contract, key) {
  15449. const getFragment = function (...args) {
  15450. const fragment = contract.interface.getFunction(key, args);
  15451. assert(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", {
  15452. operation: "fragment",
  15453. info: { key, args }
  15454. });
  15455. return fragment;
  15456. };
  15457. const populateTransaction = async function (...args) {
  15458. const fragment = getFragment(...args);
  15459. // If an overrides was passed in, copy it and normalize the values
  15460. let overrides = {};
  15461. if (fragment.inputs.length + 1 === args.length) {
  15462. overrides = await copyOverrides(args.pop());
  15463. if (overrides.from) {
  15464. overrides.from = await resolveAddress(overrides.from, getResolver(contract.runner));
  15465. }
  15466. }
  15467. if (fragment.inputs.length !== args.length) {
  15468. throw new Error("internal error: fragment inputs doesn't match arguments; should not happen");
  15469. }
  15470. const resolvedArgs = await resolveArgs(contract.runner, fragment.inputs, args);
  15471. return Object.assign({}, overrides, await resolveProperties({
  15472. to: contract.getAddress(),
  15473. data: contract.interface.encodeFunctionData(fragment, resolvedArgs)
  15474. }));
  15475. };
  15476. const staticCall = async function (...args) {
  15477. const result = await staticCallResult(...args);
  15478. if (result.length === 1) {
  15479. return result[0];
  15480. }
  15481. return result;
  15482. };
  15483. const send = async function (...args) {
  15484. const runner = contract.runner;
  15485. assert(canSend(runner), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { operation: "sendTransaction" });
  15486. const tx = await runner.sendTransaction(await populateTransaction(...args));
  15487. const provider = getProvider(contract.runner);
  15488. // @TODO: the provider can be null; make a custom dummy provider that will throw a
  15489. // meaningful error
  15490. return new ContractTransactionResponse(contract.interface, provider, tx);
  15491. };
  15492. const estimateGas = async function (...args) {
  15493. const runner = getRunner(contract.runner, "estimateGas");
  15494. assert(canEstimate(runner), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { operation: "estimateGas" });
  15495. return await runner.estimateGas(await populateTransaction(...args));
  15496. };
  15497. const staticCallResult = async function (...args) {
  15498. const runner = getRunner(contract.runner, "call");
  15499. assert(canCall(runner), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { operation: "call" });
  15500. const tx = await populateTransaction(...args);
  15501. let result = "0x";
  15502. try {
  15503. result = await runner.call(tx);
  15504. }
  15505. catch (error) {
  15506. if (isCallException(error) && error.data) {
  15507. throw contract.interface.makeError(error.data, tx);
  15508. }
  15509. throw error;
  15510. }
  15511. const fragment = getFragment(...args);
  15512. return contract.interface.decodeFunctionResult(fragment, result);
  15513. };
  15514. const method = async (...args) => {
  15515. const fragment = getFragment(...args);
  15516. if (fragment.constant) {
  15517. return await staticCall(...args);
  15518. }
  15519. return await send(...args);
  15520. };
  15521. defineProperties(method, {
  15522. name: contract.interface.getFunctionName(key),
  15523. _contract: contract, _key: key,
  15524. getFragment,
  15525. estimateGas,
  15526. populateTransaction,
  15527. send, staticCall, staticCallResult,
  15528. });
  15529. // Only works on non-ambiguous keys (refined fragment is always non-ambiguous)
  15530. Object.defineProperty(method, "fragment", {
  15531. configurable: false,
  15532. enumerable: true,
  15533. get: () => {
  15534. const fragment = contract.interface.getFunction(key);
  15535. assert(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", {
  15536. operation: "fragment",
  15537. info: { key }
  15538. });
  15539. return fragment;
  15540. }
  15541. });
  15542. return method;
  15543. }
  15544. function buildWrappedEvent(contract, key) {
  15545. const getFragment = function (...args) {
  15546. const fragment = contract.interface.getEvent(key, args);
  15547. assert(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", {
  15548. operation: "fragment",
  15549. info: { key, args }
  15550. });
  15551. return fragment;
  15552. };
  15553. const method = function (...args) {
  15554. return new PreparedTopicFilter(contract, getFragment(...args), args);
  15555. };
  15556. defineProperties(method, {
  15557. name: contract.interface.getEventName(key),
  15558. _contract: contract, _key: key,
  15559. getFragment
  15560. });
  15561. // Only works on non-ambiguous keys (refined fragment is always non-ambiguous)
  15562. Object.defineProperty(method, "fragment", {
  15563. configurable: false,
  15564. enumerable: true,
  15565. get: () => {
  15566. const fragment = contract.interface.getEvent(key);
  15567. assert(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", {
  15568. operation: "fragment",
  15569. info: { key }
  15570. });
  15571. return fragment;
  15572. }
  15573. });
  15574. return method;
  15575. }
  15576. // The combination of TypeScrype, Private Fields and Proxies makes
  15577. // the world go boom; so we hide variables with some trickery keeping
  15578. // a symbol attached to each BaseContract which its sub-class (even
  15579. // via a Proxy) can reach and use to look up its internal values.
  15580. const internal = Symbol.for("_ethersInternal_contract");
  15581. const internalValues = new WeakMap();
  15582. function setInternal(contract, values) {
  15583. internalValues.set(contract[internal], values);
  15584. }
  15585. function getInternal(contract) {
  15586. return internalValues.get(contract[internal]);
  15587. }
  15588. function isDeferred(value) {
  15589. return (value && typeof (value) === "object" && ("getTopicFilter" in value) &&
  15590. (typeof (value.getTopicFilter) === "function") && value.fragment);
  15591. }
  15592. async function getSubInfo(contract, event) {
  15593. let topics;
  15594. let fragment = null;
  15595. // Convert named events to topicHash and get the fragment for
  15596. // events which need deconstructing.
  15597. if (Array.isArray(event)) {
  15598. const topicHashify = function (name) {
  15599. if (isHexString(name, 32)) {
  15600. return name;
  15601. }
  15602. const fragment = contract.interface.getEvent(name);
  15603. assertArgument(fragment, "unknown fragment", "name", name);
  15604. return fragment.topicHash;
  15605. };
  15606. // Array of Topics and Names; e.g. `[ "0x1234...89ab", "Transfer(address)" ]`
  15607. topics = event.map((e) => {
  15608. if (e == null) {
  15609. return null;
  15610. }
  15611. if (Array.isArray(e)) {
  15612. return e.map(topicHashify);
  15613. }
  15614. return topicHashify(e);
  15615. });
  15616. }
  15617. else if (event === "*") {
  15618. topics = [null];
  15619. }
  15620. else if (typeof (event) === "string") {
  15621. if (isHexString(event, 32)) {
  15622. // Topic Hash
  15623. topics = [event];
  15624. }
  15625. else {
  15626. // Name or Signature; e.g. `"Transfer", `"Transfer(address)"`
  15627. fragment = contract.interface.getEvent(event);
  15628. assertArgument(fragment, "unknown fragment", "event", event);
  15629. topics = [fragment.topicHash];
  15630. }
  15631. }
  15632. else if (isDeferred(event)) {
  15633. // Deferred Topic Filter; e.g. `contract.filter.Transfer(from)`
  15634. topics = await event.getTopicFilter();
  15635. }
  15636. else if ("fragment" in event) {
  15637. // ContractEvent; e.g. `contract.filter.Transfer`
  15638. fragment = event.fragment;
  15639. topics = [fragment.topicHash];
  15640. }
  15641. else {
  15642. assertArgument(false, "unknown event name", "event", event);
  15643. }
  15644. // Normalize topics and sort TopicSets
  15645. topics = topics.map((t) => {
  15646. if (t == null) {
  15647. return null;
  15648. }
  15649. if (Array.isArray(t)) {
  15650. const items = Array.from(new Set(t.map((t) => t.toLowerCase())).values());
  15651. if (items.length === 1) {
  15652. return items[0];
  15653. }
  15654. items.sort();
  15655. return items;
  15656. }
  15657. return t.toLowerCase();
  15658. });
  15659. const tag = topics.map((t) => {
  15660. if (t == null) {
  15661. return "null";
  15662. }
  15663. if (Array.isArray(t)) {
  15664. return t.join("|");
  15665. }
  15666. return t;
  15667. }).join("&");
  15668. return { fragment, tag, topics };
  15669. }
  15670. async function hasSub(contract, event) {
  15671. const { subs } = getInternal(contract);
  15672. return subs.get((await getSubInfo(contract, event)).tag) || null;
  15673. }
  15674. async function getSub(contract, operation, event) {
  15675. // Make sure our runner can actually subscribe to events
  15676. const provider = getProvider(contract.runner);
  15677. assert(provider, "contract runner does not support subscribing", "UNSUPPORTED_OPERATION", { operation });
  15678. const { fragment, tag, topics } = await getSubInfo(contract, event);
  15679. const { addr, subs } = getInternal(contract);
  15680. let sub = subs.get(tag);
  15681. if (!sub) {
  15682. const address = (addr ? addr : contract);
  15683. const filter = { address, topics };
  15684. const listener = (log) => {
  15685. let foundFragment = fragment;
  15686. if (foundFragment == null) {
  15687. try {
  15688. foundFragment = contract.interface.getEvent(log.topics[0]);
  15689. }
  15690. catch (error) { }
  15691. }
  15692. // If fragment is null, we do not deconstruct the args to emit
  15693. if (foundFragment) {
  15694. const _foundFragment = foundFragment;
  15695. const args = fragment ? contract.interface.decodeEventLog(fragment, log.data, log.topics) : [];
  15696. emit(contract, event, args, (listener) => {
  15697. return new ContractEventPayload(contract, listener, event, _foundFragment, log);
  15698. });
  15699. }
  15700. else {
  15701. emit(contract, event, [], (listener) => {
  15702. return new ContractUnknownEventPayload(contract, listener, event, log);
  15703. });
  15704. }
  15705. };
  15706. let starting = [];
  15707. const start = () => {
  15708. if (starting.length) {
  15709. return;
  15710. }
  15711. starting.push(provider.on(filter, listener));
  15712. };
  15713. const stop = async () => {
  15714. if (starting.length == 0) {
  15715. return;
  15716. }
  15717. let started = starting;
  15718. starting = [];
  15719. await Promise.all(started);
  15720. provider.off(filter, listener);
  15721. };
  15722. sub = { tag, listeners: [], start, stop };
  15723. subs.set(tag, sub);
  15724. }
  15725. return sub;
  15726. }
  15727. // We use this to ensure one emit resolves before firing the next to
  15728. // ensure correct ordering (note this cannot throw and just adds the
  15729. // notice to the event queu using setTimeout).
  15730. let lastEmit = Promise.resolve();
  15731. async function _emit(contract, event, args, payloadFunc) {
  15732. await lastEmit;
  15733. const sub = await hasSub(contract, event);
  15734. if (!sub) {
  15735. return false;
  15736. }
  15737. const count = sub.listeners.length;
  15738. sub.listeners = sub.listeners.filter(({ listener, once }) => {
  15739. const passArgs = Array.from(args);
  15740. if (payloadFunc) {
  15741. passArgs.push(payloadFunc(once ? null : listener));
  15742. }
  15743. try {
  15744. listener.call(contract, ...passArgs);
  15745. }
  15746. catch (error) { }
  15747. return !once;
  15748. });
  15749. if (sub.listeners.length === 0) {
  15750. sub.stop();
  15751. getInternal(contract).subs.delete(sub.tag);
  15752. }
  15753. return (count > 0);
  15754. }
  15755. async function emit(contract, event, args, payloadFunc) {
  15756. try {
  15757. await lastEmit;
  15758. }
  15759. catch (error) { }
  15760. const resultPromise = _emit(contract, event, args, payloadFunc);
  15761. lastEmit = resultPromise;
  15762. return await resultPromise;
  15763. }
  15764. const passProperties = ["then"];
  15765. class BaseContract {
  15766. /**
  15767. * The target to connect to.
  15768. *
  15769. * This can be an address, ENS name or any [[Addressable]], such as
  15770. * another contract. To get the resovled address, use the ``getAddress``
  15771. * method.
  15772. */
  15773. target;
  15774. /**
  15775. * The contract Interface.
  15776. */
  15777. interface;
  15778. /**
  15779. * The connected runner. This is generally a [[Provider]] or a
  15780. * [[Signer]], which dictates what operations are supported.
  15781. *
  15782. * For example, a **Contract** connected to a [[Provider]] may
  15783. * only execute read-only operations.
  15784. */
  15785. runner;
  15786. /**
  15787. * All the Events available on this contract.
  15788. */
  15789. filters;
  15790. /**
  15791. * @_ignore:
  15792. */
  15793. [internal];
  15794. /**
  15795. * The fallback or receive function if any.
  15796. */
  15797. fallback;
  15798. /**
  15799. * Creates a new contract connected to %%target%% with the %%abi%% and
  15800. * optionally connected to a %%runner%% to perform operations on behalf
  15801. * of.
  15802. */
  15803. constructor(target, abi, runner, _deployTx) {
  15804. assertArgument(typeof (target) === "string" || isAddressable(target), "invalid value for Contract target", "target", target);
  15805. if (runner == null) {
  15806. runner = null;
  15807. }
  15808. const iface = Interface.from(abi);
  15809. defineProperties(this, { target, runner, interface: iface });
  15810. Object.defineProperty(this, internal, { value: {} });
  15811. let addrPromise;
  15812. let addr = null;
  15813. let deployTx = null;
  15814. if (_deployTx) {
  15815. const provider = getProvider(runner);
  15816. // @TODO: the provider can be null; make a custom dummy provider that will throw a
  15817. // meaningful error
  15818. deployTx = new ContractTransactionResponse(this.interface, provider, _deployTx);
  15819. }
  15820. let subs = new Map();
  15821. // Resolve the target as the address
  15822. if (typeof (target) === "string") {
  15823. if (isHexString(target)) {
  15824. addr = target;
  15825. addrPromise = Promise.resolve(target);
  15826. }
  15827. else {
  15828. const resolver = getRunner(runner, "resolveName");
  15829. if (!canResolve(resolver)) {
  15830. throw makeError("contract runner does not support name resolution", "UNSUPPORTED_OPERATION", {
  15831. operation: "resolveName"
  15832. });
  15833. }
  15834. addrPromise = resolver.resolveName(target).then((addr) => {
  15835. if (addr == null) {
  15836. throw makeError("an ENS name used for a contract target must be correctly configured", "UNCONFIGURED_NAME", {
  15837. value: target
  15838. });
  15839. }
  15840. getInternal(this).addr = addr;
  15841. return addr;
  15842. });
  15843. }
  15844. }
  15845. else {
  15846. addrPromise = target.getAddress().then((addr) => {
  15847. if (addr == null) {
  15848. throw new Error("TODO");
  15849. }
  15850. getInternal(this).addr = addr;
  15851. return addr;
  15852. });
  15853. }
  15854. // Set our private values
  15855. setInternal(this, { addrPromise, addr, deployTx, subs });
  15856. // Add the event filters
  15857. const filters = new Proxy({}, {
  15858. get: (target, prop, receiver) => {
  15859. // Pass important checks (like `then` for Promise) through
  15860. if (typeof (prop) === "symbol" || passProperties.indexOf(prop) >= 0) {
  15861. return Reflect.get(target, prop, receiver);
  15862. }
  15863. try {
  15864. return this.getEvent(prop);
  15865. }
  15866. catch (error) {
  15867. if (!isError(error, "INVALID_ARGUMENT") || error.argument !== "key") {
  15868. throw error;
  15869. }
  15870. }
  15871. return undefined;
  15872. },
  15873. has: (target, prop) => {
  15874. // Pass important checks (like `then` for Promise) through
  15875. if (passProperties.indexOf(prop) >= 0) {
  15876. return Reflect.has(target, prop);
  15877. }
  15878. return Reflect.has(target, prop) || this.interface.hasEvent(String(prop));
  15879. }
  15880. });
  15881. defineProperties(this, { filters });
  15882. defineProperties(this, {
  15883. fallback: ((iface.receive || iface.fallback) ? (buildWrappedFallback(this)) : null)
  15884. });
  15885. // Return a Proxy that will respond to functions
  15886. return new Proxy(this, {
  15887. get: (target, prop, receiver) => {
  15888. if (typeof (prop) === "symbol" || prop in target || passProperties.indexOf(prop) >= 0) {
  15889. return Reflect.get(target, prop, receiver);
  15890. }
  15891. // Undefined properties should return undefined
  15892. try {
  15893. return target.getFunction(prop);
  15894. }
  15895. catch (error) {
  15896. if (!isError(error, "INVALID_ARGUMENT") || error.argument !== "key") {
  15897. throw error;
  15898. }
  15899. }
  15900. return undefined;
  15901. },
  15902. has: (target, prop) => {
  15903. if (typeof (prop) === "symbol" || prop in target || passProperties.indexOf(prop) >= 0) {
  15904. return Reflect.has(target, prop);
  15905. }
  15906. return target.interface.hasFunction(prop);
  15907. }
  15908. });
  15909. }
  15910. /**
  15911. * Return a new Contract instance with the same target and ABI, but
  15912. * a different %%runner%%.
  15913. */
  15914. connect(runner) {
  15915. return new BaseContract(this.target, this.interface, runner);
  15916. }
  15917. /**
  15918. * Return a new Contract instance with the same ABI and runner, but
  15919. * a different %%target%%.
  15920. */
  15921. attach(target) {
  15922. return new BaseContract(target, this.interface, this.runner);
  15923. }
  15924. /**
  15925. * Return the resolved address of this Contract.
  15926. */
  15927. async getAddress() { return await getInternal(this).addrPromise; }
  15928. /**
  15929. * Return the deployed bytecode or null if no bytecode is found.
  15930. */
  15931. async getDeployedCode() {
  15932. const provider = getProvider(this.runner);
  15933. assert(provider, "runner does not support .provider", "UNSUPPORTED_OPERATION", { operation: "getDeployedCode" });
  15934. const code = await provider.getCode(await this.getAddress());
  15935. if (code === "0x") {
  15936. return null;
  15937. }
  15938. return code;
  15939. }
  15940. /**
  15941. * Resolve to this Contract once the bytecode has been deployed, or
  15942. * resolve immediately if already deployed.
  15943. */
  15944. async waitForDeployment() {
  15945. // We have the deployement transaction; just use that (throws if deployement fails)
  15946. const deployTx = this.deploymentTransaction();
  15947. if (deployTx) {
  15948. await deployTx.wait();
  15949. return this;
  15950. }
  15951. // Check for code
  15952. const code = await this.getDeployedCode();
  15953. if (code != null) {
  15954. return this;
  15955. }
  15956. // Make sure we can subscribe to a provider event
  15957. const provider = getProvider(this.runner);
  15958. assert(provider != null, "contract runner does not support .provider", "UNSUPPORTED_OPERATION", { operation: "waitForDeployment" });
  15959. return new Promise((resolve, reject) => {
  15960. const checkCode = async () => {
  15961. try {
  15962. const code = await this.getDeployedCode();
  15963. if (code != null) {
  15964. return resolve(this);
  15965. }
  15966. provider.once("block", checkCode);
  15967. }
  15968. catch (error) {
  15969. reject(error);
  15970. }
  15971. };
  15972. checkCode();
  15973. });
  15974. }
  15975. /**
  15976. * Return the transaction used to deploy this contract.
  15977. *
  15978. * This is only available if this instance was returned from a
  15979. * [[ContractFactory]].
  15980. */
  15981. deploymentTransaction() {
  15982. return getInternal(this).deployTx;
  15983. }
  15984. /**
  15985. * Return the function for a given name. This is useful when a contract
  15986. * method name conflicts with a JavaScript name such as ``prototype`` or
  15987. * when using a Contract programatically.
  15988. */
  15989. getFunction(key) {
  15990. if (typeof (key) !== "string") {
  15991. key = key.format();
  15992. }
  15993. const func = buildWrappedMethod(this, key);
  15994. return func;
  15995. }
  15996. /**
  15997. * Return the event for a given name. This is useful when a contract
  15998. * event name conflicts with a JavaScript name such as ``prototype`` or
  15999. * when using a Contract programatically.
  16000. */
  16001. getEvent(key) {
  16002. if (typeof (key) !== "string") {
  16003. key = key.format();
  16004. }
  16005. return buildWrappedEvent(this, key);
  16006. }
  16007. /**
  16008. * @_ignore:
  16009. */
  16010. async queryTransaction(hash) {
  16011. throw new Error("@TODO");
  16012. }
  16013. /*
  16014. // @TODO: this is a non-backwards compatible change, but will be added
  16015. // in v7 and in a potential SmartContract class in an upcoming
  16016. // v6 release
  16017. async getTransactionReceipt(hash: string): Promise<null | ContractTransactionReceipt> {
  16018. const provider = getProvider(this.runner);
  16019. assert(provider, "contract runner does not have a provider",
  16020. "UNSUPPORTED_OPERATION", { operation: "queryTransaction" });
  16021. const receipt = await provider.getTransactionReceipt(hash);
  16022. if (receipt == null) { return null; }
  16023. return new ContractTransactionReceipt(this.interface, provider, receipt);
  16024. }
  16025. */
  16026. /**
  16027. * Provide historic access to event data for %%event%% in the range
  16028. * %%fromBlock%% (default: ``0``) to %%toBlock%% (default: ``"latest"``)
  16029. * inclusive.
  16030. */
  16031. async queryFilter(event, fromBlock, toBlock) {
  16032. if (fromBlock == null) {
  16033. fromBlock = 0;
  16034. }
  16035. if (toBlock == null) {
  16036. toBlock = "latest";
  16037. }
  16038. const { addr, addrPromise } = getInternal(this);
  16039. const address = (addr ? addr : (await addrPromise));
  16040. const { fragment, topics } = await getSubInfo(this, event);
  16041. const filter = { address, topics, fromBlock, toBlock };
  16042. const provider = getProvider(this.runner);
  16043. assert(provider, "contract runner does not have a provider", "UNSUPPORTED_OPERATION", { operation: "queryFilter" });
  16044. return (await provider.getLogs(filter)).map((log) => {
  16045. let foundFragment = fragment;
  16046. if (foundFragment == null) {
  16047. try {
  16048. foundFragment = this.interface.getEvent(log.topics[0]);
  16049. }
  16050. catch (error) { }
  16051. }
  16052. if (foundFragment) {
  16053. try {
  16054. return new EventLog(log, this.interface, foundFragment);
  16055. }
  16056. catch (error) {
  16057. return new UndecodedEventLog(log, error);
  16058. }
  16059. }
  16060. return new Log(log, provider);
  16061. });
  16062. }
  16063. /**
  16064. * Add an event %%listener%% for the %%event%%.
  16065. */
  16066. async on(event, listener) {
  16067. const sub = await getSub(this, "on", event);
  16068. sub.listeners.push({ listener, once: false });
  16069. sub.start();
  16070. return this;
  16071. }
  16072. /**
  16073. * Add an event %%listener%% for the %%event%%, but remove the listener
  16074. * after it is fired once.
  16075. */
  16076. async once(event, listener) {
  16077. const sub = await getSub(this, "once", event);
  16078. sub.listeners.push({ listener, once: true });
  16079. sub.start();
  16080. return this;
  16081. }
  16082. /**
  16083. * Emit an %%event%% calling all listeners with %%args%%.
  16084. *
  16085. * Resolves to ``true`` if any listeners were called.
  16086. */
  16087. async emit(event, ...args) {
  16088. return await emit(this, event, args, null);
  16089. }
  16090. /**
  16091. * Resolves to the number of listeners of %%event%% or the total number
  16092. * of listeners if unspecified.
  16093. */
  16094. async listenerCount(event) {
  16095. if (event) {
  16096. const sub = await hasSub(this, event);
  16097. if (!sub) {
  16098. return 0;
  16099. }
  16100. return sub.listeners.length;
  16101. }
  16102. const { subs } = getInternal(this);
  16103. let total = 0;
  16104. for (const { listeners } of subs.values()) {
  16105. total += listeners.length;
  16106. }
  16107. return total;
  16108. }
  16109. /**
  16110. * Resolves to the listeners subscribed to %%event%% or all listeners
  16111. * if unspecified.
  16112. */
  16113. async listeners(event) {
  16114. if (event) {
  16115. const sub = await hasSub(this, event);
  16116. if (!sub) {
  16117. return [];
  16118. }
  16119. return sub.listeners.map(({ listener }) => listener);
  16120. }
  16121. const { subs } = getInternal(this);
  16122. let result = [];
  16123. for (const { listeners } of subs.values()) {
  16124. result = result.concat(listeners.map(({ listener }) => listener));
  16125. }
  16126. return result;
  16127. }
  16128. /**
  16129. * Remove the %%listener%% from the listeners for %%event%% or remove
  16130. * all listeners if unspecified.
  16131. */
  16132. async off(event, listener) {
  16133. const sub = await hasSub(this, event);
  16134. if (!sub) {
  16135. return this;
  16136. }
  16137. if (listener) {
  16138. const index = sub.listeners.map(({ listener }) => listener).indexOf(listener);
  16139. if (index >= 0) {
  16140. sub.listeners.splice(index, 1);
  16141. }
  16142. }
  16143. if (listener == null || sub.listeners.length === 0) {
  16144. sub.stop();
  16145. getInternal(this).subs.delete(sub.tag);
  16146. }
  16147. return this;
  16148. }
  16149. /**
  16150. * Remove all the listeners for %%event%% or remove all listeners if
  16151. * unspecified.
  16152. */
  16153. async removeAllListeners(event) {
  16154. if (event) {
  16155. const sub = await hasSub(this, event);
  16156. if (!sub) {
  16157. return this;
  16158. }
  16159. sub.stop();
  16160. getInternal(this).subs.delete(sub.tag);
  16161. }
  16162. else {
  16163. const { subs } = getInternal(this);
  16164. for (const { tag, stop } of subs.values()) {
  16165. stop();
  16166. subs.delete(tag);
  16167. }
  16168. }
  16169. return this;
  16170. }
  16171. /**
  16172. * Alias for [on].
  16173. */
  16174. async addListener(event, listener) {
  16175. return await this.on(event, listener);
  16176. }
  16177. /**
  16178. * Alias for [off].
  16179. */
  16180. async removeListener(event, listener) {
  16181. return await this.off(event, listener);
  16182. }
  16183. /**
  16184. * Create a new Class for the %%abi%%.
  16185. */
  16186. static buildClass(abi) {
  16187. class CustomContract extends BaseContract {
  16188. constructor(address, runner = null) {
  16189. super(address, abi, runner);
  16190. }
  16191. }
  16192. return CustomContract;
  16193. }
  16194. ;
  16195. /**
  16196. * Create a new BaseContract with a specified Interface.
  16197. */
  16198. static from(target, abi, runner) {
  16199. if (runner == null) {
  16200. runner = null;
  16201. }
  16202. const contract = new this(target, abi, runner);
  16203. return contract;
  16204. }
  16205. }
  16206. function _ContractBase() {
  16207. return BaseContract;
  16208. }
  16209. /**
  16210. * A [[BaseContract]] with no type guards on its methods or events.
  16211. */
  16212. class Contract extends _ContractBase() {
  16213. }
  16214. // A = Arguments to the constructor
  16215. // I = Interface of deployed contracts
  16216. /**
  16217. * A **ContractFactory** is used to deploy a Contract to the blockchain.
  16218. */
  16219. class ContractFactory {
  16220. /**
  16221. * The Contract Interface.
  16222. */
  16223. interface;
  16224. /**
  16225. * The Contract deployment bytecode. Often called the initcode.
  16226. */
  16227. bytecode;
  16228. /**
  16229. * The ContractRunner to deploy the Contract as.
  16230. */
  16231. runner;
  16232. /**
  16233. * Create a new **ContractFactory** with %%abi%% and %%bytecode%%,
  16234. * optionally connected to %%runner%%.
  16235. *
  16236. * The %%bytecode%% may be the ``bytecode`` property within the
  16237. * standard Solidity JSON output.
  16238. */
  16239. constructor(abi, bytecode, runner) {
  16240. const iface = Interface.from(abi);
  16241. // Dereference Solidity bytecode objects and allow a missing `0x`-prefix
  16242. if (bytecode instanceof Uint8Array) {
  16243. bytecode = hexlify(getBytes(bytecode));
  16244. }
  16245. else {
  16246. if (typeof (bytecode) === "object") {
  16247. bytecode = bytecode.object;
  16248. }
  16249. if (!bytecode.startsWith("0x")) {
  16250. bytecode = "0x" + bytecode;
  16251. }
  16252. bytecode = hexlify(getBytes(bytecode));
  16253. }
  16254. defineProperties(this, {
  16255. bytecode, interface: iface, runner: (runner || null)
  16256. });
  16257. }
  16258. attach(target) {
  16259. return new BaseContract(target, this.interface, this.runner);
  16260. }
  16261. /**
  16262. * Resolves to the transaction to deploy the contract, passing %%args%%
  16263. * into the constructor.
  16264. */
  16265. async getDeployTransaction(...args) {
  16266. let overrides = {};
  16267. const fragment = this.interface.deploy;
  16268. if (fragment.inputs.length + 1 === args.length) {
  16269. overrides = await copyOverrides(args.pop());
  16270. }
  16271. if (fragment.inputs.length !== args.length) {
  16272. throw new Error("incorrect number of arguments to constructor");
  16273. }
  16274. const resolvedArgs = await resolveArgs(this.runner, fragment.inputs, args);
  16275. const data = concat([this.bytecode, this.interface.encodeDeploy(resolvedArgs)]);
  16276. return Object.assign({}, overrides, { data });
  16277. }
  16278. /**
  16279. * Resolves to the Contract deployed by passing %%args%% into the
  16280. * constructor.
  16281. *
  16282. * This will resolve to the Contract before it has been deployed to the
  16283. * network, so the [[BaseContract-waitForDeployment]] should be used before
  16284. * sending any transactions to it.
  16285. */
  16286. async deploy(...args) {
  16287. const tx = await this.getDeployTransaction(...args);
  16288. assert(this.runner && typeof (this.runner.sendTransaction) === "function", "factory runner does not support sending transactions", "UNSUPPORTED_OPERATION", {
  16289. operation: "sendTransaction"
  16290. });
  16291. const sentTx = await this.runner.sendTransaction(tx);
  16292. const address = getCreateAddress(sentTx);
  16293. return new BaseContract(address, this.interface, this.runner, sentTx);
  16294. }
  16295. /**
  16296. * Return a new **ContractFactory** with the same ABI and bytecode,
  16297. * but connected to %%runner%%.
  16298. */
  16299. connect(runner) {
  16300. return new ContractFactory(this.interface, this.bytecode, runner);
  16301. }
  16302. /**
  16303. * Create a new **ContractFactory** from the standard Solidity JSON output.
  16304. */
  16305. static fromSolidity(output, runner) {
  16306. assertArgument(output != null, "bad compiler output", "output", output);
  16307. if (typeof (output) === "string") {
  16308. output = JSON.parse(output);
  16309. }
  16310. const abi = output.abi;
  16311. let bytecode = "";
  16312. if (output.bytecode) {
  16313. bytecode = output.bytecode;
  16314. }
  16315. else if (output.evm && output.evm.bytecode) {
  16316. bytecode = output.evm.bytecode;
  16317. }
  16318. return new this(abi, bytecode, runner);
  16319. }
  16320. }
  16321. /**
  16322. * ENS is a service which allows easy-to-remember names to map to
  16323. * network addresses.
  16324. *
  16325. * @_section: api/providers/ens-resolver:ENS Resolver [about-ens-rsolver]
  16326. */
  16327. // @TODO: This should use the fetch-data:ipfs gateway
  16328. // Trim off the ipfs:// prefix and return the default gateway URL
  16329. function getIpfsLink(link) {
  16330. if (link.match(/^ipfs:\/\/ipfs\//i)) {
  16331. link = link.substring(12);
  16332. }
  16333. else if (link.match(/^ipfs:\/\//i)) {
  16334. link = link.substring(7);
  16335. }
  16336. else {
  16337. assertArgument(false, "unsupported IPFS format", "link", link);
  16338. }
  16339. return `https:/\/gateway.ipfs.io/ipfs/${link}`;
  16340. }
  16341. /**
  16342. * A provider plugin super-class for processing multicoin address types.
  16343. */
  16344. class MulticoinProviderPlugin {
  16345. /**
  16346. * The name.
  16347. */
  16348. name;
  16349. /**
  16350. * Creates a new **MulticoinProviderPluing** for %%name%%.
  16351. */
  16352. constructor(name) {
  16353. defineProperties(this, { name });
  16354. }
  16355. connect(proivder) {
  16356. return this;
  16357. }
  16358. /**
  16359. * Returns ``true`` if %%coinType%% is supported by this plugin.
  16360. */
  16361. supportsCoinType(coinType) {
  16362. return false;
  16363. }
  16364. /**
  16365. * Resolves to the encoded %%address%% for %%coinType%%.
  16366. */
  16367. async encodeAddress(coinType, address) {
  16368. throw new Error("unsupported coin");
  16369. }
  16370. /**
  16371. * Resolves to the decoded %%data%% for %%coinType%%.
  16372. */
  16373. async decodeAddress(coinType, data) {
  16374. throw new Error("unsupported coin");
  16375. }
  16376. }
  16377. const matcherIpfs = new RegExp("^(ipfs):/\/(.*)$", "i");
  16378. const matchers = [
  16379. new RegExp("^(https):/\/(.*)$", "i"),
  16380. new RegExp("^(data):(.*)$", "i"),
  16381. matcherIpfs,
  16382. new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$", "i"),
  16383. ];
  16384. /**
  16385. * A connected object to a resolved ENS name resolver, which can be
  16386. * used to query additional details.
  16387. */
  16388. class EnsResolver {
  16389. /**
  16390. * The connected provider.
  16391. */
  16392. provider;
  16393. /**
  16394. * The address of the resolver.
  16395. */
  16396. address;
  16397. /**
  16398. * The name this resolver was resolved against.
  16399. */
  16400. name;
  16401. // For EIP-2544 names, the ancestor that provided the resolver
  16402. #supports2544;
  16403. #resolver;
  16404. constructor(provider, address, name) {
  16405. defineProperties(this, { provider, address, name });
  16406. this.#supports2544 = null;
  16407. this.#resolver = new Contract(address, [
  16408. "function supportsInterface(bytes4) view returns (bool)",
  16409. "function resolve(bytes, bytes) view returns (bytes)",
  16410. "function addr(bytes32) view returns (address)",
  16411. "function addr(bytes32, uint) view returns (bytes)",
  16412. "function text(bytes32, string) view returns (string)",
  16413. "function contenthash(bytes32) view returns (bytes)",
  16414. ], provider);
  16415. }
  16416. /**
  16417. * Resolves to true if the resolver supports wildcard resolution.
  16418. */
  16419. async supportsWildcard() {
  16420. if (this.#supports2544 == null) {
  16421. this.#supports2544 = (async () => {
  16422. try {
  16423. return await this.#resolver.supportsInterface("0x9061b923");
  16424. }
  16425. catch (error) {
  16426. // Wildcard resolvers must understand supportsInterface
  16427. // and return true.
  16428. if (isError(error, "CALL_EXCEPTION")) {
  16429. return false;
  16430. }
  16431. // Let future attempts try again...
  16432. this.#supports2544 = null;
  16433. throw error;
  16434. }
  16435. })();
  16436. }
  16437. return await this.#supports2544;
  16438. }
  16439. async #fetch(funcName, params) {
  16440. params = (params || []).slice();
  16441. const iface = this.#resolver.interface;
  16442. // The first parameters is always the nodehash
  16443. params.unshift(namehash(this.name));
  16444. let fragment = null;
  16445. if (await this.supportsWildcard()) {
  16446. fragment = iface.getFunction(funcName);
  16447. assert(fragment, "missing fragment", "UNKNOWN_ERROR", {
  16448. info: { funcName }
  16449. });
  16450. params = [
  16451. dnsEncode(this.name, 255),
  16452. iface.encodeFunctionData(fragment, params)
  16453. ];
  16454. funcName = "resolve(bytes,bytes)";
  16455. }
  16456. params.push({
  16457. enableCcipRead: true
  16458. });
  16459. try {
  16460. const result = await this.#resolver[funcName](...params);
  16461. if (fragment) {
  16462. return iface.decodeFunctionResult(fragment, result)[0];
  16463. }
  16464. return result;
  16465. }
  16466. catch (error) {
  16467. if (!isError(error, "CALL_EXCEPTION")) {
  16468. throw error;
  16469. }
  16470. }
  16471. return null;
  16472. }
  16473. /**
  16474. * Resolves to the address for %%coinType%% or null if the
  16475. * provided %%coinType%% has not been configured.
  16476. */
  16477. async getAddress(coinType) {
  16478. if (coinType == null) {
  16479. coinType = 60;
  16480. }
  16481. if (coinType === 60) {
  16482. try {
  16483. const result = await this.#fetch("addr(bytes32)");
  16484. // No address
  16485. if (result == null || result === ZeroAddress) {
  16486. return null;
  16487. }
  16488. return result;
  16489. }
  16490. catch (error) {
  16491. if (isError(error, "CALL_EXCEPTION")) {
  16492. return null;
  16493. }
  16494. throw error;
  16495. }
  16496. }
  16497. // Try decoding its EVM canonical chain as an EVM chain address first
  16498. if (coinType >= 0 && coinType < 0x80000000) {
  16499. let ethCoinType = coinType + 0x80000000;
  16500. const data = await this.#fetch("addr(bytes32,uint)", [ethCoinType]);
  16501. if (isHexString(data, 20)) {
  16502. return getAddress(data);
  16503. }
  16504. }
  16505. let coinPlugin = null;
  16506. for (const plugin of this.provider.plugins) {
  16507. if (!(plugin instanceof MulticoinProviderPlugin)) {
  16508. continue;
  16509. }
  16510. if (plugin.supportsCoinType(coinType)) {
  16511. coinPlugin = plugin;
  16512. break;
  16513. }
  16514. }
  16515. if (coinPlugin == null) {
  16516. return null;
  16517. }
  16518. // keccak256("addr(bytes32,uint256")
  16519. const data = await this.#fetch("addr(bytes32,uint)", [coinType]);
  16520. // No address
  16521. if (data == null || data === "0x") {
  16522. return null;
  16523. }
  16524. // Compute the address
  16525. const address = await coinPlugin.decodeAddress(coinType, data);
  16526. if (address != null) {
  16527. return address;
  16528. }
  16529. assert(false, `invalid coin data`, "UNSUPPORTED_OPERATION", {
  16530. operation: `getAddress(${coinType})`,
  16531. info: { coinType, data }
  16532. });
  16533. }
  16534. /**
  16535. * Resolves to the EIP-634 text record for %%key%%, or ``null``
  16536. * if unconfigured.
  16537. */
  16538. async getText(key) {
  16539. const data = await this.#fetch("text(bytes32,string)", [key]);
  16540. if (data == null || data === "0x") {
  16541. return null;
  16542. }
  16543. return data;
  16544. }
  16545. /**
  16546. * Rsolves to the content-hash or ``null`` if unconfigured.
  16547. */
  16548. async getContentHash() {
  16549. // keccak256("contenthash()")
  16550. const data = await this.#fetch("contenthash(bytes32)");
  16551. // No contenthash
  16552. if (data == null || data === "0x") {
  16553. return null;
  16554. }
  16555. // IPFS (CID: 1, Type: 70=DAG-PB, 72=libp2p-key)
  16556. const ipfs = data.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);
  16557. if (ipfs) {
  16558. const scheme = (ipfs[1] === "e3010170") ? "ipfs" : "ipns";
  16559. const length = parseInt(ipfs[4], 16);
  16560. if (ipfs[5].length === length * 2) {
  16561. return `${scheme}:/\/${encodeBase58("0x" + ipfs[2])}`;
  16562. }
  16563. }
  16564. // Swarm (CID: 1, Type: swarm-manifest; hash/length hard-coded to keccak256/32)
  16565. const swarm = data.match(/^0xe40101fa011b20([0-9a-f]*)$/);
  16566. if (swarm && swarm[1].length === 64) {
  16567. return `bzz:/\/${swarm[1]}`;
  16568. }
  16569. assert(false, `invalid or unsupported content hash data`, "UNSUPPORTED_OPERATION", {
  16570. operation: "getContentHash()",
  16571. info: { data }
  16572. });
  16573. }
  16574. /**
  16575. * Resolves to the avatar url or ``null`` if the avatar is either
  16576. * unconfigured or incorrectly configured (e.g. references an NFT
  16577. * not owned by the address).
  16578. *
  16579. * If diagnosing issues with configurations, the [[_getAvatar]]
  16580. * method may be useful.
  16581. */
  16582. async getAvatar() {
  16583. const avatar = await this._getAvatar();
  16584. return avatar.url;
  16585. }
  16586. /**
  16587. * When resolving an avatar, there are many steps involved, such
  16588. * fetching metadata and possibly validating ownership of an
  16589. * NFT.
  16590. *
  16591. * This method can be used to examine each step and the value it
  16592. * was working from.
  16593. */
  16594. async _getAvatar() {
  16595. const linkage = [{ type: "name", value: this.name }];
  16596. try {
  16597. // test data for ricmoo.eth
  16598. //const avatar = "eip155:1/erc721:0x265385c7f4132228A0d54EB1A9e7460b91c0cC68/29233";
  16599. const avatar = await this.getText("avatar");
  16600. if (avatar == null) {
  16601. linkage.push({ type: "!avatar", value: "" });
  16602. return { url: null, linkage };
  16603. }
  16604. linkage.push({ type: "avatar", value: avatar });
  16605. for (let i = 0; i < matchers.length; i++) {
  16606. const match = avatar.match(matchers[i]);
  16607. if (match == null) {
  16608. continue;
  16609. }
  16610. const scheme = match[1].toLowerCase();
  16611. switch (scheme) {
  16612. case "https":
  16613. case "data":
  16614. linkage.push({ type: "url", value: avatar });
  16615. return { linkage, url: avatar };
  16616. case "ipfs": {
  16617. const url = getIpfsLink(avatar);
  16618. linkage.push({ type: "ipfs", value: avatar });
  16619. linkage.push({ type: "url", value: url });
  16620. return { linkage, url };
  16621. }
  16622. case "erc721":
  16623. case "erc1155": {
  16624. // Depending on the ERC type, use tokenURI(uint256) or url(uint256)
  16625. const selector = (scheme === "erc721") ? "tokenURI(uint256)" : "uri(uint256)";
  16626. linkage.push({ type: scheme, value: avatar });
  16627. // The owner of this name
  16628. const owner = await this.getAddress();
  16629. if (owner == null) {
  16630. linkage.push({ type: "!owner", value: "" });
  16631. return { url: null, linkage };
  16632. }
  16633. const comps = (match[2] || "").split("/");
  16634. if (comps.length !== 2) {
  16635. linkage.push({ type: `!${scheme}caip`, value: (match[2] || "") });
  16636. return { url: null, linkage };
  16637. }
  16638. const tokenId = comps[1];
  16639. const contract = new Contract(comps[0], [
  16640. // ERC-721
  16641. "function tokenURI(uint) view returns (string)",
  16642. "function ownerOf(uint) view returns (address)",
  16643. // ERC-1155
  16644. "function uri(uint) view returns (string)",
  16645. "function balanceOf(address, uint256) view returns (uint)"
  16646. ], this.provider);
  16647. // Check that this account owns the token
  16648. if (scheme === "erc721") {
  16649. const tokenOwner = await contract.ownerOf(tokenId);
  16650. if (owner !== tokenOwner) {
  16651. linkage.push({ type: "!owner", value: tokenOwner });
  16652. return { url: null, linkage };
  16653. }
  16654. linkage.push({ type: "owner", value: tokenOwner });
  16655. }
  16656. else if (scheme === "erc1155") {
  16657. const balance = await contract.balanceOf(owner, tokenId);
  16658. if (!balance) {
  16659. linkage.push({ type: "!balance", value: "0" });
  16660. return { url: null, linkage };
  16661. }
  16662. linkage.push({ type: "balance", value: balance.toString() });
  16663. }
  16664. // Call the token contract for the metadata URL
  16665. let metadataUrl = await contract[selector](tokenId);
  16666. if (metadataUrl == null || metadataUrl === "0x") {
  16667. linkage.push({ type: "!metadata-url", value: "" });
  16668. return { url: null, linkage };
  16669. }
  16670. linkage.push({ type: "metadata-url-base", value: metadataUrl });
  16671. // ERC-1155 allows a generic {id} in the URL
  16672. if (scheme === "erc1155") {
  16673. metadataUrl = metadataUrl.replace("{id}", toBeHex(tokenId, 32).substring(2));
  16674. linkage.push({ type: "metadata-url-expanded", value: metadataUrl });
  16675. }
  16676. // Transform IPFS metadata links
  16677. if (metadataUrl.match(/^ipfs:/i)) {
  16678. metadataUrl = getIpfsLink(metadataUrl);
  16679. }
  16680. linkage.push({ type: "metadata-url", value: metadataUrl });
  16681. // Get the token metadata
  16682. let metadata = {};
  16683. const response = await (new FetchRequest(metadataUrl)).send();
  16684. response.assertOk();
  16685. try {
  16686. metadata = response.bodyJson;
  16687. }
  16688. catch (error) {
  16689. try {
  16690. linkage.push({ type: "!metadata", value: response.bodyText });
  16691. }
  16692. catch (error) {
  16693. const bytes = response.body;
  16694. if (bytes) {
  16695. linkage.push({ type: "!metadata", value: hexlify(bytes) });
  16696. }
  16697. return { url: null, linkage };
  16698. }
  16699. return { url: null, linkage };
  16700. }
  16701. if (!metadata) {
  16702. linkage.push({ type: "!metadata", value: "" });
  16703. return { url: null, linkage };
  16704. }
  16705. linkage.push({ type: "metadata", value: JSON.stringify(metadata) });
  16706. // Pull the image URL out
  16707. let imageUrl = metadata.image;
  16708. if (typeof (imageUrl) !== "string") {
  16709. linkage.push({ type: "!imageUrl", value: "" });
  16710. return { url: null, linkage };
  16711. }
  16712. if (imageUrl.match(/^(https:\/\/|data:)/i)) {
  16713. // Allow
  16714. }
  16715. else {
  16716. // Transform IPFS link to gateway
  16717. const ipfs = imageUrl.match(matcherIpfs);
  16718. if (ipfs == null) {
  16719. linkage.push({ type: "!imageUrl-ipfs", value: imageUrl });
  16720. return { url: null, linkage };
  16721. }
  16722. linkage.push({ type: "imageUrl-ipfs", value: imageUrl });
  16723. imageUrl = getIpfsLink(imageUrl);
  16724. }
  16725. linkage.push({ type: "url", value: imageUrl });
  16726. return { linkage, url: imageUrl };
  16727. }
  16728. }
  16729. }
  16730. }
  16731. catch (error) { }
  16732. return { linkage, url: null };
  16733. }
  16734. static async getEnsAddress(provider) {
  16735. const network = await provider.getNetwork();
  16736. const ensPlugin = network.getPlugin("org.ethers.plugins.network.Ens");
  16737. // No ENS...
  16738. assert(ensPlugin, "network does not support ENS", "UNSUPPORTED_OPERATION", {
  16739. operation: "getEnsAddress", info: { network }
  16740. });
  16741. return ensPlugin.address;
  16742. }
  16743. static async #getResolver(provider, name) {
  16744. const ensAddr = await EnsResolver.getEnsAddress(provider);
  16745. try {
  16746. const contract = new Contract(ensAddr, [
  16747. "function resolver(bytes32) view returns (address)"
  16748. ], provider);
  16749. const addr = await contract.resolver(namehash(name), {
  16750. enableCcipRead: true
  16751. });
  16752. if (addr === ZeroAddress) {
  16753. return null;
  16754. }
  16755. return addr;
  16756. }
  16757. catch (error) {
  16758. // ENS registry cannot throw errors on resolver(bytes32),
  16759. // so probably a link error
  16760. throw error;
  16761. }
  16762. return null;
  16763. }
  16764. /**
  16765. * Resolve to the ENS resolver for %%name%% using %%provider%% or
  16766. * ``null`` if unconfigured.
  16767. */
  16768. static async fromName(provider, name) {
  16769. let currentName = name;
  16770. while (true) {
  16771. if (currentName === "" || currentName === ".") {
  16772. return null;
  16773. }
  16774. // Optimization since the eth node cannot change and does
  16775. // not have a wildcard resolver
  16776. if (name !== "eth" && currentName === "eth") {
  16777. return null;
  16778. }
  16779. // Check the current node for a resolver
  16780. const addr = await EnsResolver.#getResolver(provider, currentName);
  16781. // Found a resolver!
  16782. if (addr != null) {
  16783. const resolver = new EnsResolver(provider, addr, name);
  16784. // Legacy resolver found, using EIP-2544 so it isn't safe to use
  16785. if (currentName !== name && !(await resolver.supportsWildcard())) {
  16786. return null;
  16787. }
  16788. return resolver;
  16789. }
  16790. // Get the parent node
  16791. currentName = currentName.split(".").slice(1).join(".");
  16792. }
  16793. }
  16794. }
  16795. /**
  16796. * @_ignore
  16797. */
  16798. const BN_0 = BigInt(0);
  16799. function allowNull(format, nullValue) {
  16800. return (function (value) {
  16801. if (value == null) {
  16802. return nullValue;
  16803. }
  16804. return format(value);
  16805. });
  16806. }
  16807. function arrayOf(format, allowNull) {
  16808. return ((array) => {
  16809. if (allowNull && array == null) {
  16810. return null;
  16811. }
  16812. if (!Array.isArray(array)) {
  16813. throw new Error("not an array");
  16814. }
  16815. return array.map((i) => format(i));
  16816. });
  16817. }
  16818. // Requires an object which matches a fleet of other formatters
  16819. // Any FormatFunc may return `undefined` to have the value omitted
  16820. // from the result object. Calls preserve `this`.
  16821. function object(format, altNames) {
  16822. return ((value) => {
  16823. const result = {};
  16824. for (const key in format) {
  16825. let srcKey = key;
  16826. if (altNames && key in altNames && !(srcKey in value)) {
  16827. for (const altKey of altNames[key]) {
  16828. if (altKey in value) {
  16829. srcKey = altKey;
  16830. break;
  16831. }
  16832. }
  16833. }
  16834. try {
  16835. const nv = format[key](value[srcKey]);
  16836. if (nv !== undefined) {
  16837. result[key] = nv;
  16838. }
  16839. }
  16840. catch (error) {
  16841. const message = (error instanceof Error) ? error.message : "not-an-error";
  16842. assert(false, `invalid value for value.${key} (${message})`, "BAD_DATA", { value });
  16843. }
  16844. }
  16845. return result;
  16846. });
  16847. }
  16848. function formatBoolean(value) {
  16849. switch (value) {
  16850. case true:
  16851. case "true":
  16852. return true;
  16853. case false:
  16854. case "false":
  16855. return false;
  16856. }
  16857. assertArgument(false, `invalid boolean; ${JSON.stringify(value)}`, "value", value);
  16858. }
  16859. function formatData(value) {
  16860. assertArgument(isHexString(value, true), "invalid data", "value", value);
  16861. return value;
  16862. }
  16863. function formatHash(value) {
  16864. assertArgument(isHexString(value, 32), "invalid hash", "value", value);
  16865. return value;
  16866. }
  16867. const _formatLog = object({
  16868. address: getAddress,
  16869. blockHash: formatHash,
  16870. blockNumber: getNumber,
  16871. data: formatData,
  16872. index: getNumber,
  16873. removed: allowNull(formatBoolean, false),
  16874. topics: arrayOf(formatHash),
  16875. transactionHash: formatHash,
  16876. transactionIndex: getNumber,
  16877. }, {
  16878. index: ["logIndex"]
  16879. });
  16880. function formatLog(value) {
  16881. return _formatLog(value);
  16882. }
  16883. const _formatBlock = object({
  16884. hash: allowNull(formatHash),
  16885. parentHash: formatHash,
  16886. parentBeaconBlockRoot: allowNull(formatHash, null),
  16887. number: getNumber,
  16888. timestamp: getNumber,
  16889. nonce: allowNull(formatData),
  16890. difficulty: getBigInt,
  16891. gasLimit: getBigInt,
  16892. gasUsed: getBigInt,
  16893. stateRoot: allowNull(formatHash, null),
  16894. receiptsRoot: allowNull(formatHash, null),
  16895. blobGasUsed: allowNull(getBigInt, null),
  16896. excessBlobGas: allowNull(getBigInt, null),
  16897. miner: allowNull(getAddress),
  16898. prevRandao: allowNull(formatHash, null),
  16899. extraData: formatData,
  16900. baseFeePerGas: allowNull(getBigInt)
  16901. }, {
  16902. prevRandao: ["mixHash"]
  16903. });
  16904. function formatBlock(value) {
  16905. const result = _formatBlock(value);
  16906. result.transactions = value.transactions.map((tx) => {
  16907. if (typeof (tx) === "string") {
  16908. return tx;
  16909. }
  16910. return formatTransactionResponse(tx);
  16911. });
  16912. return result;
  16913. }
  16914. const _formatReceiptLog = object({
  16915. transactionIndex: getNumber,
  16916. blockNumber: getNumber,
  16917. transactionHash: formatHash,
  16918. address: getAddress,
  16919. topics: arrayOf(formatHash),
  16920. data: formatData,
  16921. index: getNumber,
  16922. blockHash: formatHash,
  16923. }, {
  16924. index: ["logIndex"]
  16925. });
  16926. function formatReceiptLog(value) {
  16927. return _formatReceiptLog(value);
  16928. }
  16929. const _formatTransactionReceipt = object({
  16930. to: allowNull(getAddress, null),
  16931. from: allowNull(getAddress, null),
  16932. contractAddress: allowNull(getAddress, null),
  16933. // should be allowNull(hash), but broken-EIP-658 support is handled in receipt
  16934. index: getNumber,
  16935. root: allowNull(hexlify),
  16936. gasUsed: getBigInt,
  16937. blobGasUsed: allowNull(getBigInt, null),
  16938. logsBloom: allowNull(formatData),
  16939. blockHash: formatHash,
  16940. hash: formatHash,
  16941. logs: arrayOf(formatReceiptLog),
  16942. blockNumber: getNumber,
  16943. //confirmations: allowNull(getNumber, null),
  16944. cumulativeGasUsed: getBigInt,
  16945. effectiveGasPrice: allowNull(getBigInt),
  16946. blobGasPrice: allowNull(getBigInt, null),
  16947. status: allowNull(getNumber),
  16948. type: allowNull(getNumber, 0)
  16949. }, {
  16950. effectiveGasPrice: ["gasPrice"],
  16951. hash: ["transactionHash"],
  16952. index: ["transactionIndex"],
  16953. });
  16954. function formatTransactionReceipt(value) {
  16955. return _formatTransactionReceipt(value);
  16956. }
  16957. function formatTransactionResponse(value) {
  16958. // Some clients (TestRPC) do strange things like return 0x0 for the
  16959. // 0 address; correct this to be a real address
  16960. if (value.to && getBigInt(value.to) === BN_0) {
  16961. value.to = "0x0000000000000000000000000000000000000000";
  16962. }
  16963. const result = object({
  16964. hash: formatHash,
  16965. // Some nodes do not return this, usually test nodes (like Ganache)
  16966. index: allowNull(getNumber, undefined),
  16967. type: (value) => {
  16968. if (value === "0x" || value == null) {
  16969. return 0;
  16970. }
  16971. return getNumber(value);
  16972. },
  16973. accessList: allowNull(accessListify, null),
  16974. blobVersionedHashes: allowNull(arrayOf(formatHash, true), null),
  16975. blockHash: allowNull(formatHash, null),
  16976. blockNumber: allowNull(getNumber, null),
  16977. transactionIndex: allowNull(getNumber, null),
  16978. from: getAddress,
  16979. // either (gasPrice) or (maxPriorityFeePerGas + maxFeePerGas) must be set
  16980. gasPrice: allowNull(getBigInt),
  16981. maxPriorityFeePerGas: allowNull(getBigInt),
  16982. maxFeePerGas: allowNull(getBigInt),
  16983. maxFeePerBlobGas: allowNull(getBigInt, null),
  16984. gasLimit: getBigInt,
  16985. to: allowNull(getAddress, null),
  16986. value: getBigInt,
  16987. nonce: getNumber,
  16988. data: formatData,
  16989. creates: allowNull(getAddress, null),
  16990. chainId: allowNull(getBigInt, null)
  16991. }, {
  16992. data: ["input"],
  16993. gasLimit: ["gas"],
  16994. index: ["transactionIndex"]
  16995. })(value);
  16996. // If to and creates are empty, populate the creates from the value
  16997. if (result.to == null && result.creates == null) {
  16998. result.creates = getCreateAddress(result);
  16999. }
  17000. // @TODO: Check fee data
  17001. // Add an access list to supported transaction types
  17002. if ((value.type === 1 || value.type === 2) && value.accessList == null) {
  17003. result.accessList = [];
  17004. }
  17005. // Compute the signature
  17006. if (value.signature) {
  17007. result.signature = Signature.from(value.signature);
  17008. }
  17009. else {
  17010. result.signature = Signature.from(value);
  17011. }
  17012. // Some backends omit ChainId on legacy transactions, but we can compute it
  17013. if (result.chainId == null) {
  17014. const chainId = result.signature.legacyChainId;
  17015. if (chainId != null) {
  17016. result.chainId = chainId;
  17017. }
  17018. }
  17019. // @TODO: check chainID
  17020. /*
  17021. if (value.chainId != null) {
  17022. let chainId = value.chainId;
  17023. if (isHexString(chainId)) {
  17024. chainId = BigNumber.from(chainId).toNumber();
  17025. }
  17026. result.chainId = chainId;
  17027. } else {
  17028. let chainId = value.networkId;
  17029. // geth-etc returns chainId
  17030. if (chainId == null && result.v == null) {
  17031. chainId = value.chainId;
  17032. }
  17033. if (isHexString(chainId)) {
  17034. chainId = BigNumber.from(chainId).toNumber();
  17035. }
  17036. if (typeof(chainId) !== "number" && result.v != null) {
  17037. chainId = (result.v - 35) / 2;
  17038. if (chainId < 0) { chainId = 0; }
  17039. chainId = parseInt(chainId);
  17040. }
  17041. if (typeof(chainId) !== "number") { chainId = 0; }
  17042. result.chainId = chainId;
  17043. }
  17044. */
  17045. // 0x0000... should actually be null
  17046. if (result.blockHash && getBigInt(result.blockHash) === BN_0) {
  17047. result.blockHash = null;
  17048. }
  17049. return result;
  17050. }
  17051. const EnsAddress = "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e";
  17052. /**
  17053. * A **NetworkPlugin** provides additional functionality on a [[Network]].
  17054. */
  17055. class NetworkPlugin {
  17056. /**
  17057. * The name of the plugin.
  17058. *
  17059. * It is recommended to use reverse-domain-notation, which permits
  17060. * unique names with a known authority as well as hierarchal entries.
  17061. */
  17062. name;
  17063. /**
  17064. * Creates a new **NetworkPlugin**.
  17065. */
  17066. constructor(name) {
  17067. defineProperties(this, { name });
  17068. }
  17069. /**
  17070. * Creates a copy of this plugin.
  17071. */
  17072. clone() {
  17073. return new NetworkPlugin(this.name);
  17074. }
  17075. }
  17076. /**
  17077. * A **GasCostPlugin** allows a network to provide alternative values when
  17078. * computing the intrinsic gas required for a transaction.
  17079. */
  17080. class GasCostPlugin extends NetworkPlugin {
  17081. /**
  17082. * The block number to treat these values as valid from.
  17083. *
  17084. * This allows a hardfork to have updated values included as well as
  17085. * mulutiple hardforks to be supported.
  17086. */
  17087. effectiveBlock;
  17088. /**
  17089. * The transactions base fee.
  17090. */
  17091. txBase;
  17092. /**
  17093. * The fee for creating a new account.
  17094. */
  17095. txCreate;
  17096. /**
  17097. * The fee per zero-byte in the data.
  17098. */
  17099. txDataZero;
  17100. /**
  17101. * The fee per non-zero-byte in the data.
  17102. */
  17103. txDataNonzero;
  17104. /**
  17105. * The fee per storage key in the [[link-eip-2930]] access list.
  17106. */
  17107. txAccessListStorageKey;
  17108. /**
  17109. * The fee per address in the [[link-eip-2930]] access list.
  17110. */
  17111. txAccessListAddress;
  17112. /**
  17113. * Creates a new GasCostPlugin from %%effectiveBlock%% until the
  17114. * latest block or another GasCostPlugin supercedes that block number,
  17115. * with the associated %%costs%%.
  17116. */
  17117. constructor(effectiveBlock, costs) {
  17118. if (effectiveBlock == null) {
  17119. effectiveBlock = 0;
  17120. }
  17121. super(`org.ethers.network.plugins.GasCost#${(effectiveBlock || 0)}`);
  17122. const props = { effectiveBlock };
  17123. function set(name, nullish) {
  17124. let value = (costs || {})[name];
  17125. if (value == null) {
  17126. value = nullish;
  17127. }
  17128. assertArgument(typeof (value) === "number", `invalud value for ${name}`, "costs", costs);
  17129. props[name] = value;
  17130. }
  17131. set("txBase", 21000);
  17132. set("txCreate", 32000);
  17133. set("txDataZero", 4);
  17134. set("txDataNonzero", 16);
  17135. set("txAccessListStorageKey", 1900);
  17136. set("txAccessListAddress", 2400);
  17137. defineProperties(this, props);
  17138. }
  17139. clone() {
  17140. return new GasCostPlugin(this.effectiveBlock, this);
  17141. }
  17142. }
  17143. /**
  17144. * An **EnsPlugin** allows a [[Network]] to specify the ENS Registry
  17145. * Contract address and the target network to use when using that
  17146. * contract.
  17147. *
  17148. * Various testnets have their own instance of the contract to use, but
  17149. * in general, the mainnet instance supports multi-chain addresses and
  17150. * should be used.
  17151. */
  17152. class EnsPlugin extends NetworkPlugin {
  17153. /**
  17154. * The ENS Registrty Contract address.
  17155. */
  17156. address;
  17157. /**
  17158. * The chain ID that the ENS contract lives on.
  17159. */
  17160. targetNetwork;
  17161. /**
  17162. * Creates a new **EnsPlugin** connected to %%address%% on the
  17163. * %%targetNetwork%%. The default ENS address and mainnet is used
  17164. * if unspecified.
  17165. */
  17166. constructor(address, targetNetwork) {
  17167. super("org.ethers.plugins.network.Ens");
  17168. defineProperties(this, {
  17169. address: (address || EnsAddress),
  17170. targetNetwork: ((targetNetwork == null) ? 1 : targetNetwork)
  17171. });
  17172. }
  17173. clone() {
  17174. return new EnsPlugin(this.address, this.targetNetwork);
  17175. }
  17176. }
  17177. /**
  17178. * A **FeeDataNetworkPlugin** allows a network to provide and alternate
  17179. * means to specify its fee data.
  17180. *
  17181. * For example, a network which does not support [[link-eip-1559]] may
  17182. * choose to use a Gas Station site to approximate the gas price.
  17183. */
  17184. class FeeDataNetworkPlugin extends NetworkPlugin {
  17185. #feeDataFunc;
  17186. /**
  17187. * The fee data function provided to the constructor.
  17188. */
  17189. get feeDataFunc() {
  17190. return this.#feeDataFunc;
  17191. }
  17192. /**
  17193. * Creates a new **FeeDataNetworkPlugin**.
  17194. */
  17195. constructor(feeDataFunc) {
  17196. super("org.ethers.plugins.network.FeeData");
  17197. this.#feeDataFunc = feeDataFunc;
  17198. }
  17199. /**
  17200. * Resolves to the fee data.
  17201. */
  17202. async getFeeData(provider) {
  17203. return await this.#feeDataFunc(provider);
  17204. }
  17205. clone() {
  17206. return new FeeDataNetworkPlugin(this.#feeDataFunc);
  17207. }
  17208. }
  17209. class FetchUrlFeeDataNetworkPlugin extends NetworkPlugin {
  17210. #url;
  17211. #processFunc;
  17212. /**
  17213. * The URL to initialize the FetchRequest with in %%processFunc%%.
  17214. */
  17215. get url() { return this.#url; }
  17216. /**
  17217. * The callback to use when computing the FeeData.
  17218. */
  17219. get processFunc() { return this.#processFunc; }
  17220. /**
  17221. * Creates a new **FetchUrlFeeDataNetworkPlugin** which will
  17222. * be used when computing the fee data for the network.
  17223. */
  17224. constructor(url, processFunc) {
  17225. super("org.ethers.plugins.network.FetchUrlFeeDataPlugin");
  17226. this.#url = url;
  17227. this.#processFunc = processFunc;
  17228. }
  17229. // We are immutable, so we can serve as our own clone
  17230. clone() { return this; }
  17231. }
  17232. /*
  17233. export class CustomBlockNetworkPlugin extends NetworkPlugin {
  17234. readonly #blockFunc: (provider: Provider, block: BlockParams<string>) => Block<string>;
  17235. readonly #blockWithTxsFunc: (provider: Provider, block: BlockParams<TransactionResponseParams>) => Block<TransactionResponse>;
  17236. constructor(blockFunc: (provider: Provider, block: BlockParams<string>) => Block<string>, blockWithTxsFunc: (provider: Provider, block: BlockParams<TransactionResponseParams>) => Block<TransactionResponse>) {
  17237. super("org.ethers.network-plugins.custom-block");
  17238. this.#blockFunc = blockFunc;
  17239. this.#blockWithTxsFunc = blockWithTxsFunc;
  17240. }
  17241. async getBlock(provider: Provider, block: BlockParams<string>): Promise<Block<string>> {
  17242. return await this.#blockFunc(provider, block);
  17243. }
  17244. async getBlockions(provider: Provider, block: BlockParams<TransactionResponseParams>): Promise<Block<TransactionResponse>> {
  17245. return await this.#blockWithTxsFunc(provider, block);
  17246. }
  17247. clone(): CustomBlockNetworkPlugin {
  17248. return new CustomBlockNetworkPlugin(this.#blockFunc, this.#blockWithTxsFunc);
  17249. }
  17250. }
  17251. */
  17252. /**
  17253. * A **Network** encapsulates the various properties required to
  17254. * interact with a specific chain.
  17255. *
  17256. * @_subsection: api/providers:Networks [networks]
  17257. */
  17258. /* * * *
  17259. // Networks which operation against an L2 can use this plugin to
  17260. // specify how to access L1, for the purpose of resolving ENS,
  17261. // for example.
  17262. export class LayerOneConnectionPlugin extends NetworkPlugin {
  17263. readonly provider!: Provider;
  17264. // @TODO: Rename to ChainAccess and allow for connecting to any chain
  17265. constructor(provider: Provider) {
  17266. super("org.ethers.plugins.layer-one-connection");
  17267. defineProperties<LayerOneConnectionPlugin>(this, { provider });
  17268. }
  17269. clone(): LayerOneConnectionPlugin {
  17270. return new LayerOneConnectionPlugin(this.provider);
  17271. }
  17272. }
  17273. */
  17274. const Networks = new Map();
  17275. /**
  17276. * A **Network** provides access to a chain's properties and allows
  17277. * for plug-ins to extend functionality.
  17278. */
  17279. class Network {
  17280. #name;
  17281. #chainId;
  17282. #plugins;
  17283. /**
  17284. * Creates a new **Network** for %%name%% and %%chainId%%.
  17285. */
  17286. constructor(name, chainId) {
  17287. this.#name = name;
  17288. this.#chainId = getBigInt(chainId);
  17289. this.#plugins = new Map();
  17290. }
  17291. /**
  17292. * Returns a JSON-compatible representation of a Network.
  17293. */
  17294. toJSON() {
  17295. return { name: this.name, chainId: String(this.chainId) };
  17296. }
  17297. /**
  17298. * The network common name.
  17299. *
  17300. * This is the canonical name, as networks migh have multiple
  17301. * names.
  17302. */
  17303. get name() { return this.#name; }
  17304. set name(value) { this.#name = value; }
  17305. /**
  17306. * The network chain ID.
  17307. */
  17308. get chainId() { return this.#chainId; }
  17309. set chainId(value) { this.#chainId = getBigInt(value, "chainId"); }
  17310. /**
  17311. * Returns true if %%other%% matches this network. Any chain ID
  17312. * must match, and if no chain ID is present, the name must match.
  17313. *
  17314. * This method does not currently check for additional properties,
  17315. * such as ENS address or plug-in compatibility.
  17316. */
  17317. matches(other) {
  17318. if (other == null) {
  17319. return false;
  17320. }
  17321. if (typeof (other) === "string") {
  17322. try {
  17323. return (this.chainId === getBigInt(other));
  17324. }
  17325. catch (error) { }
  17326. return (this.name === other);
  17327. }
  17328. if (typeof (other) === "number" || typeof (other) === "bigint") {
  17329. try {
  17330. return (this.chainId === getBigInt(other));
  17331. }
  17332. catch (error) { }
  17333. return false;
  17334. }
  17335. if (typeof (other) === "object") {
  17336. if (other.chainId != null) {
  17337. try {
  17338. return (this.chainId === getBigInt(other.chainId));
  17339. }
  17340. catch (error) { }
  17341. return false;
  17342. }
  17343. if (other.name != null) {
  17344. return (this.name === other.name);
  17345. }
  17346. return false;
  17347. }
  17348. return false;
  17349. }
  17350. /**
  17351. * Returns the list of plugins currently attached to this Network.
  17352. */
  17353. get plugins() {
  17354. return Array.from(this.#plugins.values());
  17355. }
  17356. /**
  17357. * Attach a new %%plugin%% to this Network. The network name
  17358. * must be unique, excluding any fragment.
  17359. */
  17360. attachPlugin(plugin) {
  17361. if (this.#plugins.get(plugin.name)) {
  17362. throw new Error(`cannot replace existing plugin: ${plugin.name} `);
  17363. }
  17364. this.#plugins.set(plugin.name, plugin.clone());
  17365. return this;
  17366. }
  17367. /**
  17368. * Return the plugin, if any, matching %%name%% exactly. Plugins
  17369. * with fragments will not be returned unless %%name%% includes
  17370. * a fragment.
  17371. */
  17372. getPlugin(name) {
  17373. return (this.#plugins.get(name)) || null;
  17374. }
  17375. /**
  17376. * Gets a list of all plugins that match %%name%%, with otr without
  17377. * a fragment.
  17378. */
  17379. getPlugins(basename) {
  17380. return (this.plugins.filter((p) => (p.name.split("#")[0] === basename)));
  17381. }
  17382. /**
  17383. * Create a copy of this Network.
  17384. */
  17385. clone() {
  17386. const clone = new Network(this.name, this.chainId);
  17387. this.plugins.forEach((plugin) => {
  17388. clone.attachPlugin(plugin.clone());
  17389. });
  17390. return clone;
  17391. }
  17392. /**
  17393. * Compute the intrinsic gas required for a transaction.
  17394. *
  17395. * A GasCostPlugin can be attached to override the default
  17396. * values.
  17397. */
  17398. computeIntrinsicGas(tx) {
  17399. const costs = this.getPlugin("org.ethers.plugins.network.GasCost") || (new GasCostPlugin());
  17400. let gas = costs.txBase;
  17401. if (tx.to == null) {
  17402. gas += costs.txCreate;
  17403. }
  17404. if (tx.data) {
  17405. for (let i = 2; i < tx.data.length; i += 2) {
  17406. if (tx.data.substring(i, i + 2) === "00") {
  17407. gas += costs.txDataZero;
  17408. }
  17409. else {
  17410. gas += costs.txDataNonzero;
  17411. }
  17412. }
  17413. }
  17414. if (tx.accessList) {
  17415. const accessList = accessListify(tx.accessList);
  17416. for (const addr in accessList) {
  17417. gas += costs.txAccessListAddress + costs.txAccessListStorageKey * accessList[addr].storageKeys.length;
  17418. }
  17419. }
  17420. return gas;
  17421. }
  17422. /**
  17423. * Returns a new Network for the %%network%% name or chainId.
  17424. */
  17425. static from(network) {
  17426. injectCommonNetworks();
  17427. // Default network
  17428. if (network == null) {
  17429. return Network.from("mainnet");
  17430. }
  17431. // Canonical name or chain ID
  17432. if (typeof (network) === "number") {
  17433. network = BigInt(network);
  17434. }
  17435. if (typeof (network) === "string" || typeof (network) === "bigint") {
  17436. const networkFunc = Networks.get(network);
  17437. if (networkFunc) {
  17438. return networkFunc();
  17439. }
  17440. if (typeof (network) === "bigint") {
  17441. return new Network("unknown", network);
  17442. }
  17443. assertArgument(false, "unknown network", "network", network);
  17444. }
  17445. // Clonable with network-like abilities
  17446. if (typeof (network.clone) === "function") {
  17447. const clone = network.clone();
  17448. //if (typeof(network.name) !== "string" || typeof(network.chainId) !== "number") {
  17449. //}
  17450. return clone;
  17451. }
  17452. // Networkish
  17453. if (typeof (network) === "object") {
  17454. assertArgument(typeof (network.name) === "string" && typeof (network.chainId) === "number", "invalid network object name or chainId", "network", network);
  17455. const custom = new Network((network.name), (network.chainId));
  17456. if (network.ensAddress || network.ensNetwork != null) {
  17457. custom.attachPlugin(new EnsPlugin(network.ensAddress, network.ensNetwork));
  17458. }
  17459. //if ((<any>network).layerOneConnection) {
  17460. // custom.attachPlugin(new LayerOneConnectionPlugin((<any>network).layerOneConnection));
  17461. //}
  17462. return custom;
  17463. }
  17464. assertArgument(false, "invalid network", "network", network);
  17465. }
  17466. /**
  17467. * Register %%nameOrChainId%% with a function which returns
  17468. * an instance of a Network representing that chain.
  17469. */
  17470. static register(nameOrChainId, networkFunc) {
  17471. if (typeof (nameOrChainId) === "number") {
  17472. nameOrChainId = BigInt(nameOrChainId);
  17473. }
  17474. const existing = Networks.get(nameOrChainId);
  17475. if (existing) {
  17476. assertArgument(false, `conflicting network for ${JSON.stringify(existing.name)}`, "nameOrChainId", nameOrChainId);
  17477. }
  17478. Networks.set(nameOrChainId, networkFunc);
  17479. }
  17480. }
  17481. // We don't want to bring in formatUnits because it is backed by
  17482. // FixedNumber and we want to keep Networks tiny. The values
  17483. // included by the Gas Stations are also IEEE 754 with lots of
  17484. // rounding issues and exceed the strict checks formatUnits has.
  17485. function parseUnits(_value, decimals) {
  17486. const value = String(_value);
  17487. if (!value.match(/^[0-9.]+$/)) {
  17488. throw new Error(`invalid gwei value: ${_value}`);
  17489. }
  17490. // Break into [ whole, fraction ]
  17491. const comps = value.split(".");
  17492. if (comps.length === 1) {
  17493. comps.push("");
  17494. }
  17495. // More than 1 decimal point or too many fractional positions
  17496. if (comps.length !== 2) {
  17497. throw new Error(`invalid gwei value: ${_value}`);
  17498. }
  17499. // Pad the fraction to 9 decimalplaces
  17500. while (comps[1].length < decimals) {
  17501. comps[1] += "0";
  17502. }
  17503. // Too many decimals and some non-zero ending, take the ceiling
  17504. if (comps[1].length > 9) {
  17505. let frac = BigInt(comps[1].substring(0, 9));
  17506. if (!comps[1].substring(9).match(/^0+$/)) {
  17507. frac++;
  17508. }
  17509. comps[1] = frac.toString();
  17510. }
  17511. return BigInt(comps[0] + comps[1]);
  17512. }
  17513. // Used by Polygon to use a gas station for fee data
  17514. function getGasStationPlugin(url) {
  17515. return new FetchUrlFeeDataNetworkPlugin(url, async (fetchFeeData, provider, request) => {
  17516. // Prevent Cloudflare from blocking our request in node.js
  17517. request.setHeader("User-Agent", "ethers");
  17518. let response;
  17519. try {
  17520. const [_response, _feeData] = await Promise.all([
  17521. request.send(), fetchFeeData()
  17522. ]);
  17523. response = _response;
  17524. const payload = response.bodyJson.standard;
  17525. const feeData = {
  17526. gasPrice: _feeData.gasPrice,
  17527. maxFeePerGas: parseUnits(payload.maxFee, 9),
  17528. maxPriorityFeePerGas: parseUnits(payload.maxPriorityFee, 9),
  17529. };
  17530. return feeData;
  17531. }
  17532. catch (error) {
  17533. assert(false, `error encountered with polygon gas station (${JSON.stringify(request.url)})`, "SERVER_ERROR", { request, response, error });
  17534. }
  17535. });
  17536. }
  17537. // See: https://chainlist.org
  17538. let injected = false;
  17539. function injectCommonNetworks() {
  17540. if (injected) {
  17541. return;
  17542. }
  17543. injected = true;
  17544. /// Register popular Ethereum networks
  17545. function registerEth(name, chainId, options) {
  17546. const func = function () {
  17547. const network = new Network(name, chainId);
  17548. // We use 0 to disable ENS
  17549. if (options.ensNetwork != null) {
  17550. network.attachPlugin(new EnsPlugin(null, options.ensNetwork));
  17551. }
  17552. network.attachPlugin(new GasCostPlugin());
  17553. (options.plugins || []).forEach((plugin) => {
  17554. network.attachPlugin(plugin);
  17555. });
  17556. return network;
  17557. };
  17558. // Register the network by name and chain ID
  17559. Network.register(name, func);
  17560. Network.register(chainId, func);
  17561. if (options.altNames) {
  17562. options.altNames.forEach((name) => {
  17563. Network.register(name, func);
  17564. });
  17565. }
  17566. }
  17567. registerEth("mainnet", 1, { ensNetwork: 1, altNames: ["homestead"] });
  17568. registerEth("ropsten", 3, { ensNetwork: 3 });
  17569. registerEth("rinkeby", 4, { ensNetwork: 4 });
  17570. registerEth("goerli", 5, { ensNetwork: 5 });
  17571. registerEth("kovan", 42, { ensNetwork: 42 });
  17572. registerEth("sepolia", 11155111, { ensNetwork: 11155111 });
  17573. registerEth("holesky", 17000, { ensNetwork: 17000 });
  17574. registerEth("classic", 61, {});
  17575. registerEth("classicKotti", 6, {});
  17576. registerEth("arbitrum", 42161, {
  17577. ensNetwork: 1,
  17578. });
  17579. registerEth("arbitrum-goerli", 421613, {});
  17580. registerEth("arbitrum-sepolia", 421614, {});
  17581. registerEth("base", 8453, { ensNetwork: 1 });
  17582. registerEth("base-goerli", 84531, {});
  17583. registerEth("base-sepolia", 84532, {});
  17584. registerEth("bnb", 56, { ensNetwork: 1 });
  17585. registerEth("bnbt", 97, {});
  17586. registerEth("linea", 59144, { ensNetwork: 1 });
  17587. registerEth("linea-goerli", 59140, {});
  17588. registerEth("linea-sepolia", 59141, {});
  17589. registerEth("matic", 137, {
  17590. ensNetwork: 1,
  17591. plugins: [
  17592. getGasStationPlugin("https:/\/gasstation.polygon.technology/v2")
  17593. ]
  17594. });
  17595. registerEth("matic-amoy", 80002, {});
  17596. registerEth("matic-mumbai", 80001, {
  17597. altNames: ["maticMumbai", "maticmum"],
  17598. plugins: [
  17599. getGasStationPlugin("https:/\/gasstation-testnet.polygon.technology/v2")
  17600. ]
  17601. });
  17602. registerEth("optimism", 10, {
  17603. ensNetwork: 1,
  17604. plugins: []
  17605. });
  17606. registerEth("optimism-goerli", 420, {});
  17607. registerEth("optimism-sepolia", 11155420, {});
  17608. registerEth("xdai", 100, { ensNetwork: 1 });
  17609. }
  17610. function copy$2(obj) {
  17611. return JSON.parse(JSON.stringify(obj));
  17612. }
  17613. // @TODO: refactor this
  17614. /**
  17615. * A **PollingBlockSubscriber** polls at a regular interval for a change
  17616. * in the block number.
  17617. *
  17618. * @_docloc: api/providers/abstract-provider
  17619. */
  17620. class PollingBlockSubscriber {
  17621. #provider;
  17622. #poller;
  17623. #interval;
  17624. // The most recent block we have scanned for events. The value -2
  17625. // indicates we still need to fetch an initial block number
  17626. #blockNumber;
  17627. /**
  17628. * Create a new **PollingBlockSubscriber** attached to %%provider%%.
  17629. */
  17630. constructor(provider) {
  17631. this.#provider = provider;
  17632. this.#poller = null;
  17633. this.#interval = 4000;
  17634. this.#blockNumber = -2;
  17635. }
  17636. /**
  17637. * The polling interval.
  17638. */
  17639. get pollingInterval() { return this.#interval; }
  17640. set pollingInterval(value) { this.#interval = value; }
  17641. async #poll() {
  17642. try {
  17643. const blockNumber = await this.#provider.getBlockNumber();
  17644. // Bootstrap poll to setup our initial block number
  17645. if (this.#blockNumber === -2) {
  17646. this.#blockNumber = blockNumber;
  17647. return;
  17648. }
  17649. // @TODO: Put a cap on the maximum number of events per loop?
  17650. if (blockNumber !== this.#blockNumber) {
  17651. for (let b = this.#blockNumber + 1; b <= blockNumber; b++) {
  17652. // We have been stopped
  17653. if (this.#poller == null) {
  17654. return;
  17655. }
  17656. await this.#provider.emit("block", b);
  17657. }
  17658. this.#blockNumber = blockNumber;
  17659. }
  17660. }
  17661. catch (error) {
  17662. // @TODO: Minor bump, add an "error" event to let subscribers
  17663. // know things went awry.
  17664. //console.log(error);
  17665. }
  17666. // We have been stopped
  17667. if (this.#poller == null) {
  17668. return;
  17669. }
  17670. this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval);
  17671. }
  17672. start() {
  17673. if (this.#poller) {
  17674. return;
  17675. }
  17676. this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval);
  17677. this.#poll();
  17678. }
  17679. stop() {
  17680. if (!this.#poller) {
  17681. return;
  17682. }
  17683. this.#provider._clearTimeout(this.#poller);
  17684. this.#poller = null;
  17685. }
  17686. pause(dropWhilePaused) {
  17687. this.stop();
  17688. if (dropWhilePaused) {
  17689. this.#blockNumber = -2;
  17690. }
  17691. }
  17692. resume() {
  17693. this.start();
  17694. }
  17695. }
  17696. /**
  17697. * An **OnBlockSubscriber** can be sub-classed, with a [[_poll]]
  17698. * implmentation which will be called on every new block.
  17699. *
  17700. * @_docloc: api/providers/abstract-provider
  17701. */
  17702. class OnBlockSubscriber {
  17703. #provider;
  17704. #poll;
  17705. #running;
  17706. /**
  17707. * Create a new **OnBlockSubscriber** attached to %%provider%%.
  17708. */
  17709. constructor(provider) {
  17710. this.#provider = provider;
  17711. this.#running = false;
  17712. this.#poll = (blockNumber) => {
  17713. this._poll(blockNumber, this.#provider);
  17714. };
  17715. }
  17716. /**
  17717. * Called on every new block.
  17718. */
  17719. async _poll(blockNumber, provider) {
  17720. throw new Error("sub-classes must override this");
  17721. }
  17722. start() {
  17723. if (this.#running) {
  17724. return;
  17725. }
  17726. this.#running = true;
  17727. this.#poll(-2);
  17728. this.#provider.on("block", this.#poll);
  17729. }
  17730. stop() {
  17731. if (!this.#running) {
  17732. return;
  17733. }
  17734. this.#running = false;
  17735. this.#provider.off("block", this.#poll);
  17736. }
  17737. pause(dropWhilePaused) { this.stop(); }
  17738. resume() { this.start(); }
  17739. }
  17740. class PollingBlockTagSubscriber extends OnBlockSubscriber {
  17741. #tag;
  17742. #lastBlock;
  17743. constructor(provider, tag) {
  17744. super(provider);
  17745. this.#tag = tag;
  17746. this.#lastBlock = -2;
  17747. }
  17748. pause(dropWhilePaused) {
  17749. if (dropWhilePaused) {
  17750. this.#lastBlock = -2;
  17751. }
  17752. super.pause(dropWhilePaused);
  17753. }
  17754. async _poll(blockNumber, provider) {
  17755. const block = await provider.getBlock(this.#tag);
  17756. if (block == null) {
  17757. return;
  17758. }
  17759. if (this.#lastBlock === -2) {
  17760. this.#lastBlock = block.number;
  17761. }
  17762. else if (block.number > this.#lastBlock) {
  17763. provider.emit(this.#tag, block.number);
  17764. this.#lastBlock = block.number;
  17765. }
  17766. }
  17767. }
  17768. /**
  17769. * @_ignore:
  17770. *
  17771. * @_docloc: api/providers/abstract-provider
  17772. */
  17773. class PollingOrphanSubscriber extends OnBlockSubscriber {
  17774. #filter;
  17775. constructor(provider, filter) {
  17776. super(provider);
  17777. this.#filter = copy$2(filter);
  17778. }
  17779. async _poll(blockNumber, provider) {
  17780. throw new Error("@TODO");
  17781. }
  17782. }
  17783. /**
  17784. * A **PollingTransactionSubscriber** will poll for a given transaction
  17785. * hash for its receipt.
  17786. *
  17787. * @_docloc: api/providers/abstract-provider
  17788. */
  17789. class PollingTransactionSubscriber extends OnBlockSubscriber {
  17790. #hash;
  17791. /**
  17792. * Create a new **PollingTransactionSubscriber** attached to
  17793. * %%provider%%, listening for %%hash%%.
  17794. */
  17795. constructor(provider, hash) {
  17796. super(provider);
  17797. this.#hash = hash;
  17798. }
  17799. async _poll(blockNumber, provider) {
  17800. const tx = await provider.getTransactionReceipt(this.#hash);
  17801. if (tx) {
  17802. provider.emit(this.#hash, tx);
  17803. }
  17804. }
  17805. }
  17806. /**
  17807. * A **PollingEventSubscriber** will poll for a given filter for its logs.
  17808. *
  17809. * @_docloc: api/providers/abstract-provider
  17810. */
  17811. class PollingEventSubscriber {
  17812. #provider;
  17813. #filter;
  17814. #poller;
  17815. #running;
  17816. // The most recent block we have scanned for events. The value -2
  17817. // indicates we still need to fetch an initial block number
  17818. #blockNumber;
  17819. /**
  17820. * Create a new **PollingTransactionSubscriber** attached to
  17821. * %%provider%%, listening for %%filter%%.
  17822. */
  17823. constructor(provider, filter) {
  17824. this.#provider = provider;
  17825. this.#filter = copy$2(filter);
  17826. this.#poller = this.#poll.bind(this);
  17827. this.#running = false;
  17828. this.#blockNumber = -2;
  17829. }
  17830. async #poll(blockNumber) {
  17831. // The initial block hasn't been determined yet
  17832. if (this.#blockNumber === -2) {
  17833. return;
  17834. }
  17835. const filter = copy$2(this.#filter);
  17836. filter.fromBlock = this.#blockNumber + 1;
  17837. filter.toBlock = blockNumber;
  17838. const logs = await this.#provider.getLogs(filter);
  17839. // No logs could just mean the node has not indexed them yet,
  17840. // so we keep a sliding window of 60 blocks to keep scanning
  17841. if (logs.length === 0) {
  17842. if (this.#blockNumber < blockNumber - 60) {
  17843. this.#blockNumber = blockNumber - 60;
  17844. }
  17845. return;
  17846. }
  17847. for (const log of logs) {
  17848. this.#provider.emit(this.#filter, log);
  17849. // Only advance the block number when logs were found to
  17850. // account for networks (like BNB and Polygon) which may
  17851. // sacrifice event consistency for block event speed
  17852. this.#blockNumber = log.blockNumber;
  17853. }
  17854. }
  17855. start() {
  17856. if (this.#running) {
  17857. return;
  17858. }
  17859. this.#running = true;
  17860. if (this.#blockNumber === -2) {
  17861. this.#provider.getBlockNumber().then((blockNumber) => {
  17862. this.#blockNumber = blockNumber;
  17863. });
  17864. }
  17865. this.#provider.on("block", this.#poller);
  17866. }
  17867. stop() {
  17868. if (!this.#running) {
  17869. return;
  17870. }
  17871. this.#running = false;
  17872. this.#provider.off("block", this.#poller);
  17873. }
  17874. pause(dropWhilePaused) {
  17875. this.stop();
  17876. if (dropWhilePaused) {
  17877. this.#blockNumber = -2;
  17878. }
  17879. }
  17880. resume() {
  17881. this.start();
  17882. }
  17883. }
  17884. /**
  17885. * The available providers should suffice for most developers purposes,
  17886. * but the [[AbstractProvider]] class has many features which enable
  17887. * sub-classing it for specific purposes.
  17888. *
  17889. * @_section: api/providers/abstract-provider: Subclassing Provider [abstract-provider]
  17890. */
  17891. // @TODO
  17892. // Event coalescence
  17893. // When we register an event with an async value (e.g. address is a Signer
  17894. // or ENS name), we need to add it immeidately for the Event API, but also
  17895. // need time to resolve the address. Upon resolving the address, we need to
  17896. // migrate the listener to the static event. We also need to maintain a map
  17897. // of Signer/ENS name to address so we can sync respond to listenerCount.
  17898. // Constants
  17899. const BN_2$1 = BigInt(2);
  17900. const MAX_CCIP_REDIRECTS = 10;
  17901. function isPromise$1(value) {
  17902. return (value && typeof (value.then) === "function");
  17903. }
  17904. function getTag(prefix, value) {
  17905. return prefix + ":" + JSON.stringify(value, (k, v) => {
  17906. if (v == null) {
  17907. return "null";
  17908. }
  17909. if (typeof (v) === "bigint") {
  17910. return `bigint:${v.toString()}`;
  17911. }
  17912. if (typeof (v) === "string") {
  17913. return v.toLowerCase();
  17914. }
  17915. // Sort object keys
  17916. if (typeof (v) === "object" && !Array.isArray(v)) {
  17917. const keys = Object.keys(v);
  17918. keys.sort();
  17919. return keys.reduce((accum, key) => {
  17920. accum[key] = v[key];
  17921. return accum;
  17922. }, {});
  17923. }
  17924. return v;
  17925. });
  17926. }
  17927. /**
  17928. * An **UnmanagedSubscriber** is useful for events which do not require
  17929. * any additional management, such as ``"debug"`` which only requires
  17930. * emit in synchronous event loop triggered calls.
  17931. */
  17932. class UnmanagedSubscriber {
  17933. /**
  17934. * The name fof the event.
  17935. */
  17936. name;
  17937. /**
  17938. * Create a new UnmanagedSubscriber with %%name%%.
  17939. */
  17940. constructor(name) { defineProperties(this, { name }); }
  17941. start() { }
  17942. stop() { }
  17943. pause(dropWhilePaused) { }
  17944. resume() { }
  17945. }
  17946. function copy$1(value) {
  17947. return JSON.parse(JSON.stringify(value));
  17948. }
  17949. function concisify(items) {
  17950. items = Array.from((new Set(items)).values());
  17951. items.sort();
  17952. return items;
  17953. }
  17954. async function getSubscription(_event, provider) {
  17955. if (_event == null) {
  17956. throw new Error("invalid event");
  17957. }
  17958. // Normalize topic array info an EventFilter
  17959. if (Array.isArray(_event)) {
  17960. _event = { topics: _event };
  17961. }
  17962. if (typeof (_event) === "string") {
  17963. switch (_event) {
  17964. case "block":
  17965. case "debug":
  17966. case "error":
  17967. case "finalized":
  17968. case "network":
  17969. case "pending":
  17970. case "safe": {
  17971. return { type: _event, tag: _event };
  17972. }
  17973. }
  17974. }
  17975. if (isHexString(_event, 32)) {
  17976. const hash = _event.toLowerCase();
  17977. return { type: "transaction", tag: getTag("tx", { hash }), hash };
  17978. }
  17979. if (_event.orphan) {
  17980. const event = _event;
  17981. // @TODO: Should lowercase and whatnot things here instead of copy...
  17982. return { type: "orphan", tag: getTag("orphan", event), filter: copy$1(event) };
  17983. }
  17984. if ((_event.address || _event.topics)) {
  17985. const event = _event;
  17986. const filter = {
  17987. topics: ((event.topics || []).map((t) => {
  17988. if (t == null) {
  17989. return null;
  17990. }
  17991. if (Array.isArray(t)) {
  17992. return concisify(t.map((t) => t.toLowerCase()));
  17993. }
  17994. return t.toLowerCase();
  17995. }))
  17996. };
  17997. if (event.address) {
  17998. const addresses = [];
  17999. const promises = [];
  18000. const addAddress = (addr) => {
  18001. if (isHexString(addr)) {
  18002. addresses.push(addr);
  18003. }
  18004. else {
  18005. promises.push((async () => {
  18006. addresses.push(await resolveAddress(addr, provider));
  18007. })());
  18008. }
  18009. };
  18010. if (Array.isArray(event.address)) {
  18011. event.address.forEach(addAddress);
  18012. }
  18013. else {
  18014. addAddress(event.address);
  18015. }
  18016. if (promises.length) {
  18017. await Promise.all(promises);
  18018. }
  18019. filter.address = concisify(addresses.map((a) => a.toLowerCase()));
  18020. }
  18021. return { filter, tag: getTag("event", filter), type: "event" };
  18022. }
  18023. assertArgument(false, "unknown ProviderEvent", "event", _event);
  18024. }
  18025. function getTime$1() { return (new Date()).getTime(); }
  18026. const defaultOptions$1 = {
  18027. cacheTimeout: 250,
  18028. pollingInterval: 4000
  18029. };
  18030. /**
  18031. * An **AbstractProvider** provides a base class for other sub-classes to
  18032. * implement the [[Provider]] API by normalizing input arguments and
  18033. * formatting output results as well as tracking events for consistent
  18034. * behaviour on an eventually-consistent network.
  18035. */
  18036. class AbstractProvider {
  18037. #subs;
  18038. #plugins;
  18039. // null=unpaused, true=paused+dropWhilePaused, false=paused
  18040. #pausedState;
  18041. #destroyed;
  18042. #networkPromise;
  18043. #anyNetwork;
  18044. #performCache;
  18045. // The most recent block number if running an event or -1 if no "block" event
  18046. #lastBlockNumber;
  18047. #nextTimer;
  18048. #timers;
  18049. #disableCcipRead;
  18050. #options;
  18051. /**
  18052. * Create a new **AbstractProvider** connected to %%network%%, or
  18053. * use the various network detection capabilities to discover the
  18054. * [[Network]] if necessary.
  18055. */
  18056. constructor(_network, options) {
  18057. this.#options = Object.assign({}, defaultOptions$1, options || {});
  18058. if (_network === "any") {
  18059. this.#anyNetwork = true;
  18060. this.#networkPromise = null;
  18061. }
  18062. else if (_network) {
  18063. const network = Network.from(_network);
  18064. this.#anyNetwork = false;
  18065. this.#networkPromise = Promise.resolve(network);
  18066. setTimeout(() => { this.emit("network", network, null); }, 0);
  18067. }
  18068. else {
  18069. this.#anyNetwork = false;
  18070. this.#networkPromise = null;
  18071. }
  18072. this.#lastBlockNumber = -1;
  18073. this.#performCache = new Map();
  18074. this.#subs = new Map();
  18075. this.#plugins = new Map();
  18076. this.#pausedState = null;
  18077. this.#destroyed = false;
  18078. this.#nextTimer = 1;
  18079. this.#timers = new Map();
  18080. this.#disableCcipRead = false;
  18081. }
  18082. get pollingInterval() { return this.#options.pollingInterval; }
  18083. /**
  18084. * Returns ``this``, to allow an **AbstractProvider** to implement
  18085. * the [[ContractRunner]] interface.
  18086. */
  18087. get provider() { return this; }
  18088. /**
  18089. * Returns all the registered plug-ins.
  18090. */
  18091. get plugins() {
  18092. return Array.from(this.#plugins.values());
  18093. }
  18094. /**
  18095. * Attach a new plug-in.
  18096. */
  18097. attachPlugin(plugin) {
  18098. if (this.#plugins.get(plugin.name)) {
  18099. throw new Error(`cannot replace existing plugin: ${plugin.name} `);
  18100. }
  18101. this.#plugins.set(plugin.name, plugin.connect(this));
  18102. return this;
  18103. }
  18104. /**
  18105. * Get a plugin by name.
  18106. */
  18107. getPlugin(name) {
  18108. return (this.#plugins.get(name)) || null;
  18109. }
  18110. /**
  18111. * Prevent any CCIP-read operation, regardless of whether requested
  18112. * in a [[call]] using ``enableCcipRead``.
  18113. */
  18114. get disableCcipRead() { return this.#disableCcipRead; }
  18115. set disableCcipRead(value) { this.#disableCcipRead = !!value; }
  18116. // Shares multiple identical requests made during the same 250ms
  18117. async #perform(req) {
  18118. const timeout = this.#options.cacheTimeout;
  18119. // Caching disabled
  18120. if (timeout < 0) {
  18121. return await this._perform(req);
  18122. }
  18123. // Create a tag
  18124. const tag = getTag(req.method, req);
  18125. let perform = this.#performCache.get(tag);
  18126. if (!perform) {
  18127. perform = this._perform(req);
  18128. this.#performCache.set(tag, perform);
  18129. setTimeout(() => {
  18130. if (this.#performCache.get(tag) === perform) {
  18131. this.#performCache.delete(tag);
  18132. }
  18133. }, timeout);
  18134. }
  18135. return await perform;
  18136. }
  18137. /**
  18138. * Resolves to the data for executing the CCIP-read operations.
  18139. */
  18140. async ccipReadFetch(tx, calldata, urls) {
  18141. if (this.disableCcipRead || urls.length === 0 || tx.to == null) {
  18142. return null;
  18143. }
  18144. const sender = tx.to.toLowerCase();
  18145. const data = calldata.toLowerCase();
  18146. const errorMessages = [];
  18147. for (let i = 0; i < urls.length; i++) {
  18148. const url = urls[i];
  18149. // URL expansion
  18150. const href = url.replace("{sender}", sender).replace("{data}", data);
  18151. // If no {data} is present, use POST; otherwise GET
  18152. //const json: string | null = (url.indexOf("{data}") >= 0) ? null: JSON.stringify({ data, sender });
  18153. //const result = await fetchJson({ url: href, errorPassThrough: true }, json, (value, response) => {
  18154. // value.status = response.statusCode;
  18155. // return value;
  18156. //});
  18157. const request = new FetchRequest(href);
  18158. if (url.indexOf("{data}") === -1) {
  18159. request.body = { data, sender };
  18160. }
  18161. this.emit("debug", { action: "sendCcipReadFetchRequest", request, index: i, urls });
  18162. let errorMessage = "unknown error";
  18163. // Fetch the resource...
  18164. let resp;
  18165. try {
  18166. resp = await request.send();
  18167. }
  18168. catch (error) {
  18169. // ...low-level fetch error (missing host, bad SSL, etc.),
  18170. // so try next URL
  18171. errorMessages.push(error.message);
  18172. this.emit("debug", { action: "receiveCcipReadFetchError", request, result: { error } });
  18173. continue;
  18174. }
  18175. try {
  18176. const result = resp.bodyJson;
  18177. if (result.data) {
  18178. this.emit("debug", { action: "receiveCcipReadFetchResult", request, result });
  18179. return result.data;
  18180. }
  18181. if (result.message) {
  18182. errorMessage = result.message;
  18183. }
  18184. this.emit("debug", { action: "receiveCcipReadFetchError", request, result });
  18185. }
  18186. catch (error) { }
  18187. // 4xx indicates the result is not present; stop
  18188. 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 } });
  18189. // 5xx indicates server issue; try the next url
  18190. errorMessages.push(errorMessage);
  18191. }
  18192. assert(false, `error encountered during CCIP fetch: ${errorMessages.map((m) => JSON.stringify(m)).join(", ")}`, "OFFCHAIN_FAULT", {
  18193. reason: "500_SERVER_ERROR",
  18194. transaction: tx, info: { urls, errorMessages }
  18195. });
  18196. }
  18197. /**
  18198. * Provides the opportunity for a sub-class to wrap a block before
  18199. * returning it, to add additional properties or an alternate
  18200. * sub-class of [[Block]].
  18201. */
  18202. _wrapBlock(value, network) {
  18203. return new Block(formatBlock(value), this);
  18204. }
  18205. /**
  18206. * Provides the opportunity for a sub-class to wrap a log before
  18207. * returning it, to add additional properties or an alternate
  18208. * sub-class of [[Log]].
  18209. */
  18210. _wrapLog(value, network) {
  18211. return new Log(formatLog(value), this);
  18212. }
  18213. /**
  18214. * Provides the opportunity for a sub-class to wrap a transaction
  18215. * receipt before returning it, to add additional properties or an
  18216. * alternate sub-class of [[TransactionReceipt]].
  18217. */
  18218. _wrapTransactionReceipt(value, network) {
  18219. return new TransactionReceipt(formatTransactionReceipt(value), this);
  18220. }
  18221. /**
  18222. * Provides the opportunity for a sub-class to wrap a transaction
  18223. * response before returning it, to add additional properties or an
  18224. * alternate sub-class of [[TransactionResponse]].
  18225. */
  18226. _wrapTransactionResponse(tx, network) {
  18227. return new TransactionResponse(formatTransactionResponse(tx), this);
  18228. }
  18229. /**
  18230. * Resolves to the Network, forcing a network detection using whatever
  18231. * technique the sub-class requires.
  18232. *
  18233. * Sub-classes **must** override this.
  18234. */
  18235. _detectNetwork() {
  18236. assert(false, "sub-classes must implement this", "UNSUPPORTED_OPERATION", {
  18237. operation: "_detectNetwork"
  18238. });
  18239. }
  18240. /**
  18241. * Sub-classes should use this to perform all built-in operations. All
  18242. * methods sanitizes and normalizes the values passed into this.
  18243. *
  18244. * Sub-classes **must** override this.
  18245. */
  18246. async _perform(req) {
  18247. assert(false, `unsupported method: ${req.method}`, "UNSUPPORTED_OPERATION", {
  18248. operation: req.method,
  18249. info: req
  18250. });
  18251. }
  18252. // State
  18253. async getBlockNumber() {
  18254. const blockNumber = getNumber(await this.#perform({ method: "getBlockNumber" }), "%response");
  18255. if (this.#lastBlockNumber >= 0) {
  18256. this.#lastBlockNumber = blockNumber;
  18257. }
  18258. return blockNumber;
  18259. }
  18260. /**
  18261. * Returns or resolves to the address for %%address%%, resolving ENS
  18262. * names and [[Addressable]] objects and returning if already an
  18263. * address.
  18264. */
  18265. _getAddress(address) {
  18266. return resolveAddress(address, this);
  18267. }
  18268. /**
  18269. * Returns or resolves to a valid block tag for %%blockTag%%, resolving
  18270. * negative values and returning if already a valid block tag.
  18271. */
  18272. _getBlockTag(blockTag) {
  18273. if (blockTag == null) {
  18274. return "latest";
  18275. }
  18276. switch (blockTag) {
  18277. case "earliest":
  18278. return "0x0";
  18279. case "finalized":
  18280. case "latest":
  18281. case "pending":
  18282. case "safe":
  18283. return blockTag;
  18284. }
  18285. if (isHexString(blockTag)) {
  18286. if (isHexString(blockTag, 32)) {
  18287. return blockTag;
  18288. }
  18289. return toQuantity(blockTag);
  18290. }
  18291. if (typeof (blockTag) === "bigint") {
  18292. blockTag = getNumber(blockTag, "blockTag");
  18293. }
  18294. if (typeof (blockTag) === "number") {
  18295. if (blockTag >= 0) {
  18296. return toQuantity(blockTag);
  18297. }
  18298. if (this.#lastBlockNumber >= 0) {
  18299. return toQuantity(this.#lastBlockNumber + blockTag);
  18300. }
  18301. return this.getBlockNumber().then((b) => toQuantity(b + blockTag));
  18302. }
  18303. assertArgument(false, "invalid blockTag", "blockTag", blockTag);
  18304. }
  18305. /**
  18306. * Returns or resolves to a filter for %%filter%%, resolving any ENS
  18307. * names or [[Addressable]] object and returning if already a valid
  18308. * filter.
  18309. */
  18310. _getFilter(filter) {
  18311. // Create a canonical representation of the topics
  18312. const topics = (filter.topics || []).map((t) => {
  18313. if (t == null) {
  18314. return null;
  18315. }
  18316. if (Array.isArray(t)) {
  18317. return concisify(t.map((t) => t.toLowerCase()));
  18318. }
  18319. return t.toLowerCase();
  18320. });
  18321. const blockHash = ("blockHash" in filter) ? filter.blockHash : undefined;
  18322. const resolve = (_address, fromBlock, toBlock) => {
  18323. let address = undefined;
  18324. switch (_address.length) {
  18325. case 0: break;
  18326. case 1:
  18327. address = _address[0];
  18328. break;
  18329. default:
  18330. _address.sort();
  18331. address = _address;
  18332. }
  18333. if (blockHash) {
  18334. if (fromBlock != null || toBlock != null) {
  18335. throw new Error("invalid filter");
  18336. }
  18337. }
  18338. const filter = {};
  18339. if (address) {
  18340. filter.address = address;
  18341. }
  18342. if (topics.length) {
  18343. filter.topics = topics;
  18344. }
  18345. if (fromBlock) {
  18346. filter.fromBlock = fromBlock;
  18347. }
  18348. if (toBlock) {
  18349. filter.toBlock = toBlock;
  18350. }
  18351. if (blockHash) {
  18352. filter.blockHash = blockHash;
  18353. }
  18354. return filter;
  18355. };
  18356. // Addresses could be async (ENS names or Addressables)
  18357. let address = [];
  18358. if (filter.address) {
  18359. if (Array.isArray(filter.address)) {
  18360. for (const addr of filter.address) {
  18361. address.push(this._getAddress(addr));
  18362. }
  18363. }
  18364. else {
  18365. address.push(this._getAddress(filter.address));
  18366. }
  18367. }
  18368. let fromBlock = undefined;
  18369. if ("fromBlock" in filter) {
  18370. fromBlock = this._getBlockTag(filter.fromBlock);
  18371. }
  18372. let toBlock = undefined;
  18373. if ("toBlock" in filter) {
  18374. toBlock = this._getBlockTag(filter.toBlock);
  18375. }
  18376. if (address.filter((a) => (typeof (a) !== "string")).length ||
  18377. (fromBlock != null && typeof (fromBlock) !== "string") ||
  18378. (toBlock != null && typeof (toBlock) !== "string")) {
  18379. return Promise.all([Promise.all(address), fromBlock, toBlock]).then((result) => {
  18380. return resolve(result[0], result[1], result[2]);
  18381. });
  18382. }
  18383. return resolve(address, fromBlock, toBlock);
  18384. }
  18385. /**
  18386. * Returns or resolves to a transaction for %%request%%, resolving
  18387. * any ENS names or [[Addressable]] and returning if already a valid
  18388. * transaction.
  18389. */
  18390. _getTransactionRequest(_request) {
  18391. const request = copyRequest(_request);
  18392. const promises = [];
  18393. ["to", "from"].forEach((key) => {
  18394. if (request[key] == null) {
  18395. return;
  18396. }
  18397. const addr = resolveAddress(request[key], this);
  18398. if (isPromise$1(addr)) {
  18399. promises.push((async function () { request[key] = await addr; })());
  18400. }
  18401. else {
  18402. request[key] = addr;
  18403. }
  18404. });
  18405. if (request.blockTag != null) {
  18406. const blockTag = this._getBlockTag(request.blockTag);
  18407. if (isPromise$1(blockTag)) {
  18408. promises.push((async function () { request.blockTag = await blockTag; })());
  18409. }
  18410. else {
  18411. request.blockTag = blockTag;
  18412. }
  18413. }
  18414. if (promises.length) {
  18415. return (async function () {
  18416. await Promise.all(promises);
  18417. return request;
  18418. })();
  18419. }
  18420. return request;
  18421. }
  18422. async getNetwork() {
  18423. // No explicit network was set and this is our first time
  18424. if (this.#networkPromise == null) {
  18425. // Detect the current network (shared with all calls)
  18426. const detectNetwork = (async () => {
  18427. try {
  18428. const network = await this._detectNetwork();
  18429. this.emit("network", network, null);
  18430. return network;
  18431. }
  18432. catch (error) {
  18433. if (this.#networkPromise === detectNetwork) {
  18434. this.#networkPromise = null;
  18435. }
  18436. throw error;
  18437. }
  18438. })();
  18439. this.#networkPromise = detectNetwork;
  18440. return (await detectNetwork).clone();
  18441. }
  18442. const networkPromise = this.#networkPromise;
  18443. const [expected, actual] = await Promise.all([
  18444. networkPromise,
  18445. this._detectNetwork() // The actual connected network
  18446. ]);
  18447. if (expected.chainId !== actual.chainId) {
  18448. if (this.#anyNetwork) {
  18449. // The "any" network can change, so notify listeners
  18450. this.emit("network", actual, expected);
  18451. // Update the network if something else hasn't already changed it
  18452. if (this.#networkPromise === networkPromise) {
  18453. this.#networkPromise = Promise.resolve(actual);
  18454. }
  18455. }
  18456. else {
  18457. // Otherwise, we do not allow changes to the underlying network
  18458. assert(false, `network changed: ${expected.chainId} => ${actual.chainId} `, "NETWORK_ERROR", {
  18459. event: "changed"
  18460. });
  18461. }
  18462. }
  18463. return expected.clone();
  18464. }
  18465. async getFeeData() {
  18466. const network = await this.getNetwork();
  18467. const getFeeDataFunc = async () => {
  18468. const { _block, gasPrice, priorityFee } = await resolveProperties({
  18469. _block: this.#getBlock("latest", false),
  18470. gasPrice: ((async () => {
  18471. try {
  18472. const value = await this.#perform({ method: "getGasPrice" });
  18473. return getBigInt(value, "%response");
  18474. }
  18475. catch (error) { }
  18476. return null;
  18477. })()),
  18478. priorityFee: ((async () => {
  18479. try {
  18480. const value = await this.#perform({ method: "getPriorityFee" });
  18481. return getBigInt(value, "%response");
  18482. }
  18483. catch (error) { }
  18484. return null;
  18485. })())
  18486. });
  18487. let maxFeePerGas = null;
  18488. let maxPriorityFeePerGas = null;
  18489. // These are the recommended EIP-1559 heuristics for fee data
  18490. const block = this._wrapBlock(_block, network);
  18491. if (block && block.baseFeePerGas) {
  18492. maxPriorityFeePerGas = (priorityFee != null) ? priorityFee : BigInt("1000000000");
  18493. maxFeePerGas = (block.baseFeePerGas * BN_2$1) + maxPriorityFeePerGas;
  18494. }
  18495. return new FeeData(gasPrice, maxFeePerGas, maxPriorityFeePerGas);
  18496. };
  18497. // Check for a FeeDataNetWorkPlugin
  18498. const plugin = network.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin");
  18499. if (plugin) {
  18500. const req = new FetchRequest(plugin.url);
  18501. const feeData = await plugin.processFunc(getFeeDataFunc, this, req);
  18502. return new FeeData(feeData.gasPrice, feeData.maxFeePerGas, feeData.maxPriorityFeePerGas);
  18503. }
  18504. return await getFeeDataFunc();
  18505. }
  18506. async estimateGas(_tx) {
  18507. let tx = this._getTransactionRequest(_tx);
  18508. if (isPromise$1(tx)) {
  18509. tx = await tx;
  18510. }
  18511. return getBigInt(await this.#perform({
  18512. method: "estimateGas", transaction: tx
  18513. }), "%response");
  18514. }
  18515. async #call(tx, blockTag, attempt) {
  18516. assert(attempt < MAX_CCIP_REDIRECTS, "CCIP read exceeded maximum redirections", "OFFCHAIN_FAULT", {
  18517. reason: "TOO_MANY_REDIRECTS",
  18518. transaction: Object.assign({}, tx, { blockTag, enableCcipRead: true })
  18519. });
  18520. // This came in as a PerformActionTransaction, so to/from are safe; we can cast
  18521. const transaction = copyRequest(tx);
  18522. try {
  18523. return hexlify(await this._perform({ method: "call", transaction, blockTag }));
  18524. }
  18525. catch (error) {
  18526. // CCIP Read OffchainLookup
  18527. if (!this.disableCcipRead && isCallException(error) && error.data && attempt >= 0 && blockTag === "latest" && transaction.to != null && dataSlice(error.data, 0, 4) === "0x556f1830") {
  18528. const data = error.data;
  18529. const txSender = await resolveAddress(transaction.to, this);
  18530. // Parse the CCIP Read Arguments
  18531. let ccipArgs;
  18532. try {
  18533. ccipArgs = parseOffchainLookup(dataSlice(error.data, 4));
  18534. }
  18535. catch (error) {
  18536. assert(false, error.message, "OFFCHAIN_FAULT", {
  18537. reason: "BAD_DATA", transaction, info: { data }
  18538. });
  18539. }
  18540. // Check the sender of the OffchainLookup matches the transaction
  18541. assert(ccipArgs.sender.toLowerCase() === txSender.toLowerCase(), "CCIP Read sender mismatch", "CALL_EXCEPTION", {
  18542. action: "call",
  18543. data,
  18544. reason: "OffchainLookup",
  18545. transaction: transaction,
  18546. invocation: null,
  18547. revert: {
  18548. signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
  18549. name: "OffchainLookup",
  18550. args: ccipArgs.errorArgs
  18551. }
  18552. });
  18553. const ccipResult = await this.ccipReadFetch(transaction, ccipArgs.calldata, ccipArgs.urls);
  18554. assert(ccipResult != null, "CCIP Read failed to fetch data", "OFFCHAIN_FAULT", {
  18555. reason: "FETCH_FAILED", transaction, info: { data: error.data, errorArgs: ccipArgs.errorArgs }
  18556. });
  18557. const tx = {
  18558. to: txSender,
  18559. data: concat([ccipArgs.selector, encodeBytes([ccipResult, ccipArgs.extraData])])
  18560. };
  18561. this.emit("debug", { action: "sendCcipReadCall", transaction: tx });
  18562. try {
  18563. const result = await this.#call(tx, blockTag, attempt + 1);
  18564. this.emit("debug", { action: "receiveCcipReadCallResult", transaction: Object.assign({}, tx), result });
  18565. return result;
  18566. }
  18567. catch (error) {
  18568. this.emit("debug", { action: "receiveCcipReadCallError", transaction: Object.assign({}, tx), error });
  18569. throw error;
  18570. }
  18571. }
  18572. throw error;
  18573. }
  18574. }
  18575. async #checkNetwork(promise) {
  18576. const { value } = await resolveProperties({
  18577. network: this.getNetwork(),
  18578. value: promise
  18579. });
  18580. return value;
  18581. }
  18582. async call(_tx) {
  18583. const { tx, blockTag } = await resolveProperties({
  18584. tx: this._getTransactionRequest(_tx),
  18585. blockTag: this._getBlockTag(_tx.blockTag)
  18586. });
  18587. return await this.#checkNetwork(this.#call(tx, blockTag, _tx.enableCcipRead ? 0 : -1));
  18588. }
  18589. // Account
  18590. async #getAccountValue(request, _address, _blockTag) {
  18591. let address = this._getAddress(_address);
  18592. let blockTag = this._getBlockTag(_blockTag);
  18593. if (typeof (address) !== "string" || typeof (blockTag) !== "string") {
  18594. [address, blockTag] = await Promise.all([address, blockTag]);
  18595. }
  18596. return await this.#checkNetwork(this.#perform(Object.assign(request, { address, blockTag })));
  18597. }
  18598. async getBalance(address, blockTag) {
  18599. return getBigInt(await this.#getAccountValue({ method: "getBalance" }, address, blockTag), "%response");
  18600. }
  18601. async getTransactionCount(address, blockTag) {
  18602. return getNumber(await this.#getAccountValue({ method: "getTransactionCount" }, address, blockTag), "%response");
  18603. }
  18604. async getCode(address, blockTag) {
  18605. return hexlify(await this.#getAccountValue({ method: "getCode" }, address, blockTag));
  18606. }
  18607. async getStorage(address, _position, blockTag) {
  18608. const position = getBigInt(_position, "position");
  18609. return hexlify(await this.#getAccountValue({ method: "getStorage", position }, address, blockTag));
  18610. }
  18611. // Write
  18612. async broadcastTransaction(signedTx) {
  18613. const { blockNumber, hash, network } = await resolveProperties({
  18614. blockNumber: this.getBlockNumber(),
  18615. hash: this._perform({
  18616. method: "broadcastTransaction",
  18617. signedTransaction: signedTx
  18618. }),
  18619. network: this.getNetwork()
  18620. });
  18621. const tx = Transaction.from(signedTx);
  18622. if (tx.hash !== hash) {
  18623. throw new Error("@TODO: the returned hash did not match");
  18624. }
  18625. return this._wrapTransactionResponse(tx, network).replaceableTransaction(blockNumber);
  18626. }
  18627. async #getBlock(block, includeTransactions) {
  18628. // @TODO: Add CustomBlockPlugin check
  18629. if (isHexString(block, 32)) {
  18630. return await this.#perform({
  18631. method: "getBlock", blockHash: block, includeTransactions
  18632. });
  18633. }
  18634. let blockTag = this._getBlockTag(block);
  18635. if (typeof (blockTag) !== "string") {
  18636. blockTag = await blockTag;
  18637. }
  18638. return await this.#perform({
  18639. method: "getBlock", blockTag, includeTransactions
  18640. });
  18641. }
  18642. // Queries
  18643. async getBlock(block, prefetchTxs) {
  18644. const { network, params } = await resolveProperties({
  18645. network: this.getNetwork(),
  18646. params: this.#getBlock(block, !!prefetchTxs)
  18647. });
  18648. if (params == null) {
  18649. return null;
  18650. }
  18651. return this._wrapBlock(params, network);
  18652. }
  18653. async getTransaction(hash) {
  18654. const { network, params } = await resolveProperties({
  18655. network: this.getNetwork(),
  18656. params: this.#perform({ method: "getTransaction", hash })
  18657. });
  18658. if (params == null) {
  18659. return null;
  18660. }
  18661. return this._wrapTransactionResponse(params, network);
  18662. }
  18663. async getTransactionReceipt(hash) {
  18664. const { network, params } = await resolveProperties({
  18665. network: this.getNetwork(),
  18666. params: this.#perform({ method: "getTransactionReceipt", hash })
  18667. });
  18668. if (params == null) {
  18669. return null;
  18670. }
  18671. // Some backends did not backfill the effectiveGasPrice into old transactions
  18672. // in the receipt, so we look it up manually and inject it.
  18673. if (params.gasPrice == null && params.effectiveGasPrice == null) {
  18674. const tx = await this.#perform({ method: "getTransaction", hash });
  18675. if (tx == null) {
  18676. throw new Error("report this; could not find tx or effectiveGasPrice");
  18677. }
  18678. params.effectiveGasPrice = tx.gasPrice;
  18679. }
  18680. return this._wrapTransactionReceipt(params, network);
  18681. }
  18682. async getTransactionResult(hash) {
  18683. const { result } = await resolveProperties({
  18684. network: this.getNetwork(),
  18685. result: this.#perform({ method: "getTransactionResult", hash })
  18686. });
  18687. if (result == null) {
  18688. return null;
  18689. }
  18690. return hexlify(result);
  18691. }
  18692. // Bloom-filter Queries
  18693. async getLogs(_filter) {
  18694. let filter = this._getFilter(_filter);
  18695. if (isPromise$1(filter)) {
  18696. filter = await filter;
  18697. }
  18698. const { network, params } = await resolveProperties({
  18699. network: this.getNetwork(),
  18700. params: this.#perform({ method: "getLogs", filter })
  18701. });
  18702. return params.map((p) => this._wrapLog(p, network));
  18703. }
  18704. // ENS
  18705. _getProvider(chainId) {
  18706. assert(false, "provider cannot connect to target network", "UNSUPPORTED_OPERATION", {
  18707. operation: "_getProvider()"
  18708. });
  18709. }
  18710. async getResolver(name) {
  18711. return await EnsResolver.fromName(this, name);
  18712. }
  18713. async getAvatar(name) {
  18714. const resolver = await this.getResolver(name);
  18715. if (resolver) {
  18716. return await resolver.getAvatar();
  18717. }
  18718. return null;
  18719. }
  18720. async resolveName(name) {
  18721. const resolver = await this.getResolver(name);
  18722. if (resolver) {
  18723. return await resolver.getAddress();
  18724. }
  18725. return null;
  18726. }
  18727. async lookupAddress(address) {
  18728. address = getAddress(address);
  18729. const node = namehash(address.substring(2).toLowerCase() + ".addr.reverse");
  18730. try {
  18731. const ensAddr = await EnsResolver.getEnsAddress(this);
  18732. const ensContract = new Contract(ensAddr, [
  18733. "function resolver(bytes32) view returns (address)"
  18734. ], this);
  18735. const resolver = await ensContract.resolver(node);
  18736. if (resolver == null || resolver === ZeroAddress) {
  18737. return null;
  18738. }
  18739. const resolverContract = new Contract(resolver, [
  18740. "function name(bytes32) view returns (string)"
  18741. ], this);
  18742. const name = await resolverContract.name(node);
  18743. // Failed forward resolution
  18744. const check = await this.resolveName(name);
  18745. if (check !== address) {
  18746. return null;
  18747. }
  18748. return name;
  18749. }
  18750. catch (error) {
  18751. // No data was returned from the resolver
  18752. if (isError(error, "BAD_DATA") && error.value === "0x") {
  18753. return null;
  18754. }
  18755. // Something reerted
  18756. if (isError(error, "CALL_EXCEPTION")) {
  18757. return null;
  18758. }
  18759. throw error;
  18760. }
  18761. return null;
  18762. }
  18763. async waitForTransaction(hash, _confirms, timeout) {
  18764. const confirms = (_confirms != null) ? _confirms : 1;
  18765. if (confirms === 0) {
  18766. return this.getTransactionReceipt(hash);
  18767. }
  18768. return new Promise(async (resolve, reject) => {
  18769. let timer = null;
  18770. const listener = (async (blockNumber) => {
  18771. try {
  18772. const receipt = await this.getTransactionReceipt(hash);
  18773. if (receipt != null) {
  18774. if (blockNumber - receipt.blockNumber + 1 >= confirms) {
  18775. resolve(receipt);
  18776. //this.off("block", listener);
  18777. if (timer) {
  18778. clearTimeout(timer);
  18779. timer = null;
  18780. }
  18781. return;
  18782. }
  18783. }
  18784. }
  18785. catch (error) {
  18786. console.log("EEE", error);
  18787. }
  18788. this.once("block", listener);
  18789. });
  18790. if (timeout != null) {
  18791. timer = setTimeout(() => {
  18792. if (timer == null) {
  18793. return;
  18794. }
  18795. timer = null;
  18796. this.off("block", listener);
  18797. reject(makeError("timeout", "TIMEOUT", { reason: "timeout" }));
  18798. }, timeout);
  18799. }
  18800. listener(await this.getBlockNumber());
  18801. });
  18802. }
  18803. async waitForBlock(blockTag) {
  18804. assert(false, "not implemented yet", "NOT_IMPLEMENTED", {
  18805. operation: "waitForBlock"
  18806. });
  18807. }
  18808. /**
  18809. * Clear a timer created using the [[_setTimeout]] method.
  18810. */
  18811. _clearTimeout(timerId) {
  18812. const timer = this.#timers.get(timerId);
  18813. if (!timer) {
  18814. return;
  18815. }
  18816. if (timer.timer) {
  18817. clearTimeout(timer.timer);
  18818. }
  18819. this.#timers.delete(timerId);
  18820. }
  18821. /**
  18822. * Create a timer that will execute %%func%% after at least %%timeout%%
  18823. * (in ms). If %%timeout%% is unspecified, then %%func%% will execute
  18824. * in the next event loop.
  18825. *
  18826. * [Pausing](AbstractProvider-paused) the provider will pause any
  18827. * associated timers.
  18828. */
  18829. _setTimeout(_func, timeout) {
  18830. if (timeout == null) {
  18831. timeout = 0;
  18832. }
  18833. const timerId = this.#nextTimer++;
  18834. const func = () => {
  18835. this.#timers.delete(timerId);
  18836. _func();
  18837. };
  18838. if (this.paused) {
  18839. this.#timers.set(timerId, { timer: null, func, time: timeout });
  18840. }
  18841. else {
  18842. const timer = setTimeout(func, timeout);
  18843. this.#timers.set(timerId, { timer, func, time: getTime$1() });
  18844. }
  18845. return timerId;
  18846. }
  18847. /**
  18848. * Perform %%func%% on each subscriber.
  18849. */
  18850. _forEachSubscriber(func) {
  18851. for (const sub of this.#subs.values()) {
  18852. func(sub.subscriber);
  18853. }
  18854. }
  18855. /**
  18856. * Sub-classes may override this to customize subscription
  18857. * implementations.
  18858. */
  18859. _getSubscriber(sub) {
  18860. switch (sub.type) {
  18861. case "debug":
  18862. case "error":
  18863. case "network":
  18864. return new UnmanagedSubscriber(sub.type);
  18865. case "block": {
  18866. const subscriber = new PollingBlockSubscriber(this);
  18867. subscriber.pollingInterval = this.pollingInterval;
  18868. return subscriber;
  18869. }
  18870. case "safe":
  18871. case "finalized":
  18872. return new PollingBlockTagSubscriber(this, sub.type);
  18873. case "event":
  18874. return new PollingEventSubscriber(this, sub.filter);
  18875. case "transaction":
  18876. return new PollingTransactionSubscriber(this, sub.hash);
  18877. case "orphan":
  18878. return new PollingOrphanSubscriber(this, sub.filter);
  18879. }
  18880. throw new Error(`unsupported event: ${sub.type}`);
  18881. }
  18882. /**
  18883. * If a [[Subscriber]] fails and needs to replace itself, this
  18884. * method may be used.
  18885. *
  18886. * For example, this is used for providers when using the
  18887. * ``eth_getFilterChanges`` method, which can return null if state
  18888. * filters are not supported by the backend, allowing the Subscriber
  18889. * to swap in a [[PollingEventSubscriber]].
  18890. */
  18891. _recoverSubscriber(oldSub, newSub) {
  18892. for (const sub of this.#subs.values()) {
  18893. if (sub.subscriber === oldSub) {
  18894. if (sub.started) {
  18895. sub.subscriber.stop();
  18896. }
  18897. sub.subscriber = newSub;
  18898. if (sub.started) {
  18899. newSub.start();
  18900. }
  18901. if (this.#pausedState != null) {
  18902. newSub.pause(this.#pausedState);
  18903. }
  18904. break;
  18905. }
  18906. }
  18907. }
  18908. async #hasSub(event, emitArgs) {
  18909. let sub = await getSubscription(event, this);
  18910. // This is a log that is removing an existing log; we actually want
  18911. // to emit an orphan event for the removed log
  18912. if (sub.type === "event" && emitArgs && emitArgs.length > 0 && emitArgs[0].removed === true) {
  18913. sub = await getSubscription({ orphan: "drop-log", log: emitArgs[0] }, this);
  18914. }
  18915. return this.#subs.get(sub.tag) || null;
  18916. }
  18917. async #getSub(event) {
  18918. const subscription = await getSubscription(event, this);
  18919. // Prevent tampering with our tag in any subclass' _getSubscriber
  18920. const tag = subscription.tag;
  18921. let sub = this.#subs.get(tag);
  18922. if (!sub) {
  18923. const subscriber = this._getSubscriber(subscription);
  18924. const addressableMap = new WeakMap();
  18925. const nameMap = new Map();
  18926. sub = { subscriber, tag, addressableMap, nameMap, started: false, listeners: [] };
  18927. this.#subs.set(tag, sub);
  18928. }
  18929. return sub;
  18930. }
  18931. async on(event, listener) {
  18932. const sub = await this.#getSub(event);
  18933. sub.listeners.push({ listener, once: false });
  18934. if (!sub.started) {
  18935. sub.subscriber.start();
  18936. sub.started = true;
  18937. if (this.#pausedState != null) {
  18938. sub.subscriber.pause(this.#pausedState);
  18939. }
  18940. }
  18941. return this;
  18942. }
  18943. async once(event, listener) {
  18944. const sub = await this.#getSub(event);
  18945. sub.listeners.push({ listener, once: true });
  18946. if (!sub.started) {
  18947. sub.subscriber.start();
  18948. sub.started = true;
  18949. if (this.#pausedState != null) {
  18950. sub.subscriber.pause(this.#pausedState);
  18951. }
  18952. }
  18953. return this;
  18954. }
  18955. async emit(event, ...args) {
  18956. const sub = await this.#hasSub(event, args);
  18957. // If there is not subscription or if a recent emit removed
  18958. // the last of them (which also deleted the sub) do nothing
  18959. if (!sub || sub.listeners.length === 0) {
  18960. return false;
  18961. }
  18962. const count = sub.listeners.length;
  18963. sub.listeners = sub.listeners.filter(({ listener, once }) => {
  18964. const payload = new EventPayload(this, (once ? null : listener), event);
  18965. try {
  18966. listener.call(this, ...args, payload);
  18967. }
  18968. catch (error) { }
  18969. return !once;
  18970. });
  18971. if (sub.listeners.length === 0) {
  18972. if (sub.started) {
  18973. sub.subscriber.stop();
  18974. }
  18975. this.#subs.delete(sub.tag);
  18976. }
  18977. return (count > 0);
  18978. }
  18979. async listenerCount(event) {
  18980. if (event) {
  18981. const sub = await this.#hasSub(event);
  18982. if (!sub) {
  18983. return 0;
  18984. }
  18985. return sub.listeners.length;
  18986. }
  18987. let total = 0;
  18988. for (const { listeners } of this.#subs.values()) {
  18989. total += listeners.length;
  18990. }
  18991. return total;
  18992. }
  18993. async listeners(event) {
  18994. if (event) {
  18995. const sub = await this.#hasSub(event);
  18996. if (!sub) {
  18997. return [];
  18998. }
  18999. return sub.listeners.map(({ listener }) => listener);
  19000. }
  19001. let result = [];
  19002. for (const { listeners } of this.#subs.values()) {
  19003. result = result.concat(listeners.map(({ listener }) => listener));
  19004. }
  19005. return result;
  19006. }
  19007. async off(event, listener) {
  19008. const sub = await this.#hasSub(event);
  19009. if (!sub) {
  19010. return this;
  19011. }
  19012. if (listener) {
  19013. const index = sub.listeners.map(({ listener }) => listener).indexOf(listener);
  19014. if (index >= 0) {
  19015. sub.listeners.splice(index, 1);
  19016. }
  19017. }
  19018. if (!listener || sub.listeners.length === 0) {
  19019. if (sub.started) {
  19020. sub.subscriber.stop();
  19021. }
  19022. this.#subs.delete(sub.tag);
  19023. }
  19024. return this;
  19025. }
  19026. async removeAllListeners(event) {
  19027. if (event) {
  19028. const { tag, started, subscriber } = await this.#getSub(event);
  19029. if (started) {
  19030. subscriber.stop();
  19031. }
  19032. this.#subs.delete(tag);
  19033. }
  19034. else {
  19035. for (const [tag, { started, subscriber }] of this.#subs) {
  19036. if (started) {
  19037. subscriber.stop();
  19038. }
  19039. this.#subs.delete(tag);
  19040. }
  19041. }
  19042. return this;
  19043. }
  19044. // Alias for "on"
  19045. async addListener(event, listener) {
  19046. return await this.on(event, listener);
  19047. }
  19048. // Alias for "off"
  19049. async removeListener(event, listener) {
  19050. return this.off(event, listener);
  19051. }
  19052. /**
  19053. * If this provider has been destroyed using the [[destroy]] method.
  19054. *
  19055. * Once destroyed, all resources are reclaimed, internal event loops
  19056. * and timers are cleaned up and no further requests may be sent to
  19057. * the provider.
  19058. */
  19059. get destroyed() {
  19060. return this.#destroyed;
  19061. }
  19062. /**
  19063. * Sub-classes may use this to shutdown any sockets or release their
  19064. * resources and reject any pending requests.
  19065. *
  19066. * Sub-classes **must** call ``super.destroy()``.
  19067. */
  19068. destroy() {
  19069. // Stop all listeners
  19070. this.removeAllListeners();
  19071. // Shut down all tiemrs
  19072. for (const timerId of this.#timers.keys()) {
  19073. this._clearTimeout(timerId);
  19074. }
  19075. this.#destroyed = true;
  19076. }
  19077. /**
  19078. * Whether the provider is currently paused.
  19079. *
  19080. * A paused provider will not emit any events, and generally should
  19081. * not make any requests to the network, but that is up to sub-classes
  19082. * to manage.
  19083. *
  19084. * Setting ``paused = true`` is identical to calling ``.pause(false)``,
  19085. * which will buffer any events that occur while paused until the
  19086. * provider is unpaused.
  19087. */
  19088. get paused() { return (this.#pausedState != null); }
  19089. set paused(pause) {
  19090. if (!!pause === this.paused) {
  19091. return;
  19092. }
  19093. if (this.paused) {
  19094. this.resume();
  19095. }
  19096. else {
  19097. this.pause(false);
  19098. }
  19099. }
  19100. /**
  19101. * Pause the provider. If %%dropWhilePaused%%, any events that occur
  19102. * while paused are dropped, otherwise all events will be emitted once
  19103. * the provider is unpaused.
  19104. */
  19105. pause(dropWhilePaused) {
  19106. this.#lastBlockNumber = -1;
  19107. if (this.#pausedState != null) {
  19108. if (this.#pausedState == !!dropWhilePaused) {
  19109. return;
  19110. }
  19111. assert(false, "cannot change pause type; resume first", "UNSUPPORTED_OPERATION", {
  19112. operation: "pause"
  19113. });
  19114. }
  19115. this._forEachSubscriber((s) => s.pause(dropWhilePaused));
  19116. this.#pausedState = !!dropWhilePaused;
  19117. for (const timer of this.#timers.values()) {
  19118. // Clear the timer
  19119. if (timer.timer) {
  19120. clearTimeout(timer.timer);
  19121. }
  19122. // Remaining time needed for when we become unpaused
  19123. timer.time = getTime$1() - timer.time;
  19124. }
  19125. }
  19126. /**
  19127. * Resume the provider.
  19128. */
  19129. resume() {
  19130. if (this.#pausedState == null) {
  19131. return;
  19132. }
  19133. this._forEachSubscriber((s) => s.resume());
  19134. this.#pausedState = null;
  19135. for (const timer of this.#timers.values()) {
  19136. // Remaining time when we were paused
  19137. let timeout = timer.time;
  19138. if (timeout < 0) {
  19139. timeout = 0;
  19140. }
  19141. // Start time (in cause paused, so we con compute remaininf time)
  19142. timer.time = getTime$1();
  19143. // Start the timer
  19144. setTimeout(timer.func, timeout);
  19145. }
  19146. }
  19147. }
  19148. function _parseString(result, start) {
  19149. try {
  19150. const bytes = _parseBytes(result, start);
  19151. if (bytes) {
  19152. return toUtf8String(bytes);
  19153. }
  19154. }
  19155. catch (error) { }
  19156. return null;
  19157. }
  19158. function _parseBytes(result, start) {
  19159. if (result === "0x") {
  19160. return null;
  19161. }
  19162. try {
  19163. const offset = getNumber(dataSlice(result, start, start + 32));
  19164. const length = getNumber(dataSlice(result, offset, offset + 32));
  19165. return dataSlice(result, offset + 32, offset + 32 + length);
  19166. }
  19167. catch (error) { }
  19168. return null;
  19169. }
  19170. function numPad(value) {
  19171. const result = toBeArray(value);
  19172. if (result.length > 32) {
  19173. throw new Error("internal; should not happen");
  19174. }
  19175. const padded = new Uint8Array(32);
  19176. padded.set(result, 32 - result.length);
  19177. return padded;
  19178. }
  19179. function bytesPad(value) {
  19180. if ((value.length % 32) === 0) {
  19181. return value;
  19182. }
  19183. const result = new Uint8Array(Math.ceil(value.length / 32) * 32);
  19184. result.set(value);
  19185. return result;
  19186. }
  19187. const empty = new Uint8Array([]);
  19188. // ABI Encodes a series of (bytes, bytes, ...)
  19189. function encodeBytes(datas) {
  19190. const result = [];
  19191. let byteCount = 0;
  19192. // Add place-holders for pointers as we add items
  19193. for (let i = 0; i < datas.length; i++) {
  19194. result.push(empty);
  19195. byteCount += 32;
  19196. }
  19197. for (let i = 0; i < datas.length; i++) {
  19198. const data = getBytes(datas[i]);
  19199. // Update the bytes offset
  19200. result[i] = numPad(byteCount);
  19201. // The length and padded value of data
  19202. result.push(numPad(data.length));
  19203. result.push(bytesPad(data));
  19204. byteCount += 32 + Math.ceil(data.length / 32) * 32;
  19205. }
  19206. return concat(result);
  19207. }
  19208. const zeros = "0x0000000000000000000000000000000000000000000000000000000000000000";
  19209. function parseOffchainLookup(data) {
  19210. const result = {
  19211. sender: "", urls: [], calldata: "", selector: "", extraData: "", errorArgs: []
  19212. };
  19213. assert(dataLength(data) >= 5 * 32, "insufficient OffchainLookup data", "OFFCHAIN_FAULT", {
  19214. reason: "insufficient OffchainLookup data"
  19215. });
  19216. const sender = dataSlice(data, 0, 32);
  19217. assert(dataSlice(sender, 0, 12) === dataSlice(zeros, 0, 12), "corrupt OffchainLookup sender", "OFFCHAIN_FAULT", {
  19218. reason: "corrupt OffchainLookup sender"
  19219. });
  19220. result.sender = dataSlice(sender, 12);
  19221. // Read the URLs from the response
  19222. try {
  19223. const urls = [];
  19224. const urlsOffset = getNumber(dataSlice(data, 32, 64));
  19225. const urlsLength = getNumber(dataSlice(data, urlsOffset, urlsOffset + 32));
  19226. const urlsData = dataSlice(data, urlsOffset + 32);
  19227. for (let u = 0; u < urlsLength; u++) {
  19228. const url = _parseString(urlsData, u * 32);
  19229. if (url == null) {
  19230. throw new Error("abort");
  19231. }
  19232. urls.push(url);
  19233. }
  19234. result.urls = urls;
  19235. }
  19236. catch (error) {
  19237. assert(false, "corrupt OffchainLookup urls", "OFFCHAIN_FAULT", {
  19238. reason: "corrupt OffchainLookup urls"
  19239. });
  19240. }
  19241. // Get the CCIP calldata to forward
  19242. try {
  19243. const calldata = _parseBytes(data, 64);
  19244. if (calldata == null) {
  19245. throw new Error("abort");
  19246. }
  19247. result.calldata = calldata;
  19248. }
  19249. catch (error) {
  19250. assert(false, "corrupt OffchainLookup calldata", "OFFCHAIN_FAULT", {
  19251. reason: "corrupt OffchainLookup calldata"
  19252. });
  19253. }
  19254. // Get the callbackSelector (bytes4)
  19255. assert(dataSlice(data, 100, 128) === dataSlice(zeros, 0, 28), "corrupt OffchainLookup callbaackSelector", "OFFCHAIN_FAULT", {
  19256. reason: "corrupt OffchainLookup callbaackSelector"
  19257. });
  19258. result.selector = dataSlice(data, 96, 100);
  19259. // Get the extra data to send back to the contract as context
  19260. try {
  19261. const extraData = _parseBytes(data, 128);
  19262. if (extraData == null) {
  19263. throw new Error("abort");
  19264. }
  19265. result.extraData = extraData;
  19266. }
  19267. catch (error) {
  19268. assert(false, "corrupt OffchainLookup extraData", "OFFCHAIN_FAULT", {
  19269. reason: "corrupt OffchainLookup extraData"
  19270. });
  19271. }
  19272. result.errorArgs = "sender,urls,calldata,selector,extraData".split(/,/).map((k) => result[k]);
  19273. return result;
  19274. }
  19275. /**
  19276. * Generally the [[Wallet]] and [[JsonRpcSigner]] and their sub-classes
  19277. * are sufficent for most developers, but this is provided to
  19278. * fascilitate more complex Signers.
  19279. *
  19280. * @_section: api/providers/abstract-signer: Subclassing Signer [abstract-signer]
  19281. */
  19282. function checkProvider(signer, operation) {
  19283. if (signer.provider) {
  19284. return signer.provider;
  19285. }
  19286. assert(false, "missing provider", "UNSUPPORTED_OPERATION", { operation });
  19287. }
  19288. async function populate(signer, tx) {
  19289. let pop = copyRequest(tx);
  19290. if (pop.to != null) {
  19291. pop.to = resolveAddress(pop.to, signer);
  19292. }
  19293. if (pop.from != null) {
  19294. const from = pop.from;
  19295. pop.from = Promise.all([
  19296. signer.getAddress(),
  19297. resolveAddress(from, signer)
  19298. ]).then(([address, from]) => {
  19299. assertArgument(address.toLowerCase() === from.toLowerCase(), "transaction from mismatch", "tx.from", from);
  19300. return address;
  19301. });
  19302. }
  19303. else {
  19304. pop.from = signer.getAddress();
  19305. }
  19306. return await resolveProperties(pop);
  19307. }
  19308. /**
  19309. * An **AbstractSigner** includes most of teh functionality required
  19310. * to get a [[Signer]] working as expected, but requires a few
  19311. * Signer-specific methods be overridden.
  19312. *
  19313. */
  19314. class AbstractSigner {
  19315. /**
  19316. * The provider this signer is connected to.
  19317. */
  19318. provider;
  19319. /**
  19320. * Creates a new Signer connected to %%provider%%.
  19321. */
  19322. constructor(provider) {
  19323. defineProperties(this, { provider: (provider || null) });
  19324. }
  19325. async getNonce(blockTag) {
  19326. return checkProvider(this, "getTransactionCount").getTransactionCount(await this.getAddress(), blockTag);
  19327. }
  19328. async populateCall(tx) {
  19329. const pop = await populate(this, tx);
  19330. return pop;
  19331. }
  19332. async populateTransaction(tx) {
  19333. const provider = checkProvider(this, "populateTransaction");
  19334. const pop = await populate(this, tx);
  19335. if (pop.nonce == null) {
  19336. pop.nonce = await this.getNonce("pending");
  19337. }
  19338. if (pop.gasLimit == null) {
  19339. pop.gasLimit = await this.estimateGas(pop);
  19340. }
  19341. // Populate the chain ID
  19342. const network = await (this.provider).getNetwork();
  19343. if (pop.chainId != null) {
  19344. const chainId = getBigInt(pop.chainId);
  19345. assertArgument(chainId === network.chainId, "transaction chainId mismatch", "tx.chainId", tx.chainId);
  19346. }
  19347. else {
  19348. pop.chainId = network.chainId;
  19349. }
  19350. // Do not allow mixing pre-eip-1559 and eip-1559 properties
  19351. const hasEip1559 = (pop.maxFeePerGas != null || pop.maxPriorityFeePerGas != null);
  19352. if (pop.gasPrice != null && (pop.type === 2 || hasEip1559)) {
  19353. assertArgument(false, "eip-1559 transaction do not support gasPrice", "tx", tx);
  19354. }
  19355. else if ((pop.type === 0 || pop.type === 1) && hasEip1559) {
  19356. assertArgument(false, "pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas", "tx", tx);
  19357. }
  19358. if ((pop.type === 2 || pop.type == null) && (pop.maxFeePerGas != null && pop.maxPriorityFeePerGas != null)) {
  19359. // Fully-formed EIP-1559 transaction (skip getFeeData)
  19360. pop.type = 2;
  19361. }
  19362. else if (pop.type === 0 || pop.type === 1) {
  19363. // Explicit Legacy or EIP-2930 transaction
  19364. // We need to get fee data to determine things
  19365. const feeData = await provider.getFeeData();
  19366. assert(feeData.gasPrice != null, "network does not support gasPrice", "UNSUPPORTED_OPERATION", {
  19367. operation: "getGasPrice"
  19368. });
  19369. // Populate missing gasPrice
  19370. if (pop.gasPrice == null) {
  19371. pop.gasPrice = feeData.gasPrice;
  19372. }
  19373. }
  19374. else {
  19375. // We need to get fee data to determine things
  19376. const feeData = await provider.getFeeData();
  19377. if (pop.type == null) {
  19378. // We need to auto-detect the intended type of this transaction...
  19379. if (feeData.maxFeePerGas != null && feeData.maxPriorityFeePerGas != null) {
  19380. // The network supports EIP-1559!
  19381. // Upgrade transaction from null to eip-1559
  19382. pop.type = 2;
  19383. if (pop.gasPrice != null) {
  19384. // Using legacy gasPrice property on an eip-1559 network,
  19385. // so use gasPrice as both fee properties
  19386. const gasPrice = pop.gasPrice;
  19387. delete pop.gasPrice;
  19388. pop.maxFeePerGas = gasPrice;
  19389. pop.maxPriorityFeePerGas = gasPrice;
  19390. }
  19391. else {
  19392. // Populate missing fee data
  19393. if (pop.maxFeePerGas == null) {
  19394. pop.maxFeePerGas = feeData.maxFeePerGas;
  19395. }
  19396. if (pop.maxPriorityFeePerGas == null) {
  19397. pop.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas;
  19398. }
  19399. }
  19400. }
  19401. else if (feeData.gasPrice != null) {
  19402. // Network doesn't support EIP-1559...
  19403. // ...but they are trying to use EIP-1559 properties
  19404. assert(!hasEip1559, "network does not support EIP-1559", "UNSUPPORTED_OPERATION", {
  19405. operation: "populateTransaction"
  19406. });
  19407. // Populate missing fee data
  19408. if (pop.gasPrice == null) {
  19409. pop.gasPrice = feeData.gasPrice;
  19410. }
  19411. // Explicitly set untyped transaction to legacy
  19412. // @TODO: Maybe this shold allow type 1?
  19413. pop.type = 0;
  19414. }
  19415. else {
  19416. // getFeeData has failed us.
  19417. assert(false, "failed to get consistent fee data", "UNSUPPORTED_OPERATION", {
  19418. operation: "signer.getFeeData"
  19419. });
  19420. }
  19421. }
  19422. else if (pop.type === 2 || pop.type === 3) {
  19423. // Explicitly using EIP-1559 or EIP-4844
  19424. // Populate missing fee data
  19425. if (pop.maxFeePerGas == null) {
  19426. pop.maxFeePerGas = feeData.maxFeePerGas;
  19427. }
  19428. if (pop.maxPriorityFeePerGas == null) {
  19429. pop.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas;
  19430. }
  19431. }
  19432. }
  19433. //@TOOD: Don't await all over the place; save them up for
  19434. // the end for better batching
  19435. return await resolveProperties(pop);
  19436. }
  19437. async estimateGas(tx) {
  19438. return checkProvider(this, "estimateGas").estimateGas(await this.populateCall(tx));
  19439. }
  19440. async call(tx) {
  19441. return checkProvider(this, "call").call(await this.populateCall(tx));
  19442. }
  19443. async resolveName(name) {
  19444. const provider = checkProvider(this, "resolveName");
  19445. return await provider.resolveName(name);
  19446. }
  19447. async sendTransaction(tx) {
  19448. const provider = checkProvider(this, "sendTransaction");
  19449. const pop = await this.populateTransaction(tx);
  19450. delete pop.from;
  19451. const txObj = Transaction.from(pop);
  19452. return await provider.broadcastTransaction(await this.signTransaction(txObj));
  19453. }
  19454. }
  19455. /**
  19456. * A **VoidSigner** is a class deisgned to allow an address to be used
  19457. * in any API which accepts a Signer, but for which there are no
  19458. * credentials available to perform any actual signing.
  19459. *
  19460. * This for example allow impersonating an account for the purpose of
  19461. * static calls or estimating gas, but does not allow sending transactions.
  19462. */
  19463. class VoidSigner extends AbstractSigner {
  19464. /**
  19465. * The signer address.
  19466. */
  19467. address;
  19468. /**
  19469. * Creates a new **VoidSigner** with %%address%% attached to
  19470. * %%provider%%.
  19471. */
  19472. constructor(address, provider) {
  19473. super(provider);
  19474. defineProperties(this, { address });
  19475. }
  19476. async getAddress() { return this.address; }
  19477. connect(provider) {
  19478. return new VoidSigner(this.address, provider);
  19479. }
  19480. #throwUnsupported(suffix, operation) {
  19481. assert(false, `VoidSigner cannot sign ${suffix}`, "UNSUPPORTED_OPERATION", { operation });
  19482. }
  19483. async signTransaction(tx) {
  19484. this.#throwUnsupported("transactions", "signTransaction");
  19485. }
  19486. async signMessage(message) {
  19487. this.#throwUnsupported("messages", "signMessage");
  19488. }
  19489. async signTypedData(domain, types, value) {
  19490. this.#throwUnsupported("typed-data", "signTypedData");
  19491. }
  19492. }
  19493. /**
  19494. * There are many awesome community services that provide Ethereum
  19495. * nodes both for developers just starting out and for large-scale
  19496. * communities.
  19497. *
  19498. * @_section: api/providers/thirdparty: Community Providers [thirdparty]
  19499. */
  19500. // Show the throttle message only once per service
  19501. const shown = new Set();
  19502. /**
  19503. * Displays a warning in tht console when the community resource is
  19504. * being used too heavily by the app, recommending the developer
  19505. * acquire their own credentials instead of using the community
  19506. * credentials.
  19507. *
  19508. * The notification will only occur once per service.
  19509. */
  19510. function showThrottleMessage(service) {
  19511. if (shown.has(service)) {
  19512. return;
  19513. }
  19514. shown.add(service);
  19515. console.log("========= NOTICE =========");
  19516. console.log(`Request-Rate Exceeded for ${service} (this message will not be repeated)`);
  19517. console.log("");
  19518. console.log("The default API keys for each service are provided as a highly-throttled,");
  19519. console.log("community resource for low-traffic projects and early prototyping.");
  19520. console.log("");
  19521. console.log("While your application will continue to function, we highly recommended");
  19522. console.log("signing up for your own API keys to improve performance, increase your");
  19523. console.log("request rate/limit and enable other perks, such as metrics and advanced APIs.");
  19524. console.log("");
  19525. console.log("For more details: https:/\/docs.ethers.org/api-keys/");
  19526. console.log("==========================");
  19527. }
  19528. function copy(obj) {
  19529. return JSON.parse(JSON.stringify(obj));
  19530. }
  19531. /**
  19532. * Some backends support subscribing to events using a Filter ID.
  19533. *
  19534. * When subscribing with this technique, the node issues a unique
  19535. * //Filter ID//. At this point the node dedicates resources to
  19536. * the filter, so that periodic calls to follow up on the //Filter ID//
  19537. * will receive any events since the last call.
  19538. *
  19539. * @_docloc: api/providers/abstract-provider
  19540. */
  19541. class FilterIdSubscriber {
  19542. #provider;
  19543. #filterIdPromise;
  19544. #poller;
  19545. #running;
  19546. #network;
  19547. #hault;
  19548. /**
  19549. * Creates a new **FilterIdSubscriber** which will used [[_subscribe]]
  19550. * and [[_emitResults]] to setup the subscription and provide the event
  19551. * to the %%provider%%.
  19552. */
  19553. constructor(provider) {
  19554. this.#provider = provider;
  19555. this.#filterIdPromise = null;
  19556. this.#poller = this.#poll.bind(this);
  19557. this.#running = false;
  19558. this.#network = null;
  19559. this.#hault = false;
  19560. }
  19561. /**
  19562. * Sub-classes **must** override this to begin the subscription.
  19563. */
  19564. _subscribe(provider) {
  19565. throw new Error("subclasses must override this");
  19566. }
  19567. /**
  19568. * Sub-classes **must** override this handle the events.
  19569. */
  19570. _emitResults(provider, result) {
  19571. throw new Error("subclasses must override this");
  19572. }
  19573. /**
  19574. * Sub-classes **must** override this handle recovery on errors.
  19575. */
  19576. _recover(provider) {
  19577. throw new Error("subclasses must override this");
  19578. }
  19579. async #poll(blockNumber) {
  19580. try {
  19581. // Subscribe if necessary
  19582. if (this.#filterIdPromise == null) {
  19583. this.#filterIdPromise = this._subscribe(this.#provider);
  19584. }
  19585. // Get the Filter ID
  19586. let filterId = null;
  19587. try {
  19588. filterId = await this.#filterIdPromise;
  19589. }
  19590. catch (error) {
  19591. if (!isError(error, "UNSUPPORTED_OPERATION") || error.operation !== "eth_newFilter") {
  19592. throw error;
  19593. }
  19594. }
  19595. // The backend does not support Filter ID; downgrade to
  19596. // polling
  19597. if (filterId == null) {
  19598. this.#filterIdPromise = null;
  19599. this.#provider._recoverSubscriber(this, this._recover(this.#provider));
  19600. return;
  19601. }
  19602. const network = await this.#provider.getNetwork();
  19603. if (!this.#network) {
  19604. this.#network = network;
  19605. }
  19606. if (this.#network.chainId !== network.chainId) {
  19607. throw new Error("chaid changed");
  19608. }
  19609. if (this.#hault) {
  19610. return;
  19611. }
  19612. const result = await this.#provider.send("eth_getFilterChanges", [filterId]);
  19613. await this._emitResults(this.#provider, result);
  19614. }
  19615. catch (error) {
  19616. console.log("@TODO", error);
  19617. }
  19618. this.#provider.once("block", this.#poller);
  19619. }
  19620. #teardown() {
  19621. const filterIdPromise = this.#filterIdPromise;
  19622. if (filterIdPromise) {
  19623. this.#filterIdPromise = null;
  19624. filterIdPromise.then((filterId) => {
  19625. if (this.#provider.destroyed) {
  19626. return;
  19627. }
  19628. this.#provider.send("eth_uninstallFilter", [filterId]);
  19629. });
  19630. }
  19631. }
  19632. start() {
  19633. if (this.#running) {
  19634. return;
  19635. }
  19636. this.#running = true;
  19637. this.#poll(-2);
  19638. }
  19639. stop() {
  19640. if (!this.#running) {
  19641. return;
  19642. }
  19643. this.#running = false;
  19644. this.#hault = true;
  19645. this.#teardown();
  19646. this.#provider.off("block", this.#poller);
  19647. }
  19648. pause(dropWhilePaused) {
  19649. if (dropWhilePaused) {
  19650. this.#teardown();
  19651. }
  19652. this.#provider.off("block", this.#poller);
  19653. }
  19654. resume() { this.start(); }
  19655. }
  19656. /**
  19657. * A **FilterIdSubscriber** for receiving contract events.
  19658. *
  19659. * @_docloc: api/providers/abstract-provider
  19660. */
  19661. class FilterIdEventSubscriber extends FilterIdSubscriber {
  19662. #event;
  19663. /**
  19664. * Creates a new **FilterIdEventSubscriber** attached to %%provider%%
  19665. * listening for %%filter%%.
  19666. */
  19667. constructor(provider, filter) {
  19668. super(provider);
  19669. this.#event = copy(filter);
  19670. }
  19671. _recover(provider) {
  19672. return new PollingEventSubscriber(provider, this.#event);
  19673. }
  19674. async _subscribe(provider) {
  19675. const filterId = await provider.send("eth_newFilter", [this.#event]);
  19676. return filterId;
  19677. }
  19678. async _emitResults(provider, results) {
  19679. for (const result of results) {
  19680. provider.emit(this.#event, provider._wrapLog(result, provider._network));
  19681. }
  19682. }
  19683. }
  19684. /**
  19685. * A **FilterIdSubscriber** for receiving pending transactions events.
  19686. *
  19687. * @_docloc: api/providers/abstract-provider
  19688. */
  19689. class FilterIdPendingSubscriber extends FilterIdSubscriber {
  19690. async _subscribe(provider) {
  19691. return await provider.send("eth_newPendingTransactionFilter", []);
  19692. }
  19693. async _emitResults(provider, results) {
  19694. for (const result of results) {
  19695. provider.emit("pending", result);
  19696. }
  19697. }
  19698. }
  19699. /**
  19700. * One of the most common ways to interact with the blockchain is
  19701. * by a node running a JSON-RPC interface which can be connected to,
  19702. * based on the transport, using:
  19703. *
  19704. * - HTTP or HTTPS - [[JsonRpcProvider]]
  19705. * - WebSocket - [[WebSocketProvider]]
  19706. * - IPC - [[IpcSocketProvider]]
  19707. *
  19708. * @_section: api/providers/jsonrpc:JSON-RPC Provider [about-jsonrpcProvider]
  19709. */
  19710. // @TODO:
  19711. // - Add the batching API
  19712. // 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
  19713. const Primitive = "bigint,boolean,function,number,string,symbol".split(/,/g);
  19714. //const Methods = "getAddress,then".split(/,/g);
  19715. function deepCopy(value) {
  19716. if (value == null || Primitive.indexOf(typeof (value)) >= 0) {
  19717. return value;
  19718. }
  19719. // Keep any Addressable
  19720. if (typeof (value.getAddress) === "function") {
  19721. return value;
  19722. }
  19723. if (Array.isArray(value)) {
  19724. return (value.map(deepCopy));
  19725. }
  19726. if (typeof (value) === "object") {
  19727. return Object.keys(value).reduce((accum, key) => {
  19728. accum[key] = value[key];
  19729. return accum;
  19730. }, {});
  19731. }
  19732. throw new Error(`should not happen: ${value} (${typeof (value)})`);
  19733. }
  19734. function stall$3(duration) {
  19735. return new Promise((resolve) => { setTimeout(resolve, duration); });
  19736. }
  19737. function getLowerCase(value) {
  19738. if (value) {
  19739. return value.toLowerCase();
  19740. }
  19741. return value;
  19742. }
  19743. function isPollable(value) {
  19744. return (value && typeof (value.pollingInterval) === "number");
  19745. }
  19746. const defaultOptions = {
  19747. polling: false,
  19748. staticNetwork: null,
  19749. batchStallTime: 10,
  19750. batchMaxSize: (1 << 20),
  19751. batchMaxCount: 100,
  19752. cacheTimeout: 250,
  19753. pollingInterval: 4000
  19754. };
  19755. // @TODO: Unchecked Signers
  19756. class JsonRpcSigner extends AbstractSigner {
  19757. address;
  19758. constructor(provider, address) {
  19759. super(provider);
  19760. address = getAddress(address);
  19761. defineProperties(this, { address });
  19762. }
  19763. connect(provider) {
  19764. assert(false, "cannot reconnect JsonRpcSigner", "UNSUPPORTED_OPERATION", {
  19765. operation: "signer.connect"
  19766. });
  19767. }
  19768. async getAddress() {
  19769. return this.address;
  19770. }
  19771. // JSON-RPC will automatially fill in nonce, etc. so we just check from
  19772. async populateTransaction(tx) {
  19773. return await this.populateCall(tx);
  19774. }
  19775. // Returns just the hash of the transaction after sent, which is what
  19776. // the bare JSON-RPC API does;
  19777. async sendUncheckedTransaction(_tx) {
  19778. const tx = deepCopy(_tx);
  19779. const promises = [];
  19780. // Make sure the from matches the sender
  19781. if (tx.from) {
  19782. const _from = tx.from;
  19783. promises.push((async () => {
  19784. const from = await resolveAddress(_from, this.provider);
  19785. assertArgument(from != null && from.toLowerCase() === this.address.toLowerCase(), "from address mismatch", "transaction", _tx);
  19786. tx.from = from;
  19787. })());
  19788. }
  19789. else {
  19790. tx.from = this.address;
  19791. }
  19792. // The JSON-RPC for eth_sendTransaction uses 90000 gas; if the user
  19793. // wishes to use this, it is easy to specify explicitly, otherwise
  19794. // we look it up for them.
  19795. if (tx.gasLimit == null) {
  19796. promises.push((async () => {
  19797. tx.gasLimit = await this.provider.estimateGas({ ...tx, from: this.address });
  19798. })());
  19799. }
  19800. // The address may be an ENS name or Addressable
  19801. if (tx.to != null) {
  19802. const _to = tx.to;
  19803. promises.push((async () => {
  19804. tx.to = await resolveAddress(_to, this.provider);
  19805. })());
  19806. }
  19807. // Wait until all of our properties are filled in
  19808. if (promises.length) {
  19809. await Promise.all(promises);
  19810. }
  19811. const hexTx = this.provider.getRpcTransaction(tx);
  19812. return this.provider.send("eth_sendTransaction", [hexTx]);
  19813. }
  19814. async sendTransaction(tx) {
  19815. // This cannot be mined any earlier than any recent block
  19816. const blockNumber = await this.provider.getBlockNumber();
  19817. // Send the transaction
  19818. const hash = await this.sendUncheckedTransaction(tx);
  19819. // Unfortunately, JSON-RPC only provides and opaque transaction hash
  19820. // for a response, and we need the actual transaction, so we poll
  19821. // for it; it should show up very quickly
  19822. return await (new Promise((resolve, reject) => {
  19823. const timeouts = [1000, 100];
  19824. let invalids = 0;
  19825. const checkTx = async () => {
  19826. try {
  19827. // Try getting the transaction
  19828. const tx = await this.provider.getTransaction(hash);
  19829. if (tx != null) {
  19830. resolve(tx.replaceableTransaction(blockNumber));
  19831. return;
  19832. }
  19833. }
  19834. catch (error) {
  19835. // If we were cancelled: stop polling.
  19836. // If the data is bad: the node returns bad transactions
  19837. // If the network changed: calling again will also fail
  19838. // If unsupported: likely destroyed
  19839. if (isError(error, "CANCELLED") || isError(error, "BAD_DATA") ||
  19840. isError(error, "NETWORK_ERROR") || isError(error, "UNSUPPORTED_OPERATION")) {
  19841. if (error.info == null) {
  19842. error.info = {};
  19843. }
  19844. error.info.sendTransactionHash = hash;
  19845. reject(error);
  19846. return;
  19847. }
  19848. // Stop-gap for misbehaving backends; see #4513
  19849. if (isError(error, "INVALID_ARGUMENT")) {
  19850. invalids++;
  19851. if (error.info == null) {
  19852. error.info = {};
  19853. }
  19854. error.info.sendTransactionHash = hash;
  19855. if (invalids > 10) {
  19856. reject(error);
  19857. return;
  19858. }
  19859. }
  19860. // Notify anyone that cares; but we will try again, since
  19861. // it is likely an intermittent service error
  19862. this.provider.emit("error", makeError("failed to fetch transation after sending (will try again)", "UNKNOWN_ERROR", { error }));
  19863. }
  19864. // Wait another 4 seconds
  19865. this.provider._setTimeout(() => { checkTx(); }, timeouts.pop() || 4000);
  19866. };
  19867. checkTx();
  19868. }));
  19869. }
  19870. async signTransaction(_tx) {
  19871. const tx = deepCopy(_tx);
  19872. // Make sure the from matches the sender
  19873. if (tx.from) {
  19874. const from = await resolveAddress(tx.from, this.provider);
  19875. assertArgument(from != null && from.toLowerCase() === this.address.toLowerCase(), "from address mismatch", "transaction", _tx);
  19876. tx.from = from;
  19877. }
  19878. else {
  19879. tx.from = this.address;
  19880. }
  19881. const hexTx = this.provider.getRpcTransaction(tx);
  19882. return await this.provider.send("eth_signTransaction", [hexTx]);
  19883. }
  19884. async signMessage(_message) {
  19885. const message = ((typeof (_message) === "string") ? toUtf8Bytes(_message) : _message);
  19886. return await this.provider.send("personal_sign", [
  19887. hexlify(message), this.address.toLowerCase()
  19888. ]);
  19889. }
  19890. async signTypedData(domain, types, _value) {
  19891. const value = deepCopy(_value);
  19892. // Populate any ENS names (in-place)
  19893. const populated = await TypedDataEncoder.resolveNames(domain, types, value, async (value) => {
  19894. const address = await resolveAddress(value);
  19895. assertArgument(address != null, "TypedData does not support null address", "value", value);
  19896. return address;
  19897. });
  19898. return await this.provider.send("eth_signTypedData_v4", [
  19899. this.address.toLowerCase(),
  19900. JSON.stringify(TypedDataEncoder.getPayload(populated.domain, types, populated.value))
  19901. ]);
  19902. }
  19903. async unlock(password) {
  19904. return this.provider.send("personal_unlockAccount", [
  19905. this.address.toLowerCase(), password, null
  19906. ]);
  19907. }
  19908. // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
  19909. async _legacySignMessage(_message) {
  19910. const message = ((typeof (_message) === "string") ? toUtf8Bytes(_message) : _message);
  19911. return await this.provider.send("eth_sign", [
  19912. this.address.toLowerCase(), hexlify(message)
  19913. ]);
  19914. }
  19915. }
  19916. /**
  19917. * The JsonRpcApiProvider is an abstract class and **MUST** be
  19918. * sub-classed.
  19919. *
  19920. * It provides the base for all JSON-RPC-based Provider interaction.
  19921. *
  19922. * Sub-classing Notes:
  19923. * - a sub-class MUST override _send
  19924. * - a sub-class MUST call the `_start()` method once connected
  19925. */
  19926. class JsonRpcApiProvider extends AbstractProvider {
  19927. #options;
  19928. // The next ID to use for the JSON-RPC ID field
  19929. #nextId;
  19930. // Payloads are queued and triggered in batches using the drainTimer
  19931. #payloads;
  19932. #drainTimer;
  19933. #notReady;
  19934. #network;
  19935. #pendingDetectNetwork;
  19936. #scheduleDrain() {
  19937. if (this.#drainTimer) {
  19938. return;
  19939. }
  19940. // If we aren't using batching, no harm in sending it immediately
  19941. const stallTime = (this._getOption("batchMaxCount") === 1) ? 0 : this._getOption("batchStallTime");
  19942. this.#drainTimer = setTimeout(() => {
  19943. this.#drainTimer = null;
  19944. const payloads = this.#payloads;
  19945. this.#payloads = [];
  19946. while (payloads.length) {
  19947. // Create payload batches that satisfy our batch constraints
  19948. const batch = [(payloads.shift())];
  19949. while (payloads.length) {
  19950. if (batch.length === this.#options.batchMaxCount) {
  19951. break;
  19952. }
  19953. batch.push((payloads.shift()));
  19954. const bytes = JSON.stringify(batch.map((p) => p.payload));
  19955. if (bytes.length > this.#options.batchMaxSize) {
  19956. payloads.unshift((batch.pop()));
  19957. break;
  19958. }
  19959. }
  19960. // Process the result to each payload
  19961. (async () => {
  19962. const payload = ((batch.length === 1) ? batch[0].payload : batch.map((p) => p.payload));
  19963. this.emit("debug", { action: "sendRpcPayload", payload });
  19964. try {
  19965. const result = await this._send(payload);
  19966. this.emit("debug", { action: "receiveRpcResult", result });
  19967. // Process results in batch order
  19968. for (const { resolve, reject, payload } of batch) {
  19969. if (this.destroyed) {
  19970. reject(makeError("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: payload.method }));
  19971. continue;
  19972. }
  19973. // Find the matching result
  19974. const resp = result.filter((r) => (r.id === payload.id))[0];
  19975. // No result; the node failed us in unexpected ways
  19976. if (resp == null) {
  19977. const error = makeError("missing response for request", "BAD_DATA", {
  19978. value: result, info: { payload }
  19979. });
  19980. this.emit("error", error);
  19981. reject(error);
  19982. continue;
  19983. }
  19984. // The response is an error
  19985. if ("error" in resp) {
  19986. reject(this.getRpcError(payload, resp));
  19987. continue;
  19988. }
  19989. // All good; send the result
  19990. resolve(resp.result);
  19991. }
  19992. }
  19993. catch (error) {
  19994. this.emit("debug", { action: "receiveRpcError", error });
  19995. for (const { reject } of batch) {
  19996. // @TODO: augment the error with the payload
  19997. reject(error);
  19998. }
  19999. }
  20000. })();
  20001. }
  20002. }, stallTime);
  20003. }
  20004. constructor(network, options) {
  20005. super(network, options);
  20006. this.#nextId = 1;
  20007. this.#options = Object.assign({}, defaultOptions, options || {});
  20008. this.#payloads = [];
  20009. this.#drainTimer = null;
  20010. this.#network = null;
  20011. this.#pendingDetectNetwork = null;
  20012. {
  20013. let resolve = null;
  20014. const promise = new Promise((_resolve) => {
  20015. resolve = _resolve;
  20016. });
  20017. this.#notReady = { promise, resolve };
  20018. }
  20019. const staticNetwork = this._getOption("staticNetwork");
  20020. if (typeof (staticNetwork) === "boolean") {
  20021. assertArgument(!staticNetwork || network !== "any", "staticNetwork cannot be used on special network 'any'", "options", options);
  20022. if (staticNetwork && network != null) {
  20023. this.#network = Network.from(network);
  20024. }
  20025. }
  20026. else if (staticNetwork) {
  20027. // Make sure any static network is compatbile with the provided netwrok
  20028. assertArgument(network == null || staticNetwork.matches(network), "staticNetwork MUST match network object", "options", options);
  20029. this.#network = staticNetwork;
  20030. }
  20031. }
  20032. /**
  20033. * Returns the value associated with the option %%key%%.
  20034. *
  20035. * Sub-classes can use this to inquire about configuration options.
  20036. */
  20037. _getOption(key) {
  20038. return this.#options[key];
  20039. }
  20040. /**
  20041. * Gets the [[Network]] this provider has committed to. On each call, the network
  20042. * is detected, and if it has changed, the call will reject.
  20043. */
  20044. get _network() {
  20045. assert(this.#network, "network is not available yet", "NETWORK_ERROR");
  20046. return this.#network;
  20047. }
  20048. /**
  20049. * Resolves to the non-normalized value by performing %%req%%.
  20050. *
  20051. * Sub-classes may override this to modify behavior of actions,
  20052. * and should generally call ``super._perform`` as a fallback.
  20053. */
  20054. async _perform(req) {
  20055. // Legacy networks do not like the type field being passed along (which
  20056. // is fair), so we delete type if it is 0 and a non-EIP-1559 network
  20057. if (req.method === "call" || req.method === "estimateGas") {
  20058. let tx = req.transaction;
  20059. if (tx && tx.type != null && getBigInt(tx.type)) {
  20060. // If there are no EIP-1559 or newer properties, it might be pre-EIP-1559
  20061. if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) {
  20062. const feeData = await this.getFeeData();
  20063. if (feeData.maxFeePerGas == null && feeData.maxPriorityFeePerGas == null) {
  20064. // Network doesn't know about EIP-1559 (and hence type)
  20065. req = Object.assign({}, req, {
  20066. transaction: Object.assign({}, tx, { type: undefined })
  20067. });
  20068. }
  20069. }
  20070. }
  20071. }
  20072. const request = this.getRpcRequest(req);
  20073. if (request != null) {
  20074. return await this.send(request.method, request.args);
  20075. }
  20076. return super._perform(req);
  20077. }
  20078. /**
  20079. * Sub-classes may override this; it detects the *actual* network that
  20080. * we are **currently** connected to.
  20081. *
  20082. * Keep in mind that [[send]] may only be used once [[ready]], otherwise the
  20083. * _send primitive must be used instead.
  20084. */
  20085. async _detectNetwork() {
  20086. const network = this._getOption("staticNetwork");
  20087. if (network) {
  20088. if (network === true) {
  20089. if (this.#network) {
  20090. return this.#network;
  20091. }
  20092. }
  20093. else {
  20094. return network;
  20095. }
  20096. }
  20097. if (this.#pendingDetectNetwork) {
  20098. return await this.#pendingDetectNetwork;
  20099. }
  20100. // If we are ready, use ``send``, which enabled requests to be batched
  20101. if (this.ready) {
  20102. this.#pendingDetectNetwork = (async () => {
  20103. try {
  20104. const result = Network.from(getBigInt(await this.send("eth_chainId", [])));
  20105. this.#pendingDetectNetwork = null;
  20106. return result;
  20107. }
  20108. catch (error) {
  20109. this.#pendingDetectNetwork = null;
  20110. throw error;
  20111. }
  20112. })();
  20113. return await this.#pendingDetectNetwork;
  20114. }
  20115. // We are not ready yet; use the primitive _send
  20116. this.#pendingDetectNetwork = (async () => {
  20117. const payload = {
  20118. id: this.#nextId++, method: "eth_chainId", params: [], jsonrpc: "2.0"
  20119. };
  20120. this.emit("debug", { action: "sendRpcPayload", payload });
  20121. let result;
  20122. try {
  20123. result = (await this._send(payload))[0];
  20124. this.#pendingDetectNetwork = null;
  20125. }
  20126. catch (error) {
  20127. this.#pendingDetectNetwork = null;
  20128. this.emit("debug", { action: "receiveRpcError", error });
  20129. throw error;
  20130. }
  20131. this.emit("debug", { action: "receiveRpcResult", result });
  20132. if ("result" in result) {
  20133. return Network.from(getBigInt(result.result));
  20134. }
  20135. throw this.getRpcError(payload, result);
  20136. })();
  20137. return await this.#pendingDetectNetwork;
  20138. }
  20139. /**
  20140. * Sub-classes **MUST** call this. Until [[_start]] has been called, no calls
  20141. * will be passed to [[_send]] from [[send]]. If it is overridden, then
  20142. * ``super._start()`` **MUST** be called.
  20143. *
  20144. * Calling it multiple times is safe and has no effect.
  20145. */
  20146. _start() {
  20147. if (this.#notReady == null || this.#notReady.resolve == null) {
  20148. return;
  20149. }
  20150. this.#notReady.resolve();
  20151. this.#notReady = null;
  20152. (async () => {
  20153. // Bootstrap the network
  20154. while (this.#network == null && !this.destroyed) {
  20155. try {
  20156. this.#network = await this._detectNetwork();
  20157. }
  20158. catch (error) {
  20159. if (this.destroyed) {
  20160. break;
  20161. }
  20162. 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)");
  20163. this.emit("error", makeError("failed to bootstrap network detection", "NETWORK_ERROR", { event: "initial-network-discovery", info: { error } }));
  20164. await stall$3(1000);
  20165. }
  20166. }
  20167. // Start dispatching requests
  20168. this.#scheduleDrain();
  20169. })();
  20170. }
  20171. /**
  20172. * Resolves once the [[_start]] has been called. This can be used in
  20173. * sub-classes to defer sending data until the connection has been
  20174. * established.
  20175. */
  20176. async _waitUntilReady() {
  20177. if (this.#notReady == null) {
  20178. return;
  20179. }
  20180. return await this.#notReady.promise;
  20181. }
  20182. /**
  20183. * Return a Subscriber that will manage the %%sub%%.
  20184. *
  20185. * Sub-classes may override this to modify the behavior of
  20186. * subscription management.
  20187. */
  20188. _getSubscriber(sub) {
  20189. // Pending Filters aren't availble via polling
  20190. if (sub.type === "pending") {
  20191. return new FilterIdPendingSubscriber(this);
  20192. }
  20193. if (sub.type === "event") {
  20194. if (this._getOption("polling")) {
  20195. return new PollingEventSubscriber(this, sub.filter);
  20196. }
  20197. return new FilterIdEventSubscriber(this, sub.filter);
  20198. }
  20199. // Orphaned Logs are handled automatically, by the filter, since
  20200. // logs with removed are emitted by it
  20201. if (sub.type === "orphan" && sub.filter.orphan === "drop-log") {
  20202. return new UnmanagedSubscriber("orphan");
  20203. }
  20204. return super._getSubscriber(sub);
  20205. }
  20206. /**
  20207. * Returns true only if the [[_start]] has been called.
  20208. */
  20209. get ready() { return this.#notReady == null; }
  20210. /**
  20211. * Returns %%tx%% as a normalized JSON-RPC transaction request,
  20212. * which has all values hexlified and any numeric values converted
  20213. * to Quantity values.
  20214. */
  20215. getRpcTransaction(tx) {
  20216. const result = {};
  20217. // JSON-RPC now requires numeric values to be "quantity" values
  20218. ["chainId", "gasLimit", "gasPrice", "type", "maxFeePerGas", "maxPriorityFeePerGas", "nonce", "value"].forEach((key) => {
  20219. if (tx[key] == null) {
  20220. return;
  20221. }
  20222. let dstKey = key;
  20223. if (key === "gasLimit") {
  20224. dstKey = "gas";
  20225. }
  20226. result[dstKey] = toQuantity(getBigInt(tx[key], `tx.${key}`));
  20227. });
  20228. // Make sure addresses and data are lowercase
  20229. ["from", "to", "data"].forEach((key) => {
  20230. if (tx[key] == null) {
  20231. return;
  20232. }
  20233. result[key] = hexlify(tx[key]);
  20234. });
  20235. // Normalize the access list object
  20236. if (tx.accessList) {
  20237. result["accessList"] = accessListify(tx.accessList);
  20238. }
  20239. if (tx.blobVersionedHashes) {
  20240. // @TODO: Remove this <any> case once EIP-4844 added to prepared tx
  20241. result["blobVersionedHashes"] = tx.blobVersionedHashes.map(h => h.toLowerCase());
  20242. }
  20243. // @TODO: blobs should probably also be copied over, optionally
  20244. // accounting for the kzg property to backfill blobVersionedHashes
  20245. // using the commitment. Or should that be left as an exercise to
  20246. // the caller?
  20247. return result;
  20248. }
  20249. /**
  20250. * Returns the request method and arguments required to perform
  20251. * %%req%%.
  20252. */
  20253. getRpcRequest(req) {
  20254. switch (req.method) {
  20255. case "chainId":
  20256. return { method: "eth_chainId", args: [] };
  20257. case "getBlockNumber":
  20258. return { method: "eth_blockNumber", args: [] };
  20259. case "getGasPrice":
  20260. return { method: "eth_gasPrice", args: [] };
  20261. case "getPriorityFee":
  20262. return { method: "eth_maxPriorityFeePerGas", args: [] };
  20263. case "getBalance":
  20264. return {
  20265. method: "eth_getBalance",
  20266. args: [getLowerCase(req.address), req.blockTag]
  20267. };
  20268. case "getTransactionCount":
  20269. return {
  20270. method: "eth_getTransactionCount",
  20271. args: [getLowerCase(req.address), req.blockTag]
  20272. };
  20273. case "getCode":
  20274. return {
  20275. method: "eth_getCode",
  20276. args: [getLowerCase(req.address), req.blockTag]
  20277. };
  20278. case "getStorage":
  20279. return {
  20280. method: "eth_getStorageAt",
  20281. args: [
  20282. getLowerCase(req.address),
  20283. ("0x" + req.position.toString(16)),
  20284. req.blockTag
  20285. ]
  20286. };
  20287. case "broadcastTransaction":
  20288. return {
  20289. method: "eth_sendRawTransaction",
  20290. args: [req.signedTransaction]
  20291. };
  20292. case "getBlock":
  20293. if ("blockTag" in req) {
  20294. return {
  20295. method: "eth_getBlockByNumber",
  20296. args: [req.blockTag, !!req.includeTransactions]
  20297. };
  20298. }
  20299. else if ("blockHash" in req) {
  20300. return {
  20301. method: "eth_getBlockByHash",
  20302. args: [req.blockHash, !!req.includeTransactions]
  20303. };
  20304. }
  20305. break;
  20306. case "getTransaction":
  20307. return {
  20308. method: "eth_getTransactionByHash",
  20309. args: [req.hash]
  20310. };
  20311. case "getTransactionReceipt":
  20312. return {
  20313. method: "eth_getTransactionReceipt",
  20314. args: [req.hash]
  20315. };
  20316. case "call":
  20317. return {
  20318. method: "eth_call",
  20319. args: [this.getRpcTransaction(req.transaction), req.blockTag]
  20320. };
  20321. case "estimateGas": {
  20322. return {
  20323. method: "eth_estimateGas",
  20324. args: [this.getRpcTransaction(req.transaction)]
  20325. };
  20326. }
  20327. case "getLogs":
  20328. if (req.filter && req.filter.address != null) {
  20329. if (Array.isArray(req.filter.address)) {
  20330. req.filter.address = req.filter.address.map(getLowerCase);
  20331. }
  20332. else {
  20333. req.filter.address = getLowerCase(req.filter.address);
  20334. }
  20335. }
  20336. return { method: "eth_getLogs", args: [req.filter] };
  20337. }
  20338. return null;
  20339. }
  20340. /**
  20341. * Returns an ethers-style Error for the given JSON-RPC error
  20342. * %%payload%%, coalescing the various strings and error shapes
  20343. * that different nodes return, coercing them into a machine-readable
  20344. * standardized error.
  20345. */
  20346. getRpcError(payload, _error) {
  20347. const { method } = payload;
  20348. const { error } = _error;
  20349. if (method === "eth_estimateGas" && error.message) {
  20350. const msg = error.message;
  20351. if (!msg.match(/revert/i) && msg.match(/insufficient funds/i)) {
  20352. return makeError("insufficient funds", "INSUFFICIENT_FUNDS", {
  20353. transaction: (payload.params[0]),
  20354. info: { payload, error }
  20355. });
  20356. }
  20357. }
  20358. if (method === "eth_call" || method === "eth_estimateGas") {
  20359. const result = spelunkData(error);
  20360. const e = AbiCoder.getBuiltinCallException((method === "eth_call") ? "call" : "estimateGas", (payload.params[0]), (result ? result.data : null));
  20361. e.info = { error, payload };
  20362. return e;
  20363. }
  20364. // Only estimateGas and call can return arbitrary contract-defined text, so now we
  20365. // we can process text safely.
  20366. const message = JSON.stringify(spelunkMessage(error));
  20367. if (typeof (error.message) === "string" && error.message.match(/user denied|ethers-user-denied/i)) {
  20368. const actionMap = {
  20369. eth_sign: "signMessage",
  20370. personal_sign: "signMessage",
  20371. eth_signTypedData_v4: "signTypedData",
  20372. eth_signTransaction: "signTransaction",
  20373. eth_sendTransaction: "sendTransaction",
  20374. eth_requestAccounts: "requestAccess",
  20375. wallet_requestAccounts: "requestAccess",
  20376. };
  20377. return makeError(`user rejected action`, "ACTION_REJECTED", {
  20378. action: (actionMap[method] || "unknown"),
  20379. reason: "rejected",
  20380. info: { payload, error }
  20381. });
  20382. }
  20383. if (method === "eth_sendRawTransaction" || method === "eth_sendTransaction") {
  20384. const transaction = (payload.params[0]);
  20385. if (message.match(/insufficient funds|base fee exceeds gas limit/i)) {
  20386. return makeError("insufficient funds for intrinsic transaction cost", "INSUFFICIENT_FUNDS", {
  20387. transaction, info: { error }
  20388. });
  20389. }
  20390. if (message.match(/nonce/i) && message.match(/too low/i)) {
  20391. return makeError("nonce has already been used", "NONCE_EXPIRED", { transaction, info: { error } });
  20392. }
  20393. // "replacement transaction underpriced"
  20394. if (message.match(/replacement transaction/i) && message.match(/underpriced/i)) {
  20395. return makeError("replacement fee too low", "REPLACEMENT_UNDERPRICED", { transaction, info: { error } });
  20396. }
  20397. if (message.match(/only replay-protected/i)) {
  20398. return makeError("legacy pre-eip-155 transactions not supported", "UNSUPPORTED_OPERATION", {
  20399. operation: method, info: { transaction, info: { error } }
  20400. });
  20401. }
  20402. }
  20403. let unsupported = !!message.match(/the method .* does not exist/i);
  20404. if (!unsupported) {
  20405. if (error && error.details && error.details.startsWith("Unauthorized method:")) {
  20406. unsupported = true;
  20407. }
  20408. }
  20409. if (unsupported) {
  20410. return makeError("unsupported operation", "UNSUPPORTED_OPERATION", {
  20411. operation: payload.method, info: { error, payload }
  20412. });
  20413. }
  20414. return makeError("could not coalesce error", "UNKNOWN_ERROR", { error, payload });
  20415. }
  20416. /**
  20417. * Requests the %%method%% with %%params%% via the JSON-RPC protocol
  20418. * over the underlying channel. This can be used to call methods
  20419. * on the backend that do not have a high-level API within the Provider
  20420. * API.
  20421. *
  20422. * This method queues requests according to the batch constraints
  20423. * in the options, assigns the request a unique ID.
  20424. *
  20425. * **Do NOT override** this method in sub-classes; instead
  20426. * override [[_send]] or force the options values in the
  20427. * call to the constructor to modify this method's behavior.
  20428. */
  20429. send(method, params) {
  20430. // @TODO: cache chainId?? purge on switch_networks
  20431. // We have been destroyed; no operations are supported anymore
  20432. if (this.destroyed) {
  20433. return Promise.reject(makeError("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: method }));
  20434. }
  20435. const id = this.#nextId++;
  20436. const promise = new Promise((resolve, reject) => {
  20437. this.#payloads.push({
  20438. resolve, reject,
  20439. payload: { method, params, id, jsonrpc: "2.0" }
  20440. });
  20441. });
  20442. // If there is not a pending drainTimer, set one
  20443. this.#scheduleDrain();
  20444. return promise;
  20445. }
  20446. /**
  20447. * Resolves to the [[Signer]] account for %%address%% managed by
  20448. * the client.
  20449. *
  20450. * If the %%address%% is a number, it is used as an index in the
  20451. * the accounts from [[listAccounts]].
  20452. *
  20453. * This can only be used on clients which manage accounts (such as
  20454. * Geth with imported account or MetaMask).
  20455. *
  20456. * Throws if the account doesn't exist.
  20457. */
  20458. async getSigner(address) {
  20459. if (address == null) {
  20460. address = 0;
  20461. }
  20462. const accountsPromise = this.send("eth_accounts", []);
  20463. // Account index
  20464. if (typeof (address) === "number") {
  20465. const accounts = (await accountsPromise);
  20466. if (address >= accounts.length) {
  20467. throw new Error("no such account");
  20468. }
  20469. return new JsonRpcSigner(this, accounts[address]);
  20470. }
  20471. const { accounts } = await resolveProperties({
  20472. network: this.getNetwork(),
  20473. accounts: accountsPromise
  20474. });
  20475. // Account address
  20476. address = getAddress(address);
  20477. for (const account of accounts) {
  20478. if (getAddress(account) === address) {
  20479. return new JsonRpcSigner(this, address);
  20480. }
  20481. }
  20482. throw new Error("invalid account");
  20483. }
  20484. async listAccounts() {
  20485. const accounts = await this.send("eth_accounts", []);
  20486. return accounts.map((a) => new JsonRpcSigner(this, a));
  20487. }
  20488. destroy() {
  20489. // Stop processing requests
  20490. if (this.#drainTimer) {
  20491. clearTimeout(this.#drainTimer);
  20492. this.#drainTimer = null;
  20493. }
  20494. // Cancel all pending requests
  20495. for (const { payload, reject } of this.#payloads) {
  20496. reject(makeError("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { operation: payload.method }));
  20497. }
  20498. this.#payloads = [];
  20499. // Parent clean-up
  20500. super.destroy();
  20501. }
  20502. }
  20503. // @TODO: remove this in v7, it is not exported because this functionality
  20504. // is exposed in the JsonRpcApiProvider by setting polling to true. It should
  20505. // be safe to remove regardless, because it isn't reachable, but just in case.
  20506. /**
  20507. * @_ignore:
  20508. */
  20509. class JsonRpcApiPollingProvider extends JsonRpcApiProvider {
  20510. #pollingInterval;
  20511. constructor(network, options) {
  20512. super(network, options);
  20513. let pollingInterval = this._getOption("pollingInterval");
  20514. if (pollingInterval == null) {
  20515. pollingInterval = defaultOptions.pollingInterval;
  20516. }
  20517. this.#pollingInterval = pollingInterval;
  20518. }
  20519. _getSubscriber(sub) {
  20520. const subscriber = super._getSubscriber(sub);
  20521. if (isPollable(subscriber)) {
  20522. subscriber.pollingInterval = this.#pollingInterval;
  20523. }
  20524. return subscriber;
  20525. }
  20526. /**
  20527. * The polling interval (default: 4000 ms)
  20528. */
  20529. get pollingInterval() { return this.#pollingInterval; }
  20530. set pollingInterval(value) {
  20531. if (!Number.isInteger(value) || value < 0) {
  20532. throw new Error("invalid interval");
  20533. }
  20534. this.#pollingInterval = value;
  20535. this._forEachSubscriber((sub) => {
  20536. if (isPollable(sub)) {
  20537. sub.pollingInterval = this.#pollingInterval;
  20538. }
  20539. });
  20540. }
  20541. }
  20542. /**
  20543. * The JsonRpcProvider is one of the most common Providers,
  20544. * which performs all operations over HTTP (or HTTPS) requests.
  20545. *
  20546. * Events are processed by polling the backend for the current block
  20547. * number; when it advances, all block-base events are then checked
  20548. * for updates.
  20549. */
  20550. class JsonRpcProvider extends JsonRpcApiPollingProvider {
  20551. #connect;
  20552. constructor(url, network, options) {
  20553. if (url == null) {
  20554. url = "http:/\/localhost:8545";
  20555. }
  20556. super(network, options);
  20557. if (typeof (url) === "string") {
  20558. this.#connect = new FetchRequest(url);
  20559. }
  20560. else {
  20561. this.#connect = url.clone();
  20562. }
  20563. }
  20564. _getConnection() {
  20565. return this.#connect.clone();
  20566. }
  20567. async send(method, params) {
  20568. // All requests are over HTTP, so we can just start handling requests
  20569. // We do this here rather than the constructor so that we don't send any
  20570. // requests to the network (i.e. eth_chainId) until we absolutely have to.
  20571. await this._start();
  20572. return await super.send(method, params);
  20573. }
  20574. async _send(payload) {
  20575. // Configure a POST connection for the requested method
  20576. const request = this._getConnection();
  20577. request.body = JSON.stringify(payload);
  20578. request.setHeader("content-type", "application/json");
  20579. const response = await request.send();
  20580. response.assertOk();
  20581. let resp = response.bodyJson;
  20582. if (!Array.isArray(resp)) {
  20583. resp = [resp];
  20584. }
  20585. return resp;
  20586. }
  20587. }
  20588. function spelunkData(value) {
  20589. if (value == null) {
  20590. return null;
  20591. }
  20592. // These *are* the droids we're looking for.
  20593. if (typeof (value.message) === "string" && value.message.match(/revert/i) && isHexString(value.data)) {
  20594. return { message: value.message, data: value.data };
  20595. }
  20596. // Spelunk further...
  20597. if (typeof (value) === "object") {
  20598. for (const key in value) {
  20599. const result = spelunkData(value[key]);
  20600. if (result) {
  20601. return result;
  20602. }
  20603. }
  20604. return null;
  20605. }
  20606. // Might be a JSON string we can further descend...
  20607. if (typeof (value) === "string") {
  20608. try {
  20609. return spelunkData(JSON.parse(value));
  20610. }
  20611. catch (error) { }
  20612. }
  20613. return null;
  20614. }
  20615. function _spelunkMessage(value, result) {
  20616. if (value == null) {
  20617. return;
  20618. }
  20619. // These *are* the droids we're looking for.
  20620. if (typeof (value.message) === "string") {
  20621. result.push(value.message);
  20622. }
  20623. // Spelunk further...
  20624. if (typeof (value) === "object") {
  20625. for (const key in value) {
  20626. _spelunkMessage(value[key], result);
  20627. }
  20628. }
  20629. // Might be a JSON string we can further descend...
  20630. if (typeof (value) === "string") {
  20631. try {
  20632. return _spelunkMessage(JSON.parse(value), result);
  20633. }
  20634. catch (error) { }
  20635. }
  20636. }
  20637. function spelunkMessage(value) {
  20638. const result = [];
  20639. _spelunkMessage(value, result);
  20640. return result;
  20641. }
  20642. /**
  20643. * [[link-ankr]] provides a third-party service for connecting to
  20644. * various blockchains over JSON-RPC.
  20645. *
  20646. * **Supported Networks**
  20647. *
  20648. * - Ethereum Mainnet (``mainnet``)
  20649. * - Goerli Testnet (``goerli``)
  20650. * - Sepolia Testnet (``sepolia``)
  20651. * - Arbitrum (``arbitrum``)
  20652. * - Base (``base``)
  20653. * - Base Goerlia Testnet (``base-goerli``)
  20654. * - Base Sepolia Testnet (``base-sepolia``)
  20655. * - BNB (``bnb``)
  20656. * - BNB Testnet (``bnbt``)
  20657. * - Optimism (``optimism``)
  20658. * - Optimism Goerli Testnet (``optimism-goerli``)
  20659. * - Optimism Sepolia Testnet (``optimism-sepolia``)
  20660. * - Polygon (``matic``)
  20661. * - Polygon Mumbai Testnet (``matic-mumbai``)
  20662. *
  20663. * @_subsection: api/providers/thirdparty:Ankr [providers-ankr]
  20664. */
  20665. const defaultApiKey$1 = "9f7d929b018cdffb338517efa06f58359e86ff1ffd350bc889738523659e7972";
  20666. function getHost$5(name) {
  20667. switch (name) {
  20668. case "mainnet":
  20669. return "rpc.ankr.com/eth";
  20670. case "goerli":
  20671. return "rpc.ankr.com/eth_goerli";
  20672. case "sepolia":
  20673. return "rpc.ankr.com/eth_sepolia";
  20674. case "arbitrum":
  20675. return "rpc.ankr.com/arbitrum";
  20676. case "base":
  20677. return "rpc.ankr.com/base";
  20678. case "base-goerli":
  20679. return "rpc.ankr.com/base_goerli";
  20680. case "base-sepolia":
  20681. return "rpc.ankr.com/base_sepolia";
  20682. case "bnb":
  20683. return "rpc.ankr.com/bsc";
  20684. case "bnbt":
  20685. return "rpc.ankr.com/bsc_testnet_chapel";
  20686. case "matic":
  20687. return "rpc.ankr.com/polygon";
  20688. case "matic-mumbai":
  20689. return "rpc.ankr.com/polygon_mumbai";
  20690. case "optimism":
  20691. return "rpc.ankr.com/optimism";
  20692. case "optimism-goerli":
  20693. return "rpc.ankr.com/optimism_testnet";
  20694. case "optimism-sepolia":
  20695. return "rpc.ankr.com/optimism_sepolia";
  20696. }
  20697. assertArgument(false, "unsupported network", "network", name);
  20698. }
  20699. /**
  20700. * The **AnkrProvider** connects to the [[link-ankr]]
  20701. * JSON-RPC end-points.
  20702. *
  20703. * By default, a highly-throttled API key is used, which is
  20704. * appropriate for quick prototypes and simple scripts. To
  20705. * gain access to an increased rate-limit, it is highly
  20706. * recommended to [sign up here](link-ankr-signup).
  20707. */
  20708. class AnkrProvider extends JsonRpcProvider {
  20709. /**
  20710. * The API key for the Ankr connection.
  20711. */
  20712. apiKey;
  20713. /**
  20714. * Create a new **AnkrProvider**.
  20715. *
  20716. * By default connecting to ``mainnet`` with a highly throttled
  20717. * API key.
  20718. */
  20719. constructor(_network, apiKey) {
  20720. if (_network == null) {
  20721. _network = "mainnet";
  20722. }
  20723. const network = Network.from(_network);
  20724. if (apiKey == null) {
  20725. apiKey = defaultApiKey$1;
  20726. }
  20727. // Ankr does not support filterId, so we force polling
  20728. const options = { polling: true, staticNetwork: network };
  20729. const request = AnkrProvider.getRequest(network, apiKey);
  20730. super(request, network, options);
  20731. defineProperties(this, { apiKey });
  20732. }
  20733. _getProvider(chainId) {
  20734. try {
  20735. return new AnkrProvider(chainId, this.apiKey);
  20736. }
  20737. catch (error) { }
  20738. return super._getProvider(chainId);
  20739. }
  20740. /**
  20741. * Returns a prepared request for connecting to %%network%% with
  20742. * %%apiKey%%.
  20743. */
  20744. static getRequest(network, apiKey) {
  20745. if (apiKey == null) {
  20746. apiKey = defaultApiKey$1;
  20747. }
  20748. const request = new FetchRequest(`https:/\/${getHost$5(network.name)}/${apiKey}`);
  20749. request.allowGzip = true;
  20750. if (apiKey === defaultApiKey$1) {
  20751. request.retryFunc = async (request, response, attempt) => {
  20752. showThrottleMessage("AnkrProvider");
  20753. return true;
  20754. };
  20755. }
  20756. return request;
  20757. }
  20758. getRpcError(payload, error) {
  20759. if (payload.method === "eth_sendRawTransaction") {
  20760. if (error && error.error && error.error.message === "INTERNAL_ERROR: could not replace existing tx") {
  20761. error.error.message = "replacement transaction underpriced";
  20762. }
  20763. }
  20764. return super.getRpcError(payload, error);
  20765. }
  20766. isCommunityResource() {
  20767. return (this.apiKey === defaultApiKey$1);
  20768. }
  20769. }
  20770. /**
  20771. * [[link-alchemy]] provides a third-party service for connecting to
  20772. * various blockchains over JSON-RPC.
  20773. *
  20774. * **Supported Networks**
  20775. *
  20776. * - Ethereum Mainnet (``mainnet``)
  20777. * - Goerli Testnet (``goerli``)
  20778. * - Sepolia Testnet (``sepolia``)
  20779. * - Arbitrum (``arbitrum``)
  20780. * - Arbitrum Goerli Testnet (``arbitrum-goerli``)
  20781. * - Arbitrum Sepolia Testnet (``arbitrum-sepolia``)
  20782. * - Base (``base``)
  20783. * - Base Goerlia Testnet (``base-goerli``)
  20784. * - Base Sepolia Testnet (``base-sepolia``)
  20785. * - Optimism (``optimism``)
  20786. * - Optimism Goerli Testnet (``optimism-goerli``)
  20787. * - Optimism Sepolia Testnet (``optimism-sepolia``)
  20788. * - Polygon (``matic``)
  20789. * - Polygon Amoy Testnet (``matic-amoy``)
  20790. * - Polygon Mumbai Testnet (``matic-mumbai``)
  20791. *
  20792. * @_subsection: api/providers/thirdparty:Alchemy [providers-alchemy]
  20793. */
  20794. const defaultApiKey = "_gg7wSSi0KMBsdKnGVfHDueq6xMB9EkC";
  20795. function getHost$4(name) {
  20796. switch (name) {
  20797. case "mainnet":
  20798. return "eth-mainnet.alchemyapi.io";
  20799. case "goerli":
  20800. return "eth-goerli.g.alchemy.com";
  20801. case "sepolia":
  20802. return "eth-sepolia.g.alchemy.com";
  20803. case "arbitrum":
  20804. return "arb-mainnet.g.alchemy.com";
  20805. case "arbitrum-goerli":
  20806. return "arb-goerli.g.alchemy.com";
  20807. case "arbitrum-sepolia":
  20808. return "arb-sepolia.g.alchemy.com";
  20809. case "base":
  20810. return "base-mainnet.g.alchemy.com";
  20811. case "base-goerli":
  20812. return "base-goerli.g.alchemy.com";
  20813. case "base-sepolia":
  20814. return "base-sepolia.g.alchemy.com";
  20815. case "matic":
  20816. return "polygon-mainnet.g.alchemy.com";
  20817. case "matic-amoy":
  20818. return "polygon-amoy.g.alchemy.com";
  20819. case "matic-mumbai":
  20820. return "polygon-mumbai.g.alchemy.com";
  20821. case "optimism":
  20822. return "opt-mainnet.g.alchemy.com";
  20823. case "optimism-goerli":
  20824. return "opt-goerli.g.alchemy.com";
  20825. case "optimism-sepolia":
  20826. return "opt-sepolia.g.alchemy.com";
  20827. }
  20828. assertArgument(false, "unsupported network", "network", name);
  20829. }
  20830. /**
  20831. * The **AlchemyProvider** connects to the [[link-alchemy]]
  20832. * JSON-RPC end-points.
  20833. *
  20834. * By default, a highly-throttled API key is used, which is
  20835. * appropriate for quick prototypes and simple scripts. To
  20836. * gain access to an increased rate-limit, it is highly
  20837. * recommended to [sign up here](link-alchemy-signup).
  20838. *
  20839. * @_docloc: api/providers/thirdparty
  20840. */
  20841. class AlchemyProvider extends JsonRpcProvider {
  20842. apiKey;
  20843. constructor(_network, apiKey) {
  20844. if (_network == null) {
  20845. _network = "mainnet";
  20846. }
  20847. const network = Network.from(_network);
  20848. if (apiKey == null) {
  20849. apiKey = defaultApiKey;
  20850. }
  20851. const request = AlchemyProvider.getRequest(network, apiKey);
  20852. super(request, network, { staticNetwork: network });
  20853. defineProperties(this, { apiKey });
  20854. }
  20855. _getProvider(chainId) {
  20856. try {
  20857. return new AlchemyProvider(chainId, this.apiKey);
  20858. }
  20859. catch (error) { }
  20860. return super._getProvider(chainId);
  20861. }
  20862. async _perform(req) {
  20863. // https://docs.alchemy.com/reference/trace-transaction
  20864. if (req.method === "getTransactionResult") {
  20865. const { trace, tx } = await resolveProperties({
  20866. trace: this.send("trace_transaction", [req.hash]),
  20867. tx: this.getTransaction(req.hash)
  20868. });
  20869. if (trace == null || tx == null) {
  20870. return null;
  20871. }
  20872. let data;
  20873. let error = false;
  20874. try {
  20875. data = trace[0].result.output;
  20876. error = (trace[0].error === "Reverted");
  20877. }
  20878. catch (error) { }
  20879. if (data) {
  20880. assert(!error, "an error occurred during transaction executions", "CALL_EXCEPTION", {
  20881. action: "getTransactionResult",
  20882. data,
  20883. reason: null,
  20884. transaction: tx,
  20885. invocation: null,
  20886. revert: null // @TODO
  20887. });
  20888. return data;
  20889. }
  20890. assert(false, "could not parse trace result", "BAD_DATA", { value: trace });
  20891. }
  20892. return await super._perform(req);
  20893. }
  20894. isCommunityResource() {
  20895. return (this.apiKey === defaultApiKey);
  20896. }
  20897. static getRequest(network, apiKey) {
  20898. if (apiKey == null) {
  20899. apiKey = defaultApiKey;
  20900. }
  20901. const request = new FetchRequest(`https:/\/${getHost$4(network.name)}/v2/${apiKey}`);
  20902. request.allowGzip = true;
  20903. if (apiKey === defaultApiKey) {
  20904. request.retryFunc = async (request, response, attempt) => {
  20905. showThrottleMessage("alchemy");
  20906. return true;
  20907. };
  20908. }
  20909. return request;
  20910. }
  20911. }
  20912. /**
  20913. * [[link-chainstack]] provides a third-party service for connecting to
  20914. * various blockchains over JSON-RPC.
  20915. *
  20916. * **Supported Networks**
  20917. *
  20918. * - Ethereum Mainnet (``mainnet``)
  20919. * - Arbitrum (``arbitrum``)
  20920. * - BNB Smart Chain Mainnet (``bnb``)
  20921. * - Polygon (``matic``)
  20922. *
  20923. * @_subsection: api/providers/thirdparty:Chainstack [providers-chainstack]
  20924. */
  20925. function getApiKey(name) {
  20926. switch (name) {
  20927. case "mainnet": return "39f1d67cedf8b7831010a665328c9197";
  20928. case "arbitrum": return "0550c209db33c3abf4cc927e1e18cea1";
  20929. case "bnb": return "98b5a77e531614387366f6fc5da097f8";
  20930. case "matic": return "cd9d4d70377471aa7c142ec4a4205249";
  20931. }
  20932. assertArgument(false, "unsupported network", "network", name);
  20933. }
  20934. function getHost$3(name) {
  20935. switch (name) {
  20936. case "mainnet":
  20937. return "ethereum-mainnet.core.chainstack.com";
  20938. case "arbitrum":
  20939. return "arbitrum-mainnet.core.chainstack.com";
  20940. case "bnb":
  20941. return "bsc-mainnet.core.chainstack.com";
  20942. case "matic":
  20943. return "polygon-mainnet.core.chainstack.com";
  20944. }
  20945. assertArgument(false, "unsupported network", "network", name);
  20946. }
  20947. /**
  20948. * The **ChainstackProvider** connects to the [[link-chainstack]]
  20949. * JSON-RPC end-points.
  20950. *
  20951. * By default, a highly-throttled API key is used, which is
  20952. * appropriate for quick prototypes and simple scripts. To
  20953. * gain access to an increased rate-limit, it is highly
  20954. * recommended to [sign up here](link-chainstack).
  20955. */
  20956. class ChainstackProvider extends JsonRpcProvider {
  20957. /**
  20958. * The API key for the Chainstack connection.
  20959. */
  20960. apiKey;
  20961. /**
  20962. * Creates a new **ChainstackProvider**.
  20963. */
  20964. constructor(_network, apiKey) {
  20965. if (_network == null) {
  20966. _network = "mainnet";
  20967. }
  20968. const network = Network.from(_network);
  20969. if (apiKey == null) {
  20970. apiKey = getApiKey(network.name);
  20971. }
  20972. const request = ChainstackProvider.getRequest(network, apiKey);
  20973. super(request, network, { staticNetwork: network });
  20974. defineProperties(this, { apiKey });
  20975. }
  20976. _getProvider(chainId) {
  20977. try {
  20978. return new ChainstackProvider(chainId, this.apiKey);
  20979. }
  20980. catch (error) { }
  20981. return super._getProvider(chainId);
  20982. }
  20983. isCommunityResource() {
  20984. return (this.apiKey === getApiKey(this._network.name));
  20985. }
  20986. /**
  20987. * Returns a prepared request for connecting to %%network%%
  20988. * with %%apiKey%% and %%projectSecret%%.
  20989. */
  20990. static getRequest(network, apiKey) {
  20991. if (apiKey == null) {
  20992. apiKey = getApiKey(network.name);
  20993. }
  20994. const request = new FetchRequest(`https:/\/${getHost$3(network.name)}/${apiKey}`);
  20995. request.allowGzip = true;
  20996. if (apiKey === getApiKey(network.name)) {
  20997. request.retryFunc = async (request, response, attempt) => {
  20998. showThrottleMessage("ChainstackProvider");
  20999. return true;
  21000. };
  21001. }
  21002. return request;
  21003. }
  21004. }
  21005. /**
  21006. * About Cloudflare
  21007. *
  21008. * @_subsection: api/providers/thirdparty:Cloudflare [providers-cloudflare]
  21009. */
  21010. /**
  21011. * About Cloudflare...
  21012. */
  21013. class CloudflareProvider extends JsonRpcProvider {
  21014. constructor(_network) {
  21015. if (_network == null) {
  21016. _network = "mainnet";
  21017. }
  21018. const network = Network.from(_network);
  21019. assertArgument(network.name === "mainnet", "unsupported network", "network", _network);
  21020. super("https:/\/cloudflare-eth.com/", network, { staticNetwork: network });
  21021. }
  21022. }
  21023. /**
  21024. * [[link-etherscan]] provides a third-party service for connecting to
  21025. * various blockchains over a combination of JSON-RPC and custom API
  21026. * endpoints.
  21027. *
  21028. * **Supported Networks**
  21029. *
  21030. * - Ethereum Mainnet (``mainnet``)
  21031. * - Goerli Testnet (``goerli``)
  21032. * - Sepolia Testnet (``sepolia``)
  21033. * - Holesky Testnet (``holesky``)
  21034. * - Arbitrum (``arbitrum``)
  21035. * - Arbitrum Goerli Testnet (``arbitrum-goerli``)
  21036. * - Base (``base``)
  21037. * - Base Sepolia Testnet (``base-sepolia``)
  21038. * - BNB Smart Chain Mainnet (``bnb``)
  21039. * - BNB Smart Chain Testnet (``bnbt``)
  21040. * - Optimism (``optimism``)
  21041. * - Optimism Goerli Testnet (``optimism-goerli``)
  21042. * - Polygon (``matic``)
  21043. * - Polygon Mumbai Testnet (``matic-mumbai``)
  21044. * - Polygon Amoy Testnet (``matic-amoy``)
  21045. *
  21046. * @_subsection api/providers/thirdparty:Etherscan [providers-etherscan]
  21047. */
  21048. const THROTTLE = 2000;
  21049. function isPromise(value) {
  21050. return (value && typeof (value.then) === "function");
  21051. }
  21052. const EtherscanPluginId = "org.ethers.plugins.provider.Etherscan";
  21053. /**
  21054. * A Network can include an **EtherscanPlugin** to provide
  21055. * a custom base URL.
  21056. *
  21057. * @_docloc: api/providers/thirdparty:Etherscan
  21058. */
  21059. class EtherscanPlugin extends NetworkPlugin {
  21060. /**
  21061. * The Etherscan API base URL.
  21062. */
  21063. baseUrl;
  21064. /**
  21065. * Creates a new **EtherscanProvider** which will use
  21066. * %%baseUrl%%.
  21067. */
  21068. constructor(baseUrl) {
  21069. super(EtherscanPluginId);
  21070. defineProperties(this, { baseUrl });
  21071. }
  21072. clone() {
  21073. return new EtherscanPlugin(this.baseUrl);
  21074. }
  21075. }
  21076. const skipKeys = ["enableCcipRead"];
  21077. let nextId = 1;
  21078. /**
  21079. * The **EtherscanBaseProvider** is the super-class of
  21080. * [[EtherscanProvider]], which should generally be used instead.
  21081. *
  21082. * Since the **EtherscanProvider** includes additional code for
  21083. * [[Contract]] access, in //rare cases// that contracts are not
  21084. * used, this class can reduce code size.
  21085. *
  21086. * @_docloc: api/providers/thirdparty:Etherscan
  21087. */
  21088. class EtherscanProvider extends AbstractProvider {
  21089. /**
  21090. * The connected network.
  21091. */
  21092. network;
  21093. /**
  21094. * The API key or null if using the community provided bandwidth.
  21095. */
  21096. apiKey;
  21097. #plugin;
  21098. /**
  21099. * Creates a new **EtherscanBaseProvider**.
  21100. */
  21101. constructor(_network, _apiKey) {
  21102. const apiKey = (_apiKey != null) ? _apiKey : null;
  21103. super();
  21104. const network = Network.from(_network);
  21105. this.#plugin = network.getPlugin(EtherscanPluginId);
  21106. defineProperties(this, { apiKey, network });
  21107. // Test that the network is supported by Etherscan
  21108. this.getBaseUrl();
  21109. }
  21110. /**
  21111. * Returns the base URL.
  21112. *
  21113. * If an [[EtherscanPlugin]] is configured on the
  21114. * [[EtherscanBaseProvider_network]], returns the plugin's
  21115. * baseUrl.
  21116. */
  21117. getBaseUrl() {
  21118. if (this.#plugin) {
  21119. return this.#plugin.baseUrl;
  21120. }
  21121. switch (this.network.name) {
  21122. case "mainnet":
  21123. return "https:/\/api.etherscan.io";
  21124. case "goerli":
  21125. return "https:/\/api-goerli.etherscan.io";
  21126. case "sepolia":
  21127. return "https:/\/api-sepolia.etherscan.io";
  21128. case "holesky":
  21129. return "https:/\/api-holesky.etherscan.io";
  21130. case "arbitrum":
  21131. return "https:/\/api.arbiscan.io";
  21132. case "arbitrum-goerli":
  21133. return "https:/\/api-goerli.arbiscan.io";
  21134. case "base":
  21135. return "https:/\/api.basescan.org";
  21136. case "base-sepolia":
  21137. return "https:/\/api-sepolia.basescan.org";
  21138. case "bnb":
  21139. return "https:/\/api.bscscan.com";
  21140. case "bnbt":
  21141. return "https:/\/api-testnet.bscscan.com";
  21142. case "matic":
  21143. return "https:/\/api.polygonscan.com";
  21144. case "matic-amoy":
  21145. return "https:/\/api-amoy.polygonscan.com";
  21146. case "matic-mumbai":
  21147. return "https:/\/api-testnet.polygonscan.com";
  21148. case "optimism":
  21149. return "https:/\/api-optimistic.etherscan.io";
  21150. case "optimism-goerli":
  21151. return "https:/\/api-goerli-optimistic.etherscan.io";
  21152. }
  21153. assertArgument(false, "unsupported network", "network", this.network);
  21154. }
  21155. /**
  21156. * Returns the URL for the %%module%% and %%params%%.
  21157. */
  21158. getUrl(module, params) {
  21159. const query = Object.keys(params).reduce((accum, key) => {
  21160. const value = params[key];
  21161. if (value != null) {
  21162. accum += `&${key}=${value}`;
  21163. }
  21164. return accum;
  21165. }, "");
  21166. const apiKey = ((this.apiKey) ? `&apikey=${this.apiKey}` : "");
  21167. return `${this.getBaseUrl()}/api?module=${module}${query}${apiKey}`;
  21168. }
  21169. /**
  21170. * Returns the URL for using POST requests.
  21171. */
  21172. getPostUrl() {
  21173. return `${this.getBaseUrl()}/api`;
  21174. }
  21175. /**
  21176. * Returns the parameters for using POST requests.
  21177. */
  21178. getPostData(module, params) {
  21179. params.module = module;
  21180. params.apikey = this.apiKey;
  21181. return params;
  21182. }
  21183. async detectNetwork() {
  21184. return this.network;
  21185. }
  21186. /**
  21187. * Resolves to the result of calling %%module%% with %%params%%.
  21188. *
  21189. * If %%post%%, the request is made as a POST request.
  21190. */
  21191. async fetch(module, params, post) {
  21192. const id = nextId++;
  21193. const url = (post ? this.getPostUrl() : this.getUrl(module, params));
  21194. const payload = (post ? this.getPostData(module, params) : null);
  21195. this.emit("debug", { action: "sendRequest", id, url, payload: payload });
  21196. const request = new FetchRequest(url);
  21197. request.setThrottleParams({ slotInterval: 1000 });
  21198. request.retryFunc = (req, resp, attempt) => {
  21199. if (this.isCommunityResource()) {
  21200. showThrottleMessage("Etherscan");
  21201. }
  21202. return Promise.resolve(true);
  21203. };
  21204. request.processFunc = async (request, response) => {
  21205. const result = response.hasBody() ? JSON.parse(toUtf8String(response.body)) : {};
  21206. const throttle = ((typeof (result.result) === "string") ? result.result : "").toLowerCase().indexOf("rate limit") >= 0;
  21207. if (module === "proxy") {
  21208. // This JSON response indicates we are being throttled
  21209. if (result && result.status == 0 && result.message == "NOTOK" && throttle) {
  21210. this.emit("debug", { action: "receiveError", id, reason: "proxy-NOTOK", error: result });
  21211. response.throwThrottleError(result.result, THROTTLE);
  21212. }
  21213. }
  21214. else {
  21215. if (throttle) {
  21216. this.emit("debug", { action: "receiveError", id, reason: "null result", error: result.result });
  21217. response.throwThrottleError(result.result, THROTTLE);
  21218. }
  21219. }
  21220. return response;
  21221. };
  21222. if (payload) {
  21223. request.setHeader("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
  21224. request.body = Object.keys(payload).map((k) => `${k}=${payload[k]}`).join("&");
  21225. }
  21226. const response = await request.send();
  21227. try {
  21228. response.assertOk();
  21229. }
  21230. catch (error) {
  21231. this.emit("debug", { action: "receiveError", id, error, reason: "assertOk" });
  21232. assert(false, "response error", "SERVER_ERROR", { request, response });
  21233. }
  21234. if (!response.hasBody()) {
  21235. this.emit("debug", { action: "receiveError", id, error: "missing body", reason: "null body" });
  21236. assert(false, "missing response", "SERVER_ERROR", { request, response });
  21237. }
  21238. const result = JSON.parse(toUtf8String(response.body));
  21239. if (module === "proxy") {
  21240. if (result.jsonrpc != "2.0") {
  21241. this.emit("debug", { action: "receiveError", id, result, reason: "invalid JSON-RPC" });
  21242. assert(false, "invalid JSON-RPC response (missing jsonrpc='2.0')", "SERVER_ERROR", { request, response, info: { result } });
  21243. }
  21244. if (result.error) {
  21245. this.emit("debug", { action: "receiveError", id, result, reason: "JSON-RPC error" });
  21246. assert(false, "error response", "SERVER_ERROR", { request, response, info: { result } });
  21247. }
  21248. this.emit("debug", { action: "receiveRequest", id, result });
  21249. return result.result;
  21250. }
  21251. else {
  21252. // getLogs, getHistory have weird success responses
  21253. if (result.status == 0 && (result.message === "No records found" || result.message === "No transactions found")) {
  21254. this.emit("debug", { action: "receiveRequest", id, result });
  21255. return result.result;
  21256. }
  21257. if (result.status != 1 || (typeof (result.message) === "string" && !result.message.match(/^OK/))) {
  21258. this.emit("debug", { action: "receiveError", id, result });
  21259. assert(false, "error response", "SERVER_ERROR", { request, response, info: { result } });
  21260. }
  21261. this.emit("debug", { action: "receiveRequest", id, result });
  21262. return result.result;
  21263. }
  21264. }
  21265. /**
  21266. * Returns %%transaction%% normalized for the Etherscan API.
  21267. */
  21268. _getTransactionPostData(transaction) {
  21269. const result = {};
  21270. for (let key in transaction) {
  21271. if (skipKeys.indexOf(key) >= 0) {
  21272. continue;
  21273. }
  21274. if (transaction[key] == null) {
  21275. continue;
  21276. }
  21277. let value = transaction[key];
  21278. if (key === "type" && value === 0) {
  21279. continue;
  21280. }
  21281. if (key === "blockTag" && value === "latest") {
  21282. continue;
  21283. }
  21284. // Quantity-types require no leading zero, unless 0
  21285. if ({ type: true, gasLimit: true, gasPrice: true, maxFeePerGs: true, maxPriorityFeePerGas: true, nonce: true, value: true }[key]) {
  21286. value = toQuantity(value);
  21287. }
  21288. else if (key === "accessList") {
  21289. value = "[" + accessListify(value).map((set) => {
  21290. return `{address:"${set.address}",storageKeys:["${set.storageKeys.join('","')}"]}`;
  21291. }).join(",") + "]";
  21292. }
  21293. else if (key === "blobVersionedHashes") {
  21294. if (value.length === 0) {
  21295. continue;
  21296. }
  21297. // @TODO: update this once the API supports blobs
  21298. assert(false, "Etherscan API does not support blobVersionedHashes", "UNSUPPORTED_OPERATION", {
  21299. operation: "_getTransactionPostData",
  21300. info: { transaction }
  21301. });
  21302. }
  21303. else {
  21304. value = hexlify(value);
  21305. }
  21306. result[key] = value;
  21307. }
  21308. return result;
  21309. }
  21310. /**
  21311. * Throws the normalized Etherscan error.
  21312. */
  21313. _checkError(req, error, transaction) {
  21314. // Pull any message out if, possible
  21315. let message = "";
  21316. if (isError(error, "SERVER_ERROR")) {
  21317. // Check for an error emitted by a proxy call
  21318. try {
  21319. message = error.info.result.error.message;
  21320. }
  21321. catch (e) { }
  21322. if (!message) {
  21323. try {
  21324. message = error.info.message;
  21325. }
  21326. catch (e) { }
  21327. }
  21328. }
  21329. if (req.method === "estimateGas") {
  21330. if (!message.match(/revert/i) && message.match(/insufficient funds/i)) {
  21331. assert(false, "insufficient funds", "INSUFFICIENT_FUNDS", {
  21332. transaction: req.transaction
  21333. });
  21334. }
  21335. }
  21336. if (req.method === "call" || req.method === "estimateGas") {
  21337. if (message.match(/execution reverted/i)) {
  21338. let data = "";
  21339. try {
  21340. data = error.info.result.error.data;
  21341. }
  21342. catch (error) { }
  21343. const e = AbiCoder.getBuiltinCallException(req.method, req.transaction, data);
  21344. e.info = { request: req, error };
  21345. throw e;
  21346. }
  21347. }
  21348. if (message) {
  21349. if (req.method === "broadcastTransaction") {
  21350. const transaction = Transaction.from(req.signedTransaction);
  21351. if (message.match(/replacement/i) && message.match(/underpriced/i)) {
  21352. assert(false, "replacement fee too low", "REPLACEMENT_UNDERPRICED", {
  21353. transaction
  21354. });
  21355. }
  21356. if (message.match(/insufficient funds/)) {
  21357. assert(false, "insufficient funds for intrinsic transaction cost", "INSUFFICIENT_FUNDS", {
  21358. transaction
  21359. });
  21360. }
  21361. if (message.match(/same hash was already imported|transaction nonce is too low|nonce too low/)) {
  21362. assert(false, "nonce has already been used", "NONCE_EXPIRED", {
  21363. transaction
  21364. });
  21365. }
  21366. }
  21367. }
  21368. // Something we could not process
  21369. throw error;
  21370. }
  21371. async _detectNetwork() {
  21372. return this.network;
  21373. }
  21374. async _perform(req) {
  21375. switch (req.method) {
  21376. case "chainId":
  21377. return this.network.chainId;
  21378. case "getBlockNumber":
  21379. return this.fetch("proxy", { action: "eth_blockNumber" });
  21380. case "getGasPrice":
  21381. return this.fetch("proxy", { action: "eth_gasPrice" });
  21382. case "getPriorityFee":
  21383. // This is temporary until Etherscan completes support
  21384. if (this.network.name === "mainnet") {
  21385. return "1000000000";
  21386. }
  21387. else if (this.network.name === "optimism") {
  21388. return "1000000";
  21389. }
  21390. else {
  21391. throw new Error("fallback onto the AbstractProvider default");
  21392. }
  21393. /* Working with Etherscan to get this added:
  21394. try {
  21395. const test = await this.fetch("proxy", {
  21396. action: "eth_maxPriorityFeePerGas"
  21397. });
  21398. console.log(test);
  21399. return test;
  21400. } catch (e) {
  21401. console.log("DEBUG", e);
  21402. throw e;
  21403. }
  21404. */
  21405. /* This might be safe; but due to rounding neither myself
  21406. or Etherscan are necessarily comfortable with this. :)
  21407. try {
  21408. const result = await this.fetch("gastracker", { action: "gasoracle" });
  21409. console.log(result);
  21410. const gasPrice = parseUnits(result.SafeGasPrice, "gwei");
  21411. const baseFee = parseUnits(result.suggestBaseFee, "gwei");
  21412. const priorityFee = gasPrice - baseFee;
  21413. if (priorityFee < 0) { throw new Error("negative priority fee; defer to abstract provider default"); }
  21414. return priorityFee;
  21415. } catch (error) {
  21416. console.log("DEBUG", error);
  21417. throw error;
  21418. }
  21419. */
  21420. case "getBalance":
  21421. // Returns base-10 result
  21422. return this.fetch("account", {
  21423. action: "balance",
  21424. address: req.address,
  21425. tag: req.blockTag
  21426. });
  21427. case "getTransactionCount":
  21428. return this.fetch("proxy", {
  21429. action: "eth_getTransactionCount",
  21430. address: req.address,
  21431. tag: req.blockTag
  21432. });
  21433. case "getCode":
  21434. return this.fetch("proxy", {
  21435. action: "eth_getCode",
  21436. address: req.address,
  21437. tag: req.blockTag
  21438. });
  21439. case "getStorage":
  21440. return this.fetch("proxy", {
  21441. action: "eth_getStorageAt",
  21442. address: req.address,
  21443. position: req.position,
  21444. tag: req.blockTag
  21445. });
  21446. case "broadcastTransaction":
  21447. return this.fetch("proxy", {
  21448. action: "eth_sendRawTransaction",
  21449. hex: req.signedTransaction
  21450. }, true).catch((error) => {
  21451. return this._checkError(req, error, req.signedTransaction);
  21452. });
  21453. case "getBlock":
  21454. if ("blockTag" in req) {
  21455. return this.fetch("proxy", {
  21456. action: "eth_getBlockByNumber",
  21457. tag: req.blockTag,
  21458. boolean: (req.includeTransactions ? "true" : "false")
  21459. });
  21460. }
  21461. assert(false, "getBlock by blockHash not supported by Etherscan", "UNSUPPORTED_OPERATION", {
  21462. operation: "getBlock(blockHash)"
  21463. });
  21464. case "getTransaction":
  21465. return this.fetch("proxy", {
  21466. action: "eth_getTransactionByHash",
  21467. txhash: req.hash
  21468. });
  21469. case "getTransactionReceipt":
  21470. return this.fetch("proxy", {
  21471. action: "eth_getTransactionReceipt",
  21472. txhash: req.hash
  21473. });
  21474. case "call": {
  21475. if (req.blockTag !== "latest") {
  21476. throw new Error("EtherscanProvider does not support blockTag for call");
  21477. }
  21478. const postData = this._getTransactionPostData(req.transaction);
  21479. postData.module = "proxy";
  21480. postData.action = "eth_call";
  21481. try {
  21482. return await this.fetch("proxy", postData, true);
  21483. }
  21484. catch (error) {
  21485. return this._checkError(req, error, req.transaction);
  21486. }
  21487. }
  21488. case "estimateGas": {
  21489. const postData = this._getTransactionPostData(req.transaction);
  21490. postData.module = "proxy";
  21491. postData.action = "eth_estimateGas";
  21492. try {
  21493. return await this.fetch("proxy", postData, true);
  21494. }
  21495. catch (error) {
  21496. return this._checkError(req, error, req.transaction);
  21497. }
  21498. }
  21499. }
  21500. return super._perform(req);
  21501. }
  21502. async getNetwork() {
  21503. return this.network;
  21504. }
  21505. /**
  21506. * Resolves to the current price of ether.
  21507. *
  21508. * This returns ``0`` on any network other than ``mainnet``.
  21509. */
  21510. async getEtherPrice() {
  21511. if (this.network.name !== "mainnet") {
  21512. return 0.0;
  21513. }
  21514. return parseFloat((await this.fetch("stats", { action: "ethprice" })).ethusd);
  21515. }
  21516. /**
  21517. * Resolves to a [Contract]] for %%address%%, using the
  21518. * Etherscan API to retreive the Contract ABI.
  21519. */
  21520. async getContract(_address) {
  21521. let address = this._getAddress(_address);
  21522. if (isPromise(address)) {
  21523. address = await address;
  21524. }
  21525. try {
  21526. const resp = await this.fetch("contract", {
  21527. action: "getabi", address
  21528. });
  21529. const abi = JSON.parse(resp);
  21530. return new Contract(address, abi, this);
  21531. }
  21532. catch (error) {
  21533. return null;
  21534. }
  21535. }
  21536. isCommunityResource() {
  21537. return (this.apiKey == null);
  21538. }
  21539. }
  21540. function getGlobal() {
  21541. if (typeof self !== 'undefined') {
  21542. return self;
  21543. }
  21544. if (typeof window !== 'undefined') {
  21545. return window;
  21546. }
  21547. if (typeof global !== 'undefined') {
  21548. return global;
  21549. }
  21550. throw new Error('unable to locate global object');
  21551. }
  21552. const _WebSocket = getGlobal().WebSocket;
  21553. /**
  21554. * Generic long-lived socket provider.
  21555. *
  21556. * Sub-classing notes
  21557. * - a sub-class MUST call the `_start()` method once connected
  21558. * - a sub-class MUST override the `_write(string)` method
  21559. * - a sub-class MUST call `_processMessage(string)` for each message
  21560. *
  21561. * @_subsection: api/providers/abstract-provider:Socket Providers [about-socketProvider]
  21562. */
  21563. /**
  21564. * A **SocketSubscriber** uses a socket transport to handle events and
  21565. * should use [[_emit]] to manage the events.
  21566. */
  21567. class SocketSubscriber {
  21568. #provider;
  21569. #filter;
  21570. /**
  21571. * The filter.
  21572. */
  21573. get filter() { return JSON.parse(this.#filter); }
  21574. #filterId;
  21575. #paused;
  21576. #emitPromise;
  21577. /**
  21578. * Creates a new **SocketSubscriber** attached to %%provider%% listening
  21579. * to %%filter%%.
  21580. */
  21581. constructor(provider, filter) {
  21582. this.#provider = provider;
  21583. this.#filter = JSON.stringify(filter);
  21584. this.#filterId = null;
  21585. this.#paused = null;
  21586. this.#emitPromise = null;
  21587. }
  21588. start() {
  21589. this.#filterId = this.#provider.send("eth_subscribe", this.filter).then((filterId) => {
  21590. this.#provider._register(filterId, this);
  21591. return filterId;
  21592. });
  21593. }
  21594. stop() {
  21595. (this.#filterId).then((filterId) => {
  21596. if (this.#provider.destroyed) {
  21597. return;
  21598. }
  21599. this.#provider.send("eth_unsubscribe", [filterId]);
  21600. });
  21601. this.#filterId = null;
  21602. }
  21603. // @TODO: pause should trap the current blockNumber, unsub, and on resume use getLogs
  21604. // and resume
  21605. pause(dropWhilePaused) {
  21606. assert(dropWhilePaused, "preserve logs while paused not supported by SocketSubscriber yet", "UNSUPPORTED_OPERATION", { operation: "pause(false)" });
  21607. this.#paused = !!dropWhilePaused;
  21608. }
  21609. resume() {
  21610. this.#paused = null;
  21611. }
  21612. /**
  21613. * @_ignore:
  21614. */
  21615. _handleMessage(message) {
  21616. if (this.#filterId == null) {
  21617. return;
  21618. }
  21619. if (this.#paused === null) {
  21620. let emitPromise = this.#emitPromise;
  21621. if (emitPromise == null) {
  21622. emitPromise = this._emit(this.#provider, message);
  21623. }
  21624. else {
  21625. emitPromise = emitPromise.then(async () => {
  21626. await this._emit(this.#provider, message);
  21627. });
  21628. }
  21629. this.#emitPromise = emitPromise.then(() => {
  21630. if (this.#emitPromise === emitPromise) {
  21631. this.#emitPromise = null;
  21632. }
  21633. });
  21634. }
  21635. }
  21636. /**
  21637. * Sub-classes **must** override this to emit the events on the
  21638. * provider.
  21639. */
  21640. async _emit(provider, message) {
  21641. throw new Error("sub-classes must implemente this; _emit");
  21642. }
  21643. }
  21644. /**
  21645. * A **SocketBlockSubscriber** listens for ``newHeads`` events and emits
  21646. * ``"block"`` events.
  21647. */
  21648. class SocketBlockSubscriber extends SocketSubscriber {
  21649. /**
  21650. * @_ignore:
  21651. */
  21652. constructor(provider) {
  21653. super(provider, ["newHeads"]);
  21654. }
  21655. async _emit(provider, message) {
  21656. provider.emit("block", parseInt(message.number));
  21657. }
  21658. }
  21659. /**
  21660. * A **SocketPendingSubscriber** listens for pending transacitons and emits
  21661. * ``"pending"`` events.
  21662. */
  21663. class SocketPendingSubscriber extends SocketSubscriber {
  21664. /**
  21665. * @_ignore:
  21666. */
  21667. constructor(provider) {
  21668. super(provider, ["newPendingTransactions"]);
  21669. }
  21670. async _emit(provider, message) {
  21671. provider.emit("pending", message);
  21672. }
  21673. }
  21674. /**
  21675. * A **SocketEventSubscriber** listens for event logs.
  21676. */
  21677. class SocketEventSubscriber extends SocketSubscriber {
  21678. #logFilter;
  21679. /**
  21680. * The filter.
  21681. */
  21682. get logFilter() { return JSON.parse(this.#logFilter); }
  21683. /**
  21684. * @_ignore:
  21685. */
  21686. constructor(provider, filter) {
  21687. super(provider, ["logs", filter]);
  21688. this.#logFilter = JSON.stringify(filter);
  21689. }
  21690. async _emit(provider, message) {
  21691. provider.emit(this.logFilter, provider._wrapLog(message, provider._network));
  21692. }
  21693. }
  21694. /**
  21695. * A **SocketProvider** is backed by a long-lived connection over a
  21696. * socket, which can subscribe and receive real-time messages over
  21697. * its communication channel.
  21698. */
  21699. class SocketProvider extends JsonRpcApiProvider {
  21700. #callbacks;
  21701. // Maps each filterId to its subscriber
  21702. #subs;
  21703. // If any events come in before a subscriber has finished
  21704. // registering, queue them
  21705. #pending;
  21706. /**
  21707. * Creates a new **SocketProvider** connected to %%network%%.
  21708. *
  21709. * If unspecified, the network will be discovered.
  21710. */
  21711. constructor(network, _options) {
  21712. // Copy the options
  21713. const options = Object.assign({}, (_options != null) ? _options : {});
  21714. // Support for batches is generally not supported for
  21715. // connection-base providers; if this changes in the future
  21716. // the _send should be updated to reflect this
  21717. assertArgument(options.batchMaxCount == null || options.batchMaxCount === 1, "sockets-based providers do not support batches", "options.batchMaxCount", _options);
  21718. options.batchMaxCount = 1;
  21719. // Socket-based Providers (generally) cannot change their network,
  21720. // since they have a long-lived connection; but let people override
  21721. // this if they have just cause.
  21722. if (options.staticNetwork == null) {
  21723. options.staticNetwork = true;
  21724. }
  21725. super(network, options);
  21726. this.#callbacks = new Map();
  21727. this.#subs = new Map();
  21728. this.#pending = new Map();
  21729. }
  21730. // This value is only valid after _start has been called
  21731. /*
  21732. get _network(): Network {
  21733. if (this.#network == null) {
  21734. throw new Error("this shouldn't happen");
  21735. }
  21736. return this.#network.clone();
  21737. }
  21738. */
  21739. _getSubscriber(sub) {
  21740. switch (sub.type) {
  21741. case "close":
  21742. return new UnmanagedSubscriber("close");
  21743. case "block":
  21744. return new SocketBlockSubscriber(this);
  21745. case "pending":
  21746. return new SocketPendingSubscriber(this);
  21747. case "event":
  21748. return new SocketEventSubscriber(this, sub.filter);
  21749. case "orphan":
  21750. // Handled auto-matically within AbstractProvider
  21751. // when the log.removed = true
  21752. if (sub.filter.orphan === "drop-log") {
  21753. return new UnmanagedSubscriber("drop-log");
  21754. }
  21755. }
  21756. return super._getSubscriber(sub);
  21757. }
  21758. /**
  21759. * Register a new subscriber. This is used internalled by Subscribers
  21760. * and generally is unecessary unless extending capabilities.
  21761. */
  21762. _register(filterId, subscriber) {
  21763. this.#subs.set(filterId, subscriber);
  21764. const pending = this.#pending.get(filterId);
  21765. if (pending) {
  21766. for (const message of pending) {
  21767. subscriber._handleMessage(message);
  21768. }
  21769. this.#pending.delete(filterId);
  21770. }
  21771. }
  21772. async _send(payload) {
  21773. // WebSocket provider doesn't accept batches
  21774. assertArgument(!Array.isArray(payload), "WebSocket does not support batch send", "payload", payload);
  21775. // @TODO: stringify payloads here and store to prevent mutations
  21776. // Prepare a promise to respond to
  21777. const promise = new Promise((resolve, reject) => {
  21778. this.#callbacks.set(payload.id, { payload, resolve, reject });
  21779. });
  21780. // Wait until the socket is connected before writing to it
  21781. await this._waitUntilReady();
  21782. // Write the request to the socket
  21783. await this._write(JSON.stringify(payload));
  21784. return [await promise];
  21785. }
  21786. // Sub-classes must call this once they are connected
  21787. /*
  21788. async _start(): Promise<void> {
  21789. if (this.#ready) { return; }
  21790. for (const { payload } of this.#callbacks.values()) {
  21791. await this._write(JSON.stringify(payload));
  21792. }
  21793. this.#ready = (async function() {
  21794. await super._start();
  21795. })();
  21796. }
  21797. */
  21798. /**
  21799. * Sub-classes **must** call this with messages received over their
  21800. * transport to be processed and dispatched.
  21801. */
  21802. async _processMessage(message) {
  21803. const result = (JSON.parse(message));
  21804. if (result && typeof (result) === "object" && "id" in result) {
  21805. const callback = this.#callbacks.get(result.id);
  21806. if (callback == null) {
  21807. this.emit("error", makeError("received result for unknown id", "UNKNOWN_ERROR", {
  21808. reasonCode: "UNKNOWN_ID",
  21809. result
  21810. }));
  21811. return;
  21812. }
  21813. this.#callbacks.delete(result.id);
  21814. callback.resolve(result);
  21815. }
  21816. else if (result && result.method === "eth_subscription") {
  21817. const filterId = result.params.subscription;
  21818. const subscriber = this.#subs.get(filterId);
  21819. if (subscriber) {
  21820. subscriber._handleMessage(result.params.result);
  21821. }
  21822. else {
  21823. let pending = this.#pending.get(filterId);
  21824. if (pending == null) {
  21825. pending = [];
  21826. this.#pending.set(filterId, pending);
  21827. }
  21828. pending.push(result.params.result);
  21829. }
  21830. }
  21831. else {
  21832. this.emit("error", makeError("received unexpected message", "UNKNOWN_ERROR", {
  21833. reasonCode: "UNEXPECTED_MESSAGE",
  21834. result
  21835. }));
  21836. return;
  21837. }
  21838. }
  21839. /**
  21840. * Sub-classes **must** override this to send %%message%% over their
  21841. * transport.
  21842. */
  21843. async _write(message) {
  21844. throw new Error("sub-classes must override this");
  21845. }
  21846. }
  21847. /**
  21848. * A JSON-RPC provider which is backed by a WebSocket.
  21849. *
  21850. * WebSockets are often preferred because they retain a live connection
  21851. * to a server, which permits more instant access to events.
  21852. *
  21853. * However, this incurs higher server infrasturture costs, so additional
  21854. * resources may be required to host your own WebSocket nodes and many
  21855. * third-party services charge additional fees for WebSocket endpoints.
  21856. */
  21857. class WebSocketProvider extends SocketProvider {
  21858. #connect;
  21859. #websocket;
  21860. get websocket() {
  21861. if (this.#websocket == null) {
  21862. throw new Error("websocket closed");
  21863. }
  21864. return this.#websocket;
  21865. }
  21866. constructor(url, network, options) {
  21867. super(network, options);
  21868. if (typeof (url) === "string") {
  21869. this.#connect = () => { return new _WebSocket(url); };
  21870. this.#websocket = this.#connect();
  21871. }
  21872. else if (typeof (url) === "function") {
  21873. this.#connect = url;
  21874. this.#websocket = url();
  21875. }
  21876. else {
  21877. this.#connect = null;
  21878. this.#websocket = url;
  21879. }
  21880. this.websocket.onopen = async () => {
  21881. try {
  21882. await this._start();
  21883. this.resume();
  21884. }
  21885. catch (error) {
  21886. console.log("failed to start WebsocketProvider", error);
  21887. // @TODO: now what? Attempt reconnect?
  21888. }
  21889. };
  21890. this.websocket.onmessage = (message) => {
  21891. this._processMessage(message.data);
  21892. };
  21893. /*
  21894. this.websocket.onclose = (event) => {
  21895. // @TODO: What event.code should we reconnect on?
  21896. const reconnect = false;
  21897. if (reconnect) {
  21898. this.pause(true);
  21899. if (this.#connect) {
  21900. this.#websocket = this.#connect();
  21901. this.#websocket.onopen = ...
  21902. // @TODO: this requires the super class to rebroadcast; move it there
  21903. }
  21904. this._reconnect();
  21905. }
  21906. };
  21907. */
  21908. }
  21909. async _write(message) {
  21910. this.websocket.send(message);
  21911. }
  21912. async destroy() {
  21913. if (this.#websocket != null) {
  21914. this.#websocket.close();
  21915. this.#websocket = null;
  21916. }
  21917. super.destroy();
  21918. }
  21919. }
  21920. /**
  21921. * [[link-infura]] provides a third-party service for connecting to
  21922. * various blockchains over JSON-RPC.
  21923. *
  21924. * **Supported Networks**
  21925. *
  21926. * - Ethereum Mainnet (``mainnet``)
  21927. * - Goerli Testnet (``goerli``)
  21928. * - Sepolia Testnet (``sepolia``)
  21929. * - Arbitrum (``arbitrum``)
  21930. * - Arbitrum Goerli Testnet (``arbitrum-goerli``)
  21931. * - Arbitrum Sepolia Testnet (``arbitrum-sepolia``)
  21932. * - Base (``base``)
  21933. * - Base Goerlia Testnet (``base-goerli``)
  21934. * - Base Sepolia Testnet (``base-sepolia``)
  21935. * - BNB Smart Chain Mainnet (``bnb``)
  21936. * - BNB Smart Chain Testnet (``bnbt``)
  21937. * - Linea (``linea``)
  21938. * - Linea Goerli Testnet (``linea-goerli``)
  21939. * - Linea Sepolia Testnet (``linea-sepolia``)
  21940. * - Optimism (``optimism``)
  21941. * - Optimism Goerli Testnet (``optimism-goerli``)
  21942. * - Optimism Sepolia Testnet (``optimism-sepolia``)
  21943. * - Polygon (``matic``)
  21944. * - Polygon Amoy Testnet (``matic-amoy``)
  21945. * - Polygon Mumbai Testnet (``matic-mumbai``)
  21946. *
  21947. * @_subsection: api/providers/thirdparty:INFURA [providers-infura]
  21948. */
  21949. const defaultProjectId = "84842078b09946638c03157f83405213";
  21950. function getHost$2(name) {
  21951. switch (name) {
  21952. case "mainnet":
  21953. return "mainnet.infura.io";
  21954. case "goerli":
  21955. return "goerli.infura.io";
  21956. case "sepolia":
  21957. return "sepolia.infura.io";
  21958. case "arbitrum":
  21959. return "arbitrum-mainnet.infura.io";
  21960. case "arbitrum-goerli":
  21961. return "arbitrum-goerli.infura.io";
  21962. case "arbitrum-sepolia":
  21963. return "arbitrum-sepolia.infura.io";
  21964. case "base":
  21965. return "base-mainnet.infura.io";
  21966. case "base-goerlia":
  21967. return "base-goerli.infura.io";
  21968. case "base-sepolia":
  21969. return "base-sepolia.infura.io";
  21970. case "bnb":
  21971. return "bnbsmartchain-mainnet.infura.io";
  21972. case "bnbt":
  21973. return "bnbsmartchain-testnet.infura.io";
  21974. case "linea":
  21975. return "linea-mainnet.infura.io";
  21976. case "linea-goerli":
  21977. return "linea-goerli.infura.io";
  21978. case "linea-sepolia":
  21979. return "linea-sepolia.infura.io";
  21980. case "matic":
  21981. return "polygon-mainnet.infura.io";
  21982. case "matic-amoy":
  21983. return "polygon-amoy.infura.io";
  21984. case "matic-mumbai":
  21985. return "polygon-mumbai.infura.io";
  21986. case "optimism":
  21987. return "optimism-mainnet.infura.io";
  21988. case "optimism-goerli":
  21989. return "optimism-goerli.infura.io";
  21990. case "optimism-sepolia":
  21991. return "optimism-sepolia.infura.io";
  21992. }
  21993. assertArgument(false, "unsupported network", "network", name);
  21994. }
  21995. /**
  21996. * The **InfuraWebSocketProvider** connects to the [[link-infura]]
  21997. * WebSocket end-points.
  21998. *
  21999. * By default, a highly-throttled API key is used, which is
  22000. * appropriate for quick prototypes and simple scripts. To
  22001. * gain access to an increased rate-limit, it is highly
  22002. * recommended to [sign up here](link-infura-signup).
  22003. */
  22004. class InfuraWebSocketProvider extends WebSocketProvider {
  22005. /**
  22006. * The Project ID for the INFURA connection.
  22007. */
  22008. projectId;
  22009. /**
  22010. * The Project Secret.
  22011. *
  22012. * If null, no authenticated requests are made. This should not
  22013. * be used outside of private contexts.
  22014. */
  22015. projectSecret;
  22016. /**
  22017. * Creates a new **InfuraWebSocketProvider**.
  22018. */
  22019. constructor(network, projectId) {
  22020. const provider = new InfuraProvider(network, projectId);
  22021. const req = provider._getConnection();
  22022. assert(!req.credentials, "INFURA WebSocket project secrets unsupported", "UNSUPPORTED_OPERATION", { operation: "InfuraProvider.getWebSocketProvider()" });
  22023. const url = req.url.replace(/^http/i, "ws").replace("/v3/", "/ws/v3/");
  22024. super(url, provider._network);
  22025. defineProperties(this, {
  22026. projectId: provider.projectId,
  22027. projectSecret: provider.projectSecret
  22028. });
  22029. }
  22030. isCommunityResource() {
  22031. return (this.projectId === defaultProjectId);
  22032. }
  22033. }
  22034. /**
  22035. * The **InfuraProvider** connects to the [[link-infura]]
  22036. * JSON-RPC end-points.
  22037. *
  22038. * By default, a highly-throttled API key is used, which is
  22039. * appropriate for quick prototypes and simple scripts. To
  22040. * gain access to an increased rate-limit, it is highly
  22041. * recommended to [sign up here](link-infura-signup).
  22042. */
  22043. class InfuraProvider extends JsonRpcProvider {
  22044. /**
  22045. * The Project ID for the INFURA connection.
  22046. */
  22047. projectId;
  22048. /**
  22049. * The Project Secret.
  22050. *
  22051. * If null, no authenticated requests are made. This should not
  22052. * be used outside of private contexts.
  22053. */
  22054. projectSecret;
  22055. /**
  22056. * Creates a new **InfuraProvider**.
  22057. */
  22058. constructor(_network, projectId, projectSecret) {
  22059. if (_network == null) {
  22060. _network = "mainnet";
  22061. }
  22062. const network = Network.from(_network);
  22063. if (projectId == null) {
  22064. projectId = defaultProjectId;
  22065. }
  22066. if (projectSecret == null) {
  22067. projectSecret = null;
  22068. }
  22069. const request = InfuraProvider.getRequest(network, projectId, projectSecret);
  22070. super(request, network, { staticNetwork: network });
  22071. defineProperties(this, { projectId, projectSecret });
  22072. }
  22073. _getProvider(chainId) {
  22074. try {
  22075. return new InfuraProvider(chainId, this.projectId, this.projectSecret);
  22076. }
  22077. catch (error) { }
  22078. return super._getProvider(chainId);
  22079. }
  22080. isCommunityResource() {
  22081. return (this.projectId === defaultProjectId);
  22082. }
  22083. /**
  22084. * Creates a new **InfuraWebSocketProvider**.
  22085. */
  22086. static getWebSocketProvider(network, projectId) {
  22087. return new InfuraWebSocketProvider(network, projectId);
  22088. }
  22089. /**
  22090. * Returns a prepared request for connecting to %%network%%
  22091. * with %%projectId%% and %%projectSecret%%.
  22092. */
  22093. static getRequest(network, projectId, projectSecret) {
  22094. if (projectId == null) {
  22095. projectId = defaultProjectId;
  22096. }
  22097. if (projectSecret == null) {
  22098. projectSecret = null;
  22099. }
  22100. const request = new FetchRequest(`https:/\/${getHost$2(network.name)}/v3/${projectId}`);
  22101. request.allowGzip = true;
  22102. if (projectSecret) {
  22103. request.setCredentials("", projectSecret);
  22104. }
  22105. if (projectId === defaultProjectId) {
  22106. request.retryFunc = async (request, response, attempt) => {
  22107. showThrottleMessage("InfuraProvider");
  22108. return true;
  22109. };
  22110. }
  22111. return request;
  22112. }
  22113. }
  22114. /**
  22115. * [[link-quicknode]] provides a third-party service for connecting to
  22116. * various blockchains over JSON-RPC.
  22117. *
  22118. * **Supported Networks**
  22119. *
  22120. * - Ethereum Mainnet (``mainnet``)
  22121. * - Goerli Testnet (``goerli``)
  22122. * - Sepolia Testnet (``sepolia``)
  22123. * - Holesky Testnet (``holesky``)
  22124. * - Arbitrum (``arbitrum``)
  22125. * - Arbitrum Goerli Testnet (``arbitrum-goerli``)
  22126. * - Arbitrum Sepolia Testnet (``arbitrum-sepolia``)
  22127. * - Base Mainnet (``base``);
  22128. * - Base Goerli Testnet (``base-goerli``);
  22129. * - Base Sepolia Testnet (``base-sepolia``);
  22130. * - BNB Smart Chain Mainnet (``bnb``)
  22131. * - BNB Smart Chain Testnet (``bnbt``)
  22132. * - Optimism (``optimism``)
  22133. * - Optimism Goerli Testnet (``optimism-goerli``)
  22134. * - Optimism Sepolia Testnet (``optimism-sepolia``)
  22135. * - Polygon (``matic``)
  22136. * - Polygon Mumbai Testnet (``matic-mumbai``)
  22137. *
  22138. * @_subsection: api/providers/thirdparty:QuickNode [providers-quicknode]
  22139. */
  22140. const defaultToken = "919b412a057b5e9c9b6dce193c5a60242d6efadb";
  22141. function getHost$1(name) {
  22142. switch (name) {
  22143. case "mainnet":
  22144. return "ethers.quiknode.pro";
  22145. case "goerli":
  22146. return "ethers.ethereum-goerli.quiknode.pro";
  22147. case "sepolia":
  22148. return "ethers.ethereum-sepolia.quiknode.pro";
  22149. case "holesky":
  22150. return "ethers.ethereum-holesky.quiknode.pro";
  22151. case "arbitrum":
  22152. return "ethers.arbitrum-mainnet.quiknode.pro";
  22153. case "arbitrum-goerli":
  22154. return "ethers.arbitrum-goerli.quiknode.pro";
  22155. case "arbitrum-sepolia":
  22156. return "ethers.arbitrum-sepolia.quiknode.pro";
  22157. case "base":
  22158. return "ethers.base-mainnet.quiknode.pro";
  22159. case "base-goerli":
  22160. return "ethers.base-goerli.quiknode.pro";
  22161. case "base-spolia":
  22162. return "ethers.base-sepolia.quiknode.pro";
  22163. case "bnb":
  22164. return "ethers.bsc.quiknode.pro";
  22165. case "bnbt":
  22166. return "ethers.bsc-testnet.quiknode.pro";
  22167. case "matic":
  22168. return "ethers.matic.quiknode.pro";
  22169. case "matic-mumbai":
  22170. return "ethers.matic-testnet.quiknode.pro";
  22171. case "optimism":
  22172. return "ethers.optimism.quiknode.pro";
  22173. case "optimism-goerli":
  22174. return "ethers.optimism-goerli.quiknode.pro";
  22175. case "optimism-sepolia":
  22176. return "ethers.optimism-sepolia.quiknode.pro";
  22177. case "xdai":
  22178. return "ethers.xdai.quiknode.pro";
  22179. }
  22180. assertArgument(false, "unsupported network", "network", name);
  22181. }
  22182. /*
  22183. @TODO:
  22184. These networks are not currently present in the Network
  22185. default included networks. Research them and ensure they
  22186. are EVM compatible and work with ethers
  22187. http://ethers.matic-amoy.quiknode.pro
  22188. http://ethers.avalanche-mainnet.quiknode.pro
  22189. http://ethers.avalanche-testnet.quiknode.pro
  22190. http://ethers.blast-sepolia.quiknode.pro
  22191. http://ethers.celo-mainnet.quiknode.pro
  22192. http://ethers.fantom.quiknode.pro
  22193. http://ethers.imx-demo.quiknode.pro
  22194. http://ethers.imx-mainnet.quiknode.pro
  22195. http://ethers.imx-testnet.quiknode.pro
  22196. http://ethers.near-mainnet.quiknode.pro
  22197. http://ethers.near-testnet.quiknode.pro
  22198. http://ethers.nova-mainnet.quiknode.pro
  22199. http://ethers.scroll-mainnet.quiknode.pro
  22200. http://ethers.scroll-testnet.quiknode.pro
  22201. http://ethers.tron-mainnet.quiknode.pro
  22202. http://ethers.zkevm-mainnet.quiknode.pro
  22203. http://ethers.zkevm-testnet.quiknode.pro
  22204. http://ethers.zksync-mainnet.quiknode.pro
  22205. http://ethers.zksync-testnet.quiknode.pro
  22206. */
  22207. /**
  22208. * The **QuickNodeProvider** connects to the [[link-quicknode]]
  22209. * JSON-RPC end-points.
  22210. *
  22211. * By default, a highly-throttled API token is used, which is
  22212. * appropriate for quick prototypes and simple scripts. To
  22213. * gain access to an increased rate-limit, it is highly
  22214. * recommended to [sign up here](link-quicknode).
  22215. */
  22216. class QuickNodeProvider extends JsonRpcProvider {
  22217. /**
  22218. * The API token.
  22219. */
  22220. token;
  22221. /**
  22222. * Creates a new **QuickNodeProvider**.
  22223. */
  22224. constructor(_network, token) {
  22225. if (_network == null) {
  22226. _network = "mainnet";
  22227. }
  22228. const network = Network.from(_network);
  22229. if (token == null) {
  22230. token = defaultToken;
  22231. }
  22232. const request = QuickNodeProvider.getRequest(network, token);
  22233. super(request, network, { staticNetwork: network });
  22234. defineProperties(this, { token });
  22235. }
  22236. _getProvider(chainId) {
  22237. try {
  22238. return new QuickNodeProvider(chainId, this.token);
  22239. }
  22240. catch (error) { }
  22241. return super._getProvider(chainId);
  22242. }
  22243. isCommunityResource() {
  22244. return (this.token === defaultToken);
  22245. }
  22246. /**
  22247. * Returns a new request prepared for %%network%% and the
  22248. * %%token%%.
  22249. */
  22250. static getRequest(network, token) {
  22251. if (token == null) {
  22252. token = defaultToken;
  22253. }
  22254. const request = new FetchRequest(`https:/\/${getHost$1(network.name)}/${token}`);
  22255. request.allowGzip = true;
  22256. //if (projectSecret) { request.setCredentials("", projectSecret); }
  22257. if (token === defaultToken) {
  22258. request.retryFunc = async (request, response, attempt) => {
  22259. showThrottleMessage("QuickNodeProvider");
  22260. return true;
  22261. };
  22262. }
  22263. return request;
  22264. }
  22265. }
  22266. /**
  22267. * A **FallbackProvider** provides resilience, security and performance
  22268. * in a way that is customizable and configurable.
  22269. *
  22270. * @_section: api/providers/fallback-provider:Fallback Provider [about-fallback-provider]
  22271. */
  22272. const BN_1 = BigInt("1");
  22273. const BN_2 = BigInt("2");
  22274. function shuffle(array) {
  22275. for (let i = array.length - 1; i > 0; i--) {
  22276. const j = Math.floor(Math.random() * (i + 1));
  22277. const tmp = array[i];
  22278. array[i] = array[j];
  22279. array[j] = tmp;
  22280. }
  22281. }
  22282. function stall$2(duration) {
  22283. return new Promise((resolve) => { setTimeout(resolve, duration); });
  22284. }
  22285. function getTime() { return (new Date()).getTime(); }
  22286. function stringify(value) {
  22287. return JSON.stringify(value, (key, value) => {
  22288. if (typeof (value) === "bigint") {
  22289. return { type: "bigint", value: value.toString() };
  22290. }
  22291. return value;
  22292. });
  22293. }
  22294. const defaultConfig = { stallTimeout: 400, priority: 1, weight: 1 };
  22295. const defaultState = {
  22296. blockNumber: -2, requests: 0, lateResponses: 0, errorResponses: 0,
  22297. outOfSync: -1, unsupportedEvents: 0, rollingDuration: 0, score: 0,
  22298. _network: null, _updateNumber: null, _totalTime: 0,
  22299. _lastFatalError: null, _lastFatalErrorTimestamp: 0
  22300. };
  22301. async function waitForSync(config, blockNumber) {
  22302. while (config.blockNumber < 0 || config.blockNumber < blockNumber) {
  22303. if (!config._updateNumber) {
  22304. config._updateNumber = (async () => {
  22305. try {
  22306. const blockNumber = await config.provider.getBlockNumber();
  22307. if (blockNumber > config.blockNumber) {
  22308. config.blockNumber = blockNumber;
  22309. }
  22310. }
  22311. catch (error) {
  22312. config.blockNumber = -2;
  22313. config._lastFatalError = error;
  22314. config._lastFatalErrorTimestamp = getTime();
  22315. }
  22316. config._updateNumber = null;
  22317. })();
  22318. }
  22319. await config._updateNumber;
  22320. config.outOfSync++;
  22321. if (config._lastFatalError) {
  22322. break;
  22323. }
  22324. }
  22325. }
  22326. function _normalize(value) {
  22327. if (value == null) {
  22328. return "null";
  22329. }
  22330. if (Array.isArray(value)) {
  22331. return "[" + (value.map(_normalize)).join(",") + "]";
  22332. }
  22333. if (typeof (value) === "object" && typeof (value.toJSON) === "function") {
  22334. return _normalize(value.toJSON());
  22335. }
  22336. switch (typeof (value)) {
  22337. case "boolean":
  22338. case "symbol":
  22339. return value.toString();
  22340. case "bigint":
  22341. case "number":
  22342. return BigInt(value).toString();
  22343. case "string":
  22344. return JSON.stringify(value);
  22345. case "object": {
  22346. const keys = Object.keys(value);
  22347. keys.sort();
  22348. return "{" + keys.map((k) => `${JSON.stringify(k)}:${_normalize(value[k])}`).join(",") + "}";
  22349. }
  22350. }
  22351. console.log("Could not serialize", value);
  22352. throw new Error("Hmm...");
  22353. }
  22354. function normalizeResult(value) {
  22355. if ("error" in value) {
  22356. const error = value.error;
  22357. return { tag: _normalize(error), value: error };
  22358. }
  22359. const result = value.result;
  22360. return { tag: _normalize(result), value: result };
  22361. }
  22362. // This strategy picks the highest weight result, as long as the weight is
  22363. // equal to or greater than quorum
  22364. function checkQuorum(quorum, results) {
  22365. const tally = new Map();
  22366. for (const { value, tag, weight } of results) {
  22367. const t = tally.get(tag) || { value, weight: 0 };
  22368. t.weight += weight;
  22369. tally.set(tag, t);
  22370. }
  22371. let best = null;
  22372. for (const r of tally.values()) {
  22373. if (r.weight >= quorum && (!best || r.weight > best.weight)) {
  22374. best = r;
  22375. }
  22376. }
  22377. if (best) {
  22378. return best.value;
  22379. }
  22380. return undefined;
  22381. }
  22382. function getMedian(quorum, results) {
  22383. let resultWeight = 0;
  22384. const errorMap = new Map();
  22385. let bestError = null;
  22386. const values = [];
  22387. for (const { value, tag, weight } of results) {
  22388. if (value instanceof Error) {
  22389. const e = errorMap.get(tag) || { value, weight: 0 };
  22390. e.weight += weight;
  22391. errorMap.set(tag, e);
  22392. if (bestError == null || e.weight > bestError.weight) {
  22393. bestError = e;
  22394. }
  22395. }
  22396. else {
  22397. values.push(BigInt(value));
  22398. resultWeight += weight;
  22399. }
  22400. }
  22401. if (resultWeight < quorum) {
  22402. // We have quorum for an error
  22403. if (bestError && bestError.weight >= quorum) {
  22404. return bestError.value;
  22405. }
  22406. // We do not have quorum for a result
  22407. return undefined;
  22408. }
  22409. // Get the sorted values
  22410. values.sort((a, b) => ((a < b) ? -1 : (b > a) ? 1 : 0));
  22411. const mid = Math.floor(values.length / 2);
  22412. // Odd-length; take the middle value
  22413. if (values.length % 2) {
  22414. return values[mid];
  22415. }
  22416. // Even length; take the ceiling of the mean of the center two values
  22417. return (values[mid - 1] + values[mid] + BN_1) / BN_2;
  22418. }
  22419. function getAnyResult(quorum, results) {
  22420. // If any value or error meets quorum, that is our preferred result
  22421. const result = checkQuorum(quorum, results);
  22422. if (result !== undefined) {
  22423. return result;
  22424. }
  22425. // Otherwise, do we have any result?
  22426. for (const r of results) {
  22427. if (r.value) {
  22428. return r.value;
  22429. }
  22430. }
  22431. // Nope!
  22432. return undefined;
  22433. }
  22434. function getFuzzyMode(quorum, results) {
  22435. if (quorum === 1) {
  22436. return getNumber(getMedian(quorum, results), "%internal");
  22437. }
  22438. const tally = new Map();
  22439. const add = (result, weight) => {
  22440. const t = tally.get(result) || { result, weight: 0 };
  22441. t.weight += weight;
  22442. tally.set(result, t);
  22443. };
  22444. for (const { weight, value } of results) {
  22445. const r = getNumber(value);
  22446. add(r - 1, weight);
  22447. add(r, weight);
  22448. add(r + 1, weight);
  22449. }
  22450. let bestWeight = 0;
  22451. let bestResult = undefined;
  22452. for (const { weight, result } of tally.values()) {
  22453. // Use this result, if this result meets quorum and has either:
  22454. // - a better weight
  22455. // - or equal weight, but the result is larger
  22456. if (weight >= quorum && (weight > bestWeight || (bestResult != null && weight === bestWeight && result > bestResult))) {
  22457. bestWeight = weight;
  22458. bestResult = result;
  22459. }
  22460. }
  22461. return bestResult;
  22462. }
  22463. /**
  22464. * A **FallbackProvider** manages several [[Providers]] providing
  22465. * resilience by switching between slow or misbehaving nodes, security
  22466. * by requiring multiple backends to aggree and performance by allowing
  22467. * faster backends to respond earlier.
  22468. *
  22469. */
  22470. class FallbackProvider extends AbstractProvider {
  22471. /**
  22472. * The number of backends that must agree on a value before it is
  22473. * accpeted.
  22474. */
  22475. quorum;
  22476. /**
  22477. * @_ignore:
  22478. */
  22479. eventQuorum;
  22480. /**
  22481. * @_ignore:
  22482. */
  22483. eventWorkers;
  22484. #configs;
  22485. #height;
  22486. #initialSyncPromise;
  22487. /**
  22488. * Creates a new **FallbackProvider** with %%providers%% connected to
  22489. * %%network%%.
  22490. *
  22491. * If a [[Provider]] is included in %%providers%%, defaults are used
  22492. * for the configuration.
  22493. */
  22494. constructor(providers, network, options) {
  22495. super(network, options);
  22496. this.#configs = providers.map((p) => {
  22497. if (p instanceof AbstractProvider) {
  22498. return Object.assign({ provider: p }, defaultConfig, defaultState);
  22499. }
  22500. else {
  22501. return Object.assign({}, defaultConfig, p, defaultState);
  22502. }
  22503. });
  22504. this.#height = -2;
  22505. this.#initialSyncPromise = null;
  22506. if (options && options.quorum != null) {
  22507. this.quorum = options.quorum;
  22508. }
  22509. else {
  22510. this.quorum = Math.ceil(this.#configs.reduce((accum, config) => {
  22511. accum += config.weight;
  22512. return accum;
  22513. }, 0) / 2);
  22514. }
  22515. this.eventQuorum = 1;
  22516. this.eventWorkers = 1;
  22517. assertArgument(this.quorum <= this.#configs.reduce((a, c) => (a + c.weight), 0), "quorum exceed provider weight", "quorum", this.quorum);
  22518. }
  22519. get providerConfigs() {
  22520. return this.#configs.map((c) => {
  22521. const result = Object.assign({}, c);
  22522. for (const key in result) {
  22523. if (key[0] === "_") {
  22524. delete result[key];
  22525. }
  22526. }
  22527. return result;
  22528. });
  22529. }
  22530. async _detectNetwork() {
  22531. return Network.from(getBigInt(await this._perform({ method: "chainId" })));
  22532. }
  22533. // @TODO: Add support to select providers to be the event subscriber
  22534. //_getSubscriber(sub: Subscription): Subscriber {
  22535. // throw new Error("@TODO");
  22536. //}
  22537. /**
  22538. * Transforms a %%req%% into the correct method call on %%provider%%.
  22539. */
  22540. async _translatePerform(provider, req) {
  22541. switch (req.method) {
  22542. case "broadcastTransaction":
  22543. return await provider.broadcastTransaction(req.signedTransaction);
  22544. case "call":
  22545. return await provider.call(Object.assign({}, req.transaction, { blockTag: req.blockTag }));
  22546. case "chainId":
  22547. return (await provider.getNetwork()).chainId;
  22548. case "estimateGas":
  22549. return await provider.estimateGas(req.transaction);
  22550. case "getBalance":
  22551. return await provider.getBalance(req.address, req.blockTag);
  22552. case "getBlock": {
  22553. const block = ("blockHash" in req) ? req.blockHash : req.blockTag;
  22554. return await provider.getBlock(block, req.includeTransactions);
  22555. }
  22556. case "getBlockNumber":
  22557. return await provider.getBlockNumber();
  22558. case "getCode":
  22559. return await provider.getCode(req.address, req.blockTag);
  22560. case "getGasPrice":
  22561. return (await provider.getFeeData()).gasPrice;
  22562. case "getPriorityFee":
  22563. return (await provider.getFeeData()).maxPriorityFeePerGas;
  22564. case "getLogs":
  22565. return await provider.getLogs(req.filter);
  22566. case "getStorage":
  22567. return await provider.getStorage(req.address, req.position, req.blockTag);
  22568. case "getTransaction":
  22569. return await provider.getTransaction(req.hash);
  22570. case "getTransactionCount":
  22571. return await provider.getTransactionCount(req.address, req.blockTag);
  22572. case "getTransactionReceipt":
  22573. return await provider.getTransactionReceipt(req.hash);
  22574. case "getTransactionResult":
  22575. return await provider.getTransactionResult(req.hash);
  22576. }
  22577. }
  22578. // Grab the next (random) config that is not already part of
  22579. // the running set
  22580. #getNextConfig(running) {
  22581. // @TODO: Maybe do a check here to favour (heavily) providers that
  22582. // do not require waitForSync and disfavour providers that
  22583. // seem down-ish or are behaving slowly
  22584. const configs = Array.from(running).map((r) => r.config);
  22585. // Shuffle the states, sorted by priority
  22586. const allConfigs = this.#configs.slice();
  22587. shuffle(allConfigs);
  22588. allConfigs.sort((a, b) => (a.priority - b.priority));
  22589. for (const config of allConfigs) {
  22590. if (config._lastFatalError) {
  22591. continue;
  22592. }
  22593. if (configs.indexOf(config) === -1) {
  22594. return config;
  22595. }
  22596. }
  22597. return null;
  22598. }
  22599. // Adds a new runner (if available) to running.
  22600. #addRunner(running, req) {
  22601. const config = this.#getNextConfig(running);
  22602. // No runners available
  22603. if (config == null) {
  22604. return null;
  22605. }
  22606. // Create a new runner
  22607. const runner = {
  22608. config, result: null, didBump: false,
  22609. perform: null, staller: null
  22610. };
  22611. const now = getTime();
  22612. // Start performing this operation
  22613. runner.perform = (async () => {
  22614. try {
  22615. config.requests++;
  22616. const result = await this._translatePerform(config.provider, req);
  22617. runner.result = { result };
  22618. }
  22619. catch (error) {
  22620. config.errorResponses++;
  22621. runner.result = { error };
  22622. }
  22623. const dt = (getTime() - now);
  22624. config._totalTime += dt;
  22625. config.rollingDuration = 0.95 * config.rollingDuration + 0.05 * dt;
  22626. runner.perform = null;
  22627. })();
  22628. // Start a staller; when this times out, it's time to force
  22629. // kicking off another runner because we are taking too long
  22630. runner.staller = (async () => {
  22631. await stall$2(config.stallTimeout);
  22632. runner.staller = null;
  22633. })();
  22634. running.add(runner);
  22635. return runner;
  22636. }
  22637. // Initializes the blockNumber and network for each runner and
  22638. // blocks until initialized
  22639. async #initialSync() {
  22640. let initialSync = this.#initialSyncPromise;
  22641. if (!initialSync) {
  22642. const promises = [];
  22643. this.#configs.forEach((config) => {
  22644. promises.push((async () => {
  22645. await waitForSync(config, 0);
  22646. if (!config._lastFatalError) {
  22647. config._network = await config.provider.getNetwork();
  22648. }
  22649. })());
  22650. });
  22651. this.#initialSyncPromise = initialSync = (async () => {
  22652. // Wait for all providers to have a block number and network
  22653. await Promise.all(promises);
  22654. // Check all the networks match
  22655. let chainId = null;
  22656. for (const config of this.#configs) {
  22657. if (config._lastFatalError) {
  22658. continue;
  22659. }
  22660. const network = (config._network);
  22661. if (chainId == null) {
  22662. chainId = network.chainId;
  22663. }
  22664. else if (network.chainId !== chainId) {
  22665. assert(false, "cannot mix providers on different networks", "UNSUPPORTED_OPERATION", {
  22666. operation: "new FallbackProvider"
  22667. });
  22668. }
  22669. }
  22670. })();
  22671. }
  22672. await initialSync;
  22673. }
  22674. async #checkQuorum(running, req) {
  22675. // Get all the result objects
  22676. const results = [];
  22677. for (const runner of running) {
  22678. if (runner.result != null) {
  22679. const { tag, value } = normalizeResult(runner.result);
  22680. results.push({ tag, value, weight: runner.config.weight });
  22681. }
  22682. }
  22683. // Are there enough results to event meet quorum?
  22684. if (results.reduce((a, r) => (a + r.weight), 0) < this.quorum) {
  22685. return undefined;
  22686. }
  22687. switch (req.method) {
  22688. case "getBlockNumber": {
  22689. // We need to get the bootstrap block height
  22690. if (this.#height === -2) {
  22691. this.#height = Math.ceil(getNumber(getMedian(this.quorum, this.#configs.filter((c) => (!c._lastFatalError)).map((c) => ({
  22692. value: c.blockNumber,
  22693. tag: getNumber(c.blockNumber).toString(),
  22694. weight: c.weight
  22695. })))));
  22696. }
  22697. // Find the mode across all the providers, allowing for
  22698. // a little drift between block heights
  22699. const mode = getFuzzyMode(this.quorum, results);
  22700. if (mode === undefined) {
  22701. return undefined;
  22702. }
  22703. if (mode > this.#height) {
  22704. this.#height = mode;
  22705. }
  22706. return this.#height;
  22707. }
  22708. case "getGasPrice":
  22709. case "getPriorityFee":
  22710. case "estimateGas":
  22711. return getMedian(this.quorum, results);
  22712. case "getBlock":
  22713. // Pending blocks are in the mempool and already
  22714. // quite untrustworthy; just grab anything
  22715. if ("blockTag" in req && req.blockTag === "pending") {
  22716. return getAnyResult(this.quorum, results);
  22717. }
  22718. return checkQuorum(this.quorum, results);
  22719. case "call":
  22720. case "chainId":
  22721. case "getBalance":
  22722. case "getTransactionCount":
  22723. case "getCode":
  22724. case "getStorage":
  22725. case "getTransaction":
  22726. case "getTransactionReceipt":
  22727. case "getLogs":
  22728. return checkQuorum(this.quorum, results);
  22729. case "broadcastTransaction":
  22730. return getAnyResult(this.quorum, results);
  22731. }
  22732. assert(false, "unsupported method", "UNSUPPORTED_OPERATION", {
  22733. operation: `_perform(${stringify(req.method)})`
  22734. });
  22735. }
  22736. async #waitForQuorum(running, req) {
  22737. if (running.size === 0) {
  22738. throw new Error("no runners?!");
  22739. }
  22740. // Any promises that are interesting to watch for; an expired stall
  22741. // or a successful perform
  22742. const interesting = [];
  22743. let newRunners = 0;
  22744. for (const runner of running) {
  22745. // No responses, yet; keep an eye on it
  22746. if (runner.perform) {
  22747. interesting.push(runner.perform);
  22748. }
  22749. // Still stalling...
  22750. if (runner.staller) {
  22751. interesting.push(runner.staller);
  22752. continue;
  22753. }
  22754. // This runner has already triggered another runner
  22755. if (runner.didBump) {
  22756. continue;
  22757. }
  22758. // Got a response (result or error) or stalled; kick off another runner
  22759. runner.didBump = true;
  22760. newRunners++;
  22761. }
  22762. // Check if we have reached quorum on a result (or error)
  22763. const value = await this.#checkQuorum(running, req);
  22764. if (value !== undefined) {
  22765. if (value instanceof Error) {
  22766. throw value;
  22767. }
  22768. return value;
  22769. }
  22770. // Add any new runners, because a staller timed out or a result
  22771. // or error response came in.
  22772. for (let i = 0; i < newRunners; i++) {
  22773. this.#addRunner(running, req);
  22774. }
  22775. // All providers have returned, and we have no result
  22776. assert(interesting.length > 0, "quorum not met", "SERVER_ERROR", {
  22777. request: "%sub-requests",
  22778. info: { request: req, results: Array.from(running).map((r) => stringify(r.result)) }
  22779. });
  22780. // Wait for someone to either complete its perform or stall out
  22781. await Promise.race(interesting);
  22782. // This is recursive, but at worst case the depth is 2x the
  22783. // number of providers (each has a perform and a staller)
  22784. return await this.#waitForQuorum(running, req);
  22785. }
  22786. async _perform(req) {
  22787. // Broadcasting a transaction is rare (ish) and already incurs
  22788. // a cost on the user, so spamming is safe-ish. Just send it to
  22789. // every backend.
  22790. if (req.method === "broadcastTransaction") {
  22791. // Once any broadcast provides a positive result, use it. No
  22792. // need to wait for anyone else
  22793. const results = this.#configs.map((c) => null);
  22794. const broadcasts = this.#configs.map(async ({ provider, weight }, index) => {
  22795. try {
  22796. const result = await provider._perform(req);
  22797. results[index] = Object.assign(normalizeResult({ result }), { weight });
  22798. }
  22799. catch (error) {
  22800. results[index] = Object.assign(normalizeResult({ error }), { weight });
  22801. }
  22802. });
  22803. // As each promise finishes...
  22804. while (true) {
  22805. // Check for a valid broadcast result
  22806. const done = results.filter((r) => (r != null));
  22807. for (const { value } of done) {
  22808. if (!(value instanceof Error)) {
  22809. return value;
  22810. }
  22811. }
  22812. // Check for a legit broadcast error (one which we cannot
  22813. // recover from; some nodes may return the following red
  22814. // herring events:
  22815. // - alredy seend (UNKNOWN_ERROR)
  22816. // - NONCE_EXPIRED
  22817. // - REPLACEMENT_UNDERPRICED
  22818. const result = checkQuorum(this.quorum, results.filter((r) => (r != null)));
  22819. if (isError(result, "INSUFFICIENT_FUNDS")) {
  22820. throw result;
  22821. }
  22822. // Kick off the next provider (if any)
  22823. const waiting = broadcasts.filter((b, i) => (results[i] == null));
  22824. if (waiting.length === 0) {
  22825. break;
  22826. }
  22827. await Promise.race(waiting);
  22828. }
  22829. // Use standard quorum results; any result was returned above,
  22830. // so this will find any error that met quorum if any
  22831. const result = getAnyResult(this.quorum, results);
  22832. assert(result !== undefined, "problem multi-broadcasting", "SERVER_ERROR", {
  22833. request: "%sub-requests",
  22834. info: { request: req, results: results.map(stringify) }
  22835. });
  22836. if (result instanceof Error) {
  22837. throw result;
  22838. }
  22839. return result;
  22840. }
  22841. await this.#initialSync();
  22842. // Bootstrap enough runners to meet quorum
  22843. const running = new Set();
  22844. let inflightQuorum = 0;
  22845. while (true) {
  22846. const runner = this.#addRunner(running, req);
  22847. if (runner == null) {
  22848. break;
  22849. }
  22850. inflightQuorum += runner.config.weight;
  22851. if (inflightQuorum >= this.quorum) {
  22852. break;
  22853. }
  22854. }
  22855. const result = await this.#waitForQuorum(running, req);
  22856. // Track requests sent to a provider that are still
  22857. // outstanding after quorum has been otherwise found
  22858. for (const runner of running) {
  22859. if (runner.perform && runner.result == null) {
  22860. runner.config.lateResponses++;
  22861. }
  22862. }
  22863. return result;
  22864. }
  22865. async destroy() {
  22866. for (const { provider } of this.#configs) {
  22867. provider.destroy();
  22868. }
  22869. super.destroy();
  22870. }
  22871. }
  22872. function isWebSocketLike(value) {
  22873. return (value && typeof (value.send) === "function" &&
  22874. typeof (value.close) === "function");
  22875. }
  22876. const Testnets = "goerli kovan sepolia classicKotti optimism-goerli arbitrum-goerli matic-mumbai bnbt".split(" ");
  22877. /**
  22878. * Returns a default provider for %%network%%.
  22879. *
  22880. * If %%network%% is a [[WebSocketLike]] or string that begins with
  22881. * ``"ws:"`` or ``"wss:"``, a [[WebSocketProvider]] is returned backed
  22882. * by that WebSocket or URL.
  22883. *
  22884. * If %%network%% is a string that begins with ``"HTTP:"`` or ``"HTTPS:"``,
  22885. * a [[JsonRpcProvider]] is returned connected to that URL.
  22886. *
  22887. * Otherwise, a default provider is created backed by well-known public
  22888. * Web3 backends (such as [[link-infura]]) using community-provided API
  22889. * keys.
  22890. *
  22891. * The %%options%% allows specifying custom API keys per backend (setting
  22892. * an API key to ``"-"`` will omit that provider) and ``options.exclusive``
  22893. * can be set to either a backend name or and array of backend names, which
  22894. * will whitelist **only** those backends.
  22895. *
  22896. * Current backend strings supported are:
  22897. * - ``"alchemy"``
  22898. * - ``"ankr"``
  22899. * - ``"cloudflare"``
  22900. * - ``"chainstack"``
  22901. * - ``"etherscan"``
  22902. * - ``"infura"``
  22903. * - ``"publicPolygon"``
  22904. * - ``"quicknode"``
  22905. *
  22906. * @example:
  22907. * // Connect to a local Geth node
  22908. * provider = getDefaultProvider("http://localhost:8545/");
  22909. *
  22910. * // Connect to Ethereum mainnet with any current and future
  22911. * // third-party services available
  22912. * provider = getDefaultProvider("mainnet");
  22913. *
  22914. * // Connect to Polygon, but only allow Etherscan and
  22915. * // INFURA and use "MY_API_KEY" in calls to Etherscan.
  22916. * provider = getDefaultProvider("matic", {
  22917. * etherscan: "MY_API_KEY",
  22918. * exclusive: [ "etherscan", "infura" ]
  22919. * });
  22920. */
  22921. function getDefaultProvider(network, options) {
  22922. if (options == null) {
  22923. options = {};
  22924. }
  22925. const allowService = (name) => {
  22926. if (options[name] === "-") {
  22927. return false;
  22928. }
  22929. if (typeof (options.exclusive) === "string") {
  22930. return (name === options.exclusive);
  22931. }
  22932. if (Array.isArray(options.exclusive)) {
  22933. return (options.exclusive.indexOf(name) !== -1);
  22934. }
  22935. return true;
  22936. };
  22937. if (typeof (network) === "string" && network.match(/^https?:/)) {
  22938. return new JsonRpcProvider(network);
  22939. }
  22940. if (typeof (network) === "string" && network.match(/^wss?:/) || isWebSocketLike(network)) {
  22941. return new WebSocketProvider(network);
  22942. }
  22943. // Get the network and name, if possible
  22944. let staticNetwork = null;
  22945. try {
  22946. staticNetwork = Network.from(network);
  22947. }
  22948. catch (error) { }
  22949. const providers = [];
  22950. if (allowService("publicPolygon") && staticNetwork) {
  22951. if (staticNetwork.name === "matic") {
  22952. providers.push(new JsonRpcProvider("https:/\/polygon-rpc.com/", staticNetwork, { staticNetwork }));
  22953. }
  22954. else if (staticNetwork.name === "matic-amoy") {
  22955. providers.push(new JsonRpcProvider("https:/\/rpc-amoy.polygon.technology/", staticNetwork, { staticNetwork }));
  22956. }
  22957. }
  22958. if (allowService("alchemy")) {
  22959. try {
  22960. providers.push(new AlchemyProvider(network, options.alchemy));
  22961. }
  22962. catch (error) { }
  22963. }
  22964. if (allowService("ankr") && options.ankr != null) {
  22965. try {
  22966. providers.push(new AnkrProvider(network, options.ankr));
  22967. }
  22968. catch (error) { }
  22969. }
  22970. if (allowService("chainstack")) {
  22971. try {
  22972. providers.push(new ChainstackProvider(network, options.chainstack));
  22973. }
  22974. catch (error) { }
  22975. }
  22976. if (allowService("cloudflare")) {
  22977. try {
  22978. providers.push(new CloudflareProvider(network));
  22979. }
  22980. catch (error) { }
  22981. }
  22982. if (allowService("etherscan")) {
  22983. try {
  22984. providers.push(new EtherscanProvider(network, options.etherscan));
  22985. }
  22986. catch (error) { }
  22987. }
  22988. if (allowService("infura")) {
  22989. try {
  22990. let projectId = options.infura;
  22991. let projectSecret = undefined;
  22992. if (typeof (projectId) === "object") {
  22993. projectSecret = projectId.projectSecret;
  22994. projectId = projectId.projectId;
  22995. }
  22996. providers.push(new InfuraProvider(network, projectId, projectSecret));
  22997. }
  22998. catch (error) { }
  22999. }
  23000. /*
  23001. if (options.pocket !== "-") {
  23002. try {
  23003. let appId = options.pocket;
  23004. let secretKey: undefined | string = undefined;
  23005. let loadBalancer: undefined | boolean = undefined;
  23006. if (typeof(appId) === "object") {
  23007. loadBalancer = !!appId.loadBalancer;
  23008. secretKey = appId.secretKey;
  23009. appId = appId.appId;
  23010. }
  23011. providers.push(new PocketProvider(network, appId, secretKey, loadBalancer));
  23012. } catch (error) { console.log(error); }
  23013. }
  23014. */
  23015. if (allowService("quicknode")) {
  23016. try {
  23017. let token = options.quicknode;
  23018. providers.push(new QuickNodeProvider(network, token));
  23019. }
  23020. catch (error) { }
  23021. }
  23022. assert(providers.length, "unsupported default network", "UNSUPPORTED_OPERATION", {
  23023. operation: "getDefaultProvider"
  23024. });
  23025. // No need for a FallbackProvider
  23026. if (providers.length === 1) {
  23027. return providers[0];
  23028. }
  23029. // We use the floor because public third-party providers can be unreliable,
  23030. // so a low number of providers with a large quorum will fail too often
  23031. let quorum = Math.floor(providers.length / 2);
  23032. if (quorum > 2) {
  23033. quorum = 2;
  23034. }
  23035. // Testnets don't need as strong a security gaurantee and speed is
  23036. // more useful during testing
  23037. if (staticNetwork && Testnets.indexOf(staticNetwork.name) !== -1) {
  23038. quorum = 1;
  23039. }
  23040. // Provided override qorum takes priority
  23041. if (options && options.quorum) {
  23042. quorum = options.quorum;
  23043. }
  23044. return new FallbackProvider(providers, undefined, { quorum });
  23045. }
  23046. /**
  23047. * A **NonceManager** wraps another [[Signer]] and automatically manages
  23048. * the nonce, ensuring serialized and sequential nonces are used during
  23049. * transaction.
  23050. */
  23051. class NonceManager extends AbstractSigner {
  23052. /**
  23053. * The Signer being managed.
  23054. */
  23055. signer;
  23056. #noncePromise;
  23057. #delta;
  23058. /**
  23059. * Creates a new **NonceManager** to manage %%signer%%.
  23060. */
  23061. constructor(signer) {
  23062. super(signer.provider);
  23063. defineProperties(this, { signer });
  23064. this.#noncePromise = null;
  23065. this.#delta = 0;
  23066. }
  23067. async getAddress() {
  23068. return this.signer.getAddress();
  23069. }
  23070. connect(provider) {
  23071. return new NonceManager(this.signer.connect(provider));
  23072. }
  23073. async getNonce(blockTag) {
  23074. if (blockTag === "pending") {
  23075. if (this.#noncePromise == null) {
  23076. this.#noncePromise = super.getNonce("pending");
  23077. }
  23078. const delta = this.#delta;
  23079. return (await this.#noncePromise) + delta;
  23080. }
  23081. return super.getNonce(blockTag);
  23082. }
  23083. /**
  23084. * Manually increment the nonce. This may be useful when managng
  23085. * offline transactions.
  23086. */
  23087. increment() {
  23088. this.#delta++;
  23089. }
  23090. /**
  23091. * Resets the nonce, causing the **NonceManager** to reload the current
  23092. * nonce from the blockchain on the next transaction.
  23093. */
  23094. reset() {
  23095. this.#delta = 0;
  23096. this.#noncePromise = null;
  23097. }
  23098. async sendTransaction(tx) {
  23099. const noncePromise = this.getNonce("pending");
  23100. this.increment();
  23101. tx = await this.signer.populateTransaction(tx);
  23102. tx.nonce = await noncePromise;
  23103. // @TODO: Maybe handle interesting/recoverable errors?
  23104. // Like don't increment if the tx was certainly not sent
  23105. return await this.signer.sendTransaction(tx);
  23106. }
  23107. signTransaction(tx) {
  23108. return this.signer.signTransaction(tx);
  23109. }
  23110. signMessage(message) {
  23111. return this.signer.signMessage(message);
  23112. }
  23113. signTypedData(domain, types, value) {
  23114. return this.signer.signTypedData(domain, types, value);
  23115. }
  23116. }
  23117. /**
  23118. * A **BrowserProvider** is intended to wrap an injected provider which
  23119. * adheres to the [[link-eip-1193]] standard, which most (if not all)
  23120. * currently do.
  23121. */
  23122. class BrowserProvider extends JsonRpcApiPollingProvider {
  23123. #request;
  23124. /**
  23125. * Connect to the %%ethereum%% provider, optionally forcing the
  23126. * %%network%%.
  23127. */
  23128. constructor(ethereum, network, _options) {
  23129. // Copy the options
  23130. const options = Object.assign({}, ((_options != null) ? _options : {}), { batchMaxCount: 1 });
  23131. assertArgument(ethereum && ethereum.request, "invalid EIP-1193 provider", "ethereum", ethereum);
  23132. super(network, options);
  23133. this.#request = async (method, params) => {
  23134. const payload = { method, params };
  23135. this.emit("debug", { action: "sendEip1193Request", payload });
  23136. try {
  23137. const result = await ethereum.request(payload);
  23138. this.emit("debug", { action: "receiveEip1193Result", result });
  23139. return result;
  23140. }
  23141. catch (e) {
  23142. const error = new Error(e.message);
  23143. error.code = e.code;
  23144. error.data = e.data;
  23145. error.payload = payload;
  23146. this.emit("debug", { action: "receiveEip1193Error", error });
  23147. throw error;
  23148. }
  23149. };
  23150. }
  23151. async send(method, params) {
  23152. await this._start();
  23153. return await super.send(method, params);
  23154. }
  23155. async _send(payload) {
  23156. assertArgument(!Array.isArray(payload), "EIP-1193 does not support batch request", "payload", payload);
  23157. try {
  23158. const result = await this.#request(payload.method, payload.params || []);
  23159. return [{ id: payload.id, result }];
  23160. }
  23161. catch (e) {
  23162. return [{
  23163. id: payload.id,
  23164. error: { code: e.code, data: e.data, message: e.message }
  23165. }];
  23166. }
  23167. }
  23168. getRpcError(payload, error) {
  23169. error = JSON.parse(JSON.stringify(error));
  23170. // EIP-1193 gives us some machine-readable error codes, so rewrite
  23171. // them into
  23172. switch (error.error.code || -1) {
  23173. case 4001:
  23174. error.error.message = `ethers-user-denied: ${error.error.message}`;
  23175. break;
  23176. case 4200:
  23177. error.error.message = `ethers-unsupported: ${error.error.message}`;
  23178. break;
  23179. }
  23180. return super.getRpcError(payload, error);
  23181. }
  23182. /**
  23183. * Resolves to ``true`` if the provider manages the %%address%%.
  23184. */
  23185. async hasSigner(address) {
  23186. if (address == null) {
  23187. address = 0;
  23188. }
  23189. const accounts = await this.send("eth_accounts", []);
  23190. if (typeof (address) === "number") {
  23191. return (accounts.length > address);
  23192. }
  23193. address = address.toLowerCase();
  23194. return accounts.filter((a) => (a.toLowerCase() === address)).length !== 0;
  23195. }
  23196. async getSigner(address) {
  23197. if (address == null) {
  23198. address = 0;
  23199. }
  23200. if (!(await this.hasSigner(address))) {
  23201. try {
  23202. //const resp =
  23203. await this.#request("eth_requestAccounts", []);
  23204. //console.log("RESP", resp);
  23205. }
  23206. catch (error) {
  23207. const payload = error.payload;
  23208. throw this.getRpcError(payload, { id: payload.id, error });
  23209. }
  23210. }
  23211. return await super.getSigner(address);
  23212. }
  23213. }
  23214. /**
  23215. * [[link-pocket]] provides a third-party service for connecting to
  23216. * various blockchains over JSON-RPC.
  23217. *
  23218. * **Supported Networks**
  23219. *
  23220. * - Ethereum Mainnet (``mainnet``)
  23221. * - Goerli Testnet (``goerli``)
  23222. * - Polygon (``matic``)
  23223. * - Arbitrum (``arbitrum``)
  23224. *
  23225. * @_subsection: api/providers/thirdparty:Pocket [providers-pocket]
  23226. */
  23227. const defaultApplicationId = "62e1ad51b37b8e00394bda3b";
  23228. function getHost(name) {
  23229. switch (name) {
  23230. case "mainnet":
  23231. return "eth-mainnet.gateway.pokt.network";
  23232. case "goerli":
  23233. return "eth-goerli.gateway.pokt.network";
  23234. case "matic":
  23235. return "poly-mainnet.gateway.pokt.network";
  23236. case "matic-mumbai":
  23237. return "polygon-mumbai-rpc.gateway.pokt.network";
  23238. }
  23239. assertArgument(false, "unsupported network", "network", name);
  23240. }
  23241. /**
  23242. * The **PocketProvider** connects to the [[link-pocket]]
  23243. * JSON-RPC end-points.
  23244. *
  23245. * By default, a highly-throttled API key is used, which is
  23246. * appropriate for quick prototypes and simple scripts. To
  23247. * gain access to an increased rate-limit, it is highly
  23248. * recommended to [sign up here](link-pocket-signup).
  23249. */
  23250. class PocketProvider extends JsonRpcProvider {
  23251. /**
  23252. * The Application ID for the Pocket connection.
  23253. */
  23254. applicationId;
  23255. /**
  23256. * The Application Secret for making authenticated requests
  23257. * to the Pocket connection.
  23258. */
  23259. applicationSecret;
  23260. /**
  23261. * Create a new **PocketProvider**.
  23262. *
  23263. * By default connecting to ``mainnet`` with a highly throttled
  23264. * API key.
  23265. */
  23266. constructor(_network, applicationId, applicationSecret) {
  23267. if (_network == null) {
  23268. _network = "mainnet";
  23269. }
  23270. const network = Network.from(_network);
  23271. if (applicationId == null) {
  23272. applicationId = defaultApplicationId;
  23273. }
  23274. if (applicationSecret == null) {
  23275. applicationSecret = null;
  23276. }
  23277. const options = { staticNetwork: network };
  23278. const request = PocketProvider.getRequest(network, applicationId, applicationSecret);
  23279. super(request, network, options);
  23280. defineProperties(this, { applicationId, applicationSecret });
  23281. }
  23282. _getProvider(chainId) {
  23283. try {
  23284. return new PocketProvider(chainId, this.applicationId, this.applicationSecret);
  23285. }
  23286. catch (error) { }
  23287. return super._getProvider(chainId);
  23288. }
  23289. /**
  23290. * Returns a prepared request for connecting to %%network%% with
  23291. * %%applicationId%%.
  23292. */
  23293. static getRequest(network, applicationId, applicationSecret) {
  23294. if (applicationId == null) {
  23295. applicationId = defaultApplicationId;
  23296. }
  23297. const request = new FetchRequest(`https:/\/${getHost(network.name)}/v1/lb/${applicationId}`);
  23298. request.allowGzip = true;
  23299. if (applicationSecret) {
  23300. request.setCredentials("", applicationSecret);
  23301. }
  23302. if (applicationId === defaultApplicationId) {
  23303. request.retryFunc = async (request, response, attempt) => {
  23304. showThrottleMessage("PocketProvider");
  23305. return true;
  23306. };
  23307. }
  23308. return request;
  23309. }
  23310. isCommunityResource() {
  23311. return (this.applicationId === defaultApplicationId);
  23312. }
  23313. }
  23314. const IpcSocketProvider = undefined;
  23315. /**
  23316. * The **BaseWallet** is a stream-lined implementation of a
  23317. * [[Signer]] that operates with a private key.
  23318. *
  23319. * It is preferred to use the [[Wallet]] class, as it offers
  23320. * additional functionality and simplifies loading a variety
  23321. * of JSON formats, Mnemonic Phrases, etc.
  23322. *
  23323. * This class may be of use for those attempting to implement
  23324. * a minimal Signer.
  23325. */
  23326. class BaseWallet extends AbstractSigner {
  23327. /**
  23328. * The wallet address.
  23329. */
  23330. address;
  23331. #signingKey;
  23332. /**
  23333. * Creates a new BaseWallet for %%privateKey%%, optionally
  23334. * connected to %%provider%%.
  23335. *
  23336. * If %%provider%% is not specified, only offline methods can
  23337. * be used.
  23338. */
  23339. constructor(privateKey, provider) {
  23340. super(provider);
  23341. assertArgument(privateKey && typeof (privateKey.sign) === "function", "invalid private key", "privateKey", "[ REDACTED ]");
  23342. this.#signingKey = privateKey;
  23343. const address = computeAddress(this.signingKey.publicKey);
  23344. defineProperties(this, { address });
  23345. }
  23346. // Store private values behind getters to reduce visibility
  23347. // in console.log
  23348. /**
  23349. * The [[SigningKey]] used for signing payloads.
  23350. */
  23351. get signingKey() { return this.#signingKey; }
  23352. /**
  23353. * The private key for this wallet.
  23354. */
  23355. get privateKey() { return this.signingKey.privateKey; }
  23356. async getAddress() { return this.address; }
  23357. connect(provider) {
  23358. return new BaseWallet(this.#signingKey, provider);
  23359. }
  23360. async signTransaction(tx) {
  23361. tx = copyRequest(tx);
  23362. // Replace any Addressable or ENS name with an address
  23363. const { to, from } = await resolveProperties({
  23364. to: (tx.to ? resolveAddress(tx.to, this.provider) : undefined),
  23365. from: (tx.from ? resolveAddress(tx.from, this.provider) : undefined)
  23366. });
  23367. if (to != null) {
  23368. tx.to = to;
  23369. }
  23370. if (from != null) {
  23371. tx.from = from;
  23372. }
  23373. if (tx.from != null) {
  23374. assertArgument(getAddress((tx.from)) === this.address, "transaction from address mismatch", "tx.from", tx.from);
  23375. delete tx.from;
  23376. }
  23377. // Build the transaction
  23378. const btx = Transaction.from(tx);
  23379. btx.signature = this.signingKey.sign(btx.unsignedHash);
  23380. return btx.serialized;
  23381. }
  23382. async signMessage(message) {
  23383. return this.signMessageSync(message);
  23384. }
  23385. // @TODO: Add a secialized signTx and signTyped sync that enforces
  23386. // all parameters are known?
  23387. /**
  23388. * Returns the signature for %%message%% signed with this wallet.
  23389. */
  23390. signMessageSync(message) {
  23391. return this.signingKey.sign(hashMessage(message)).serialized;
  23392. }
  23393. async signTypedData(domain, types, value) {
  23394. // Populate any ENS names
  23395. const populated = await TypedDataEncoder.resolveNames(domain, types, value, async (name) => {
  23396. // @TODO: this should use resolveName; addresses don't
  23397. // need a provider
  23398. assert(this.provider != null, "cannot resolve ENS names without a provider", "UNSUPPORTED_OPERATION", {
  23399. operation: "resolveName",
  23400. info: { name }
  23401. });
  23402. const address = await this.provider.resolveName(name);
  23403. assert(address != null, "unconfigured ENS name", "UNCONFIGURED_NAME", {
  23404. value: name
  23405. });
  23406. return address;
  23407. });
  23408. return this.signingKey.sign(TypedDataEncoder.hash(populated.domain, types, populated.value)).serialized;
  23409. }
  23410. }
  23411. const subsChrs = " !#$%&'()*+,-./<=>?@[]^_`{|}~";
  23412. const Word = /^[a-z]*$/i;
  23413. function unfold(words, sep) {
  23414. let initial = 97;
  23415. return words.reduce((accum, word) => {
  23416. if (word === sep) {
  23417. initial++;
  23418. }
  23419. else if (word.match(Word)) {
  23420. accum.push(String.fromCharCode(initial) + word);
  23421. }
  23422. else {
  23423. initial = 97;
  23424. accum.push(word);
  23425. }
  23426. return accum;
  23427. }, []);
  23428. }
  23429. /**
  23430. * @_ignore
  23431. */
  23432. function decode(data, subs) {
  23433. // Replace all the substitutions with their expanded form
  23434. for (let i = subsChrs.length - 1; i >= 0; i--) {
  23435. data = data.split(subsChrs[i]).join(subs.substring(2 * i, 2 * i + 2));
  23436. }
  23437. // Get all tle clumps; each suffix, first-increment and second-increment
  23438. const clumps = [];
  23439. const leftover = data.replace(/(:|([0-9])|([A-Z][a-z]*))/g, (all, item, semi, word) => {
  23440. if (semi) {
  23441. for (let i = parseInt(semi); i >= 0; i--) {
  23442. clumps.push(";");
  23443. }
  23444. }
  23445. else {
  23446. clumps.push(item.toLowerCase());
  23447. }
  23448. return "";
  23449. });
  23450. /* c8 ignore start */
  23451. if (leftover) {
  23452. throw new Error(`leftovers: ${JSON.stringify(leftover)}`);
  23453. }
  23454. /* c8 ignore stop */
  23455. return unfold(unfold(clumps, ";"), ":");
  23456. }
  23457. /**
  23458. * @_ignore
  23459. */
  23460. function decodeOwl(data) {
  23461. assertArgument(data[0] === "0", "unsupported auwl data", "data", data);
  23462. return decode(data.substring(1 + 2 * subsChrs.length), data.substring(1, 1 + 2 * subsChrs.length));
  23463. }
  23464. /**
  23465. * A Wordlist represents a collection of language-specific
  23466. * words used to encode and devoce [[link-bip-39]] encoded data
  23467. * by mapping words to 11-bit values and vice versa.
  23468. */
  23469. class Wordlist {
  23470. locale;
  23471. /**
  23472. * Creates a new Wordlist instance.
  23473. *
  23474. * Sub-classes MUST call this if they provide their own constructor,
  23475. * passing in the locale string of the language.
  23476. *
  23477. * Generally there is no need to create instances of a Wordlist,
  23478. * since each language-specific Wordlist creates an instance and
  23479. * there is no state kept internally, so they are safe to share.
  23480. */
  23481. constructor(locale) {
  23482. defineProperties(this, { locale });
  23483. }
  23484. /**
  23485. * Sub-classes may override this to provide a language-specific
  23486. * method for spliting %%phrase%% into individual words.
  23487. *
  23488. * By default, %%phrase%% is split using any sequences of
  23489. * white-space as defined by regular expressions (i.e. ``/\s+/``).
  23490. */
  23491. split(phrase) {
  23492. return phrase.toLowerCase().split(/\s+/g);
  23493. }
  23494. /**
  23495. * Sub-classes may override this to provider a language-specific
  23496. * method for joining %%words%% into a phrase.
  23497. *
  23498. * By default, %%words%% are joined by a single space.
  23499. */
  23500. join(words) {
  23501. return words.join(" ");
  23502. }
  23503. }
  23504. // Use the encode-latin.js script to create the necessary
  23505. // data files to be consumed by this class
  23506. /**
  23507. * An OWL format Wordlist is an encoding method that exploits
  23508. * the general locality of alphabetically sorted words to
  23509. * achieve a simple but effective means of compression.
  23510. *
  23511. * This class is generally not useful to most developers as
  23512. * it is used mainly internally to keep Wordlists for languages
  23513. * based on ASCII-7 small.
  23514. *
  23515. * If necessary, there are tools within the ``generation/`` folder
  23516. * to create the necessary data.
  23517. */
  23518. class WordlistOwl extends Wordlist {
  23519. #data;
  23520. #checksum;
  23521. /**
  23522. * Creates a new Wordlist for %%locale%% using the OWL %%data%%
  23523. * and validated against the %%checksum%%.
  23524. */
  23525. constructor(locale, data, checksum) {
  23526. super(locale);
  23527. this.#data = data;
  23528. this.#checksum = checksum;
  23529. this.#words = null;
  23530. }
  23531. /**
  23532. * The OWL-encoded data.
  23533. */
  23534. get _data() { return this.#data; }
  23535. /**
  23536. * Decode all the words for the wordlist.
  23537. */
  23538. _decodeWords() {
  23539. return decodeOwl(this.#data);
  23540. }
  23541. #words;
  23542. #loadWords() {
  23543. if (this.#words == null) {
  23544. const words = this._decodeWords();
  23545. // Verify the computed list matches the official list
  23546. const checksum = id(words.join("\n") + "\n");
  23547. /* c8 ignore start */
  23548. if (checksum !== this.#checksum) {
  23549. throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`);
  23550. }
  23551. /* c8 ignore stop */
  23552. this.#words = words;
  23553. }
  23554. return this.#words;
  23555. }
  23556. getWord(index) {
  23557. const words = this.#loadWords();
  23558. assertArgument(index >= 0 && index < words.length, `invalid word index: ${index}`, "index", index);
  23559. return words[index];
  23560. }
  23561. getWordIndex(word) {
  23562. return this.#loadWords().indexOf(word);
  23563. }
  23564. }
  23565. 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";
  23566. const checksum = "0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60";
  23567. let wordlist = null;
  23568. /**
  23569. * The [[link-bip39-en]] for [mnemonic phrases](link-bip-39).
  23570. *
  23571. * @_docloc: api/wordlists
  23572. */
  23573. class LangEn extends WordlistOwl {
  23574. /**
  23575. * Creates a new instance of the English language Wordlist.
  23576. *
  23577. * This should be unnecessary most of the time as the exported
  23578. * [[langEn]] should suffice.
  23579. *
  23580. * @_ignore:
  23581. */
  23582. constructor() { super("en", words, checksum); }
  23583. /**
  23584. * Returns a singleton instance of a ``LangEn``, creating it
  23585. * if this is the first time being called.
  23586. */
  23587. static wordlist() {
  23588. if (wordlist == null) {
  23589. wordlist = new LangEn();
  23590. }
  23591. return wordlist;
  23592. }
  23593. }
  23594. // Returns a byte with the MSB bits set
  23595. function getUpperMask(bits) {
  23596. return ((1 << bits) - 1) << (8 - bits) & 0xff;
  23597. }
  23598. // Returns a byte with the LSB bits set
  23599. function getLowerMask(bits) {
  23600. return ((1 << bits) - 1) & 0xff;
  23601. }
  23602. function mnemonicToEntropy(mnemonic, wordlist) {
  23603. assertNormalize("NFKD");
  23604. if (wordlist == null) {
  23605. wordlist = LangEn.wordlist();
  23606. }
  23607. const words = wordlist.split(mnemonic);
  23608. assertArgument((words.length % 3) === 0 && words.length >= 12 && words.length <= 24, "invalid mnemonic length", "mnemonic", "[ REDACTED ]");
  23609. const entropy = new Uint8Array(Math.ceil(11 * words.length / 8));
  23610. let offset = 0;
  23611. for (let i = 0; i < words.length; i++) {
  23612. let index = wordlist.getWordIndex(words[i].normalize("NFKD"));
  23613. assertArgument(index >= 0, `invalid mnemonic word at index ${i}`, "mnemonic", "[ REDACTED ]");
  23614. for (let bit = 0; bit < 11; bit++) {
  23615. if (index & (1 << (10 - bit))) {
  23616. entropy[offset >> 3] |= (1 << (7 - (offset % 8)));
  23617. }
  23618. offset++;
  23619. }
  23620. }
  23621. const entropyBits = 32 * words.length / 3;
  23622. const checksumBits = words.length / 3;
  23623. const checksumMask = getUpperMask(checksumBits);
  23624. const checksum = getBytes(sha256(entropy.slice(0, entropyBits / 8)))[0] & checksumMask;
  23625. assertArgument(checksum === (entropy[entropy.length - 1] & checksumMask), "invalid mnemonic checksum", "mnemonic", "[ REDACTED ]");
  23626. return hexlify(entropy.slice(0, entropyBits / 8));
  23627. }
  23628. function entropyToMnemonic(entropy, wordlist) {
  23629. assertArgument((entropy.length % 4) === 0 && entropy.length >= 16 && entropy.length <= 32, "invalid entropy size", "entropy", "[ REDACTED ]");
  23630. if (wordlist == null) {
  23631. wordlist = LangEn.wordlist();
  23632. }
  23633. const indices = [0];
  23634. let remainingBits = 11;
  23635. for (let i = 0; i < entropy.length; i++) {
  23636. // Consume the whole byte (with still more to go)
  23637. if (remainingBits > 8) {
  23638. indices[indices.length - 1] <<= 8;
  23639. indices[indices.length - 1] |= entropy[i];
  23640. remainingBits -= 8;
  23641. // This byte will complete an 11-bit index
  23642. }
  23643. else {
  23644. indices[indices.length - 1] <<= remainingBits;
  23645. indices[indices.length - 1] |= entropy[i] >> (8 - remainingBits);
  23646. // Start the next word
  23647. indices.push(entropy[i] & getLowerMask(8 - remainingBits));
  23648. remainingBits += 3;
  23649. }
  23650. }
  23651. // Compute the checksum bits
  23652. const checksumBits = entropy.length / 4;
  23653. const checksum = parseInt(sha256(entropy).substring(2, 4), 16) & getUpperMask(checksumBits);
  23654. // Shift the checksum into the word indices
  23655. indices[indices.length - 1] <<= checksumBits;
  23656. indices[indices.length - 1] |= (checksum >> (8 - checksumBits));
  23657. return wordlist.join(indices.map((index) => wordlist.getWord(index)));
  23658. }
  23659. const _guard$1 = {};
  23660. /**
  23661. * A **Mnemonic** wraps all properties required to compute [[link-bip-39]]
  23662. * seeds and convert between phrases and entropy.
  23663. */
  23664. class Mnemonic {
  23665. /**
  23666. * The mnemonic phrase of 12, 15, 18, 21 or 24 words.
  23667. *
  23668. * Use the [[wordlist]] ``split`` method to get the individual words.
  23669. */
  23670. phrase;
  23671. /**
  23672. * The password used for this mnemonic. If no password is used this
  23673. * is the empty string (i.e. ``""``) as per the specification.
  23674. */
  23675. password;
  23676. /**
  23677. * The wordlist for this mnemonic.
  23678. */
  23679. wordlist;
  23680. /**
  23681. * The underlying entropy which the mnemonic encodes.
  23682. */
  23683. entropy;
  23684. /**
  23685. * @private
  23686. */
  23687. constructor(guard, entropy, phrase, password, wordlist) {
  23688. if (password == null) {
  23689. password = "";
  23690. }
  23691. if (wordlist == null) {
  23692. wordlist = LangEn.wordlist();
  23693. }
  23694. assertPrivate(guard, _guard$1, "Mnemonic");
  23695. defineProperties(this, { phrase, password, wordlist, entropy });
  23696. }
  23697. /**
  23698. * Returns the seed for the mnemonic.
  23699. */
  23700. computeSeed() {
  23701. const salt = toUtf8Bytes("mnemonic" + this.password, "NFKD");
  23702. return pbkdf2(toUtf8Bytes(this.phrase, "NFKD"), salt, 2048, 64, "sha512");
  23703. }
  23704. /**
  23705. * Creates a new Mnemonic for the %%phrase%%.
  23706. *
  23707. * The default %%password%% is the empty string and the default
  23708. * wordlist is the [English wordlists](LangEn).
  23709. */
  23710. static fromPhrase(phrase, password, wordlist) {
  23711. // Normalize the case and space; throws if invalid
  23712. const entropy = mnemonicToEntropy(phrase, wordlist);
  23713. phrase = entropyToMnemonic(getBytes(entropy), wordlist);
  23714. return new Mnemonic(_guard$1, entropy, phrase, password, wordlist);
  23715. }
  23716. /**
  23717. * Create a new **Mnemonic** from the %%entropy%%.
  23718. *
  23719. * The default %%password%% is the empty string and the default
  23720. * wordlist is the [English wordlists](LangEn).
  23721. */
  23722. static fromEntropy(_entropy, password, wordlist) {
  23723. const entropy = getBytes(_entropy, "entropy");
  23724. const phrase = entropyToMnemonic(entropy, wordlist);
  23725. return new Mnemonic(_guard$1, hexlify(entropy), phrase, password, wordlist);
  23726. }
  23727. /**
  23728. * Returns the phrase for %%mnemonic%%.
  23729. */
  23730. static entropyToPhrase(_entropy, wordlist) {
  23731. const entropy = getBytes(_entropy, "entropy");
  23732. return entropyToMnemonic(entropy, wordlist);
  23733. }
  23734. /**
  23735. * Returns the entropy for %%phrase%%.
  23736. */
  23737. static phraseToEntropy(phrase, wordlist) {
  23738. return mnemonicToEntropy(phrase, wordlist);
  23739. }
  23740. /**
  23741. * Returns true if %%phrase%% is a valid [[link-bip-39]] phrase.
  23742. *
  23743. * This checks all the provided words belong to the %%wordlist%%,
  23744. * that the length is valid and the checksum is correct.
  23745. */
  23746. static isValidMnemonic(phrase, wordlist) {
  23747. try {
  23748. mnemonicToEntropy(phrase, wordlist);
  23749. return true;
  23750. }
  23751. catch (error) { }
  23752. return false;
  23753. }
  23754. }
  23755. /*! MIT License. Copyright 2015-2022 Richard Moore <me@ricmoo.com>. See LICENSE.txt. */
  23756. var __classPrivateFieldGet$2 = (__$G && __$G.__classPrivateFieldGet) || function (receiver, state, kind, f) {
  23757. if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
  23758. 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");
  23759. return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
  23760. };
  23761. var __classPrivateFieldSet$2 = (__$G && __$G.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
  23762. if (kind === "m") throw new TypeError("Private method is not writable");
  23763. if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
  23764. 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");
  23765. return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
  23766. };
  23767. var _AES_key, _AES_Kd, _AES_Ke;
  23768. // Number of rounds by keysize
  23769. const numberOfRounds = { 16: 10, 24: 12, 32: 14 };
  23770. // Round constant words
  23771. 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];
  23772. // S-box and Inverse S-box (S is for Substitution)
  23773. 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];
  23774. 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];
  23775. // Transformations for encryption
  23776. 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];
  23777. 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];
  23778. 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];
  23779. 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];
  23780. // Transformations for decryption
  23781. 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];
  23782. 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];
  23783. 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];
  23784. 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];
  23785. // Transformations for decryption key expansion
  23786. 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];
  23787. 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];
  23788. 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];
  23789. 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];
  23790. function convertToInt32(bytes) {
  23791. const result = [];
  23792. for (let i = 0; i < bytes.length; i += 4) {
  23793. result.push((bytes[i] << 24) | (bytes[i + 1] << 16) | (bytes[i + 2] << 8) | bytes[i + 3]);
  23794. }
  23795. return result;
  23796. }
  23797. class AES {
  23798. get key() { return __classPrivateFieldGet$2(this, _AES_key, "f").slice(); }
  23799. constructor(key) {
  23800. _AES_key.set(this, void 0);
  23801. _AES_Kd.set(this, void 0);
  23802. _AES_Ke.set(this, void 0);
  23803. if (!(this instanceof AES)) {
  23804. throw Error('AES must be instanitated with `new`');
  23805. }
  23806. __classPrivateFieldSet$2(this, _AES_key, new Uint8Array(key), "f");
  23807. const rounds = numberOfRounds[this.key.length];
  23808. if (rounds == null) {
  23809. throw new TypeError('invalid key size (must be 16, 24 or 32 bytes)');
  23810. }
  23811. // encryption round keys
  23812. __classPrivateFieldSet$2(this, _AES_Ke, [], "f");
  23813. // decryption round keys
  23814. __classPrivateFieldSet$2(this, _AES_Kd, [], "f");
  23815. for (let i = 0; i <= rounds; i++) {
  23816. __classPrivateFieldGet$2(this, _AES_Ke, "f").push([0, 0, 0, 0]);
  23817. __classPrivateFieldGet$2(this, _AES_Kd, "f").push([0, 0, 0, 0]);
  23818. }
  23819. const roundKeyCount = (rounds + 1) * 4;
  23820. const KC = this.key.length / 4;
  23821. // convert the key into ints
  23822. const tk = convertToInt32(this.key);
  23823. // copy values into round key arrays
  23824. let index;
  23825. for (let i = 0; i < KC; i++) {
  23826. index = i >> 2;
  23827. __classPrivateFieldGet$2(this, _AES_Ke, "f")[index][i % 4] = tk[i];
  23828. __classPrivateFieldGet$2(this, _AES_Kd, "f")[rounds - index][i % 4] = tk[i];
  23829. }
  23830. // key expansion (fips-197 section 5.2)
  23831. let rconpointer = 0;
  23832. let t = KC, tt;
  23833. while (t < roundKeyCount) {
  23834. tt = tk[KC - 1];
  23835. tk[0] ^= ((S[(tt >> 16) & 0xFF] << 24) ^
  23836. (S[(tt >> 8) & 0xFF] << 16) ^
  23837. (S[tt & 0xFF] << 8) ^
  23838. S[(tt >> 24) & 0xFF] ^
  23839. (rcon[rconpointer] << 24));
  23840. rconpointer += 1;
  23841. // key expansion (for non-256 bit)
  23842. if (KC != 8) {
  23843. for (let i = 1; i < KC; i++) {
  23844. tk[i] ^= tk[i - 1];
  23845. }
  23846. // key expansion for 256-bit keys is "slightly different" (fips-197)
  23847. }
  23848. else {
  23849. for (let i = 1; i < (KC / 2); i++) {
  23850. tk[i] ^= tk[i - 1];
  23851. }
  23852. tt = tk[(KC / 2) - 1];
  23853. tk[KC / 2] ^= (S[tt & 0xFF] ^
  23854. (S[(tt >> 8) & 0xFF] << 8) ^
  23855. (S[(tt >> 16) & 0xFF] << 16) ^
  23856. (S[(tt >> 24) & 0xFF] << 24));
  23857. for (let i = (KC / 2) + 1; i < KC; i++) {
  23858. tk[i] ^= tk[i - 1];
  23859. }
  23860. }
  23861. // copy values into round key arrays
  23862. let i = 0, r, c;
  23863. while (i < KC && t < roundKeyCount) {
  23864. r = t >> 2;
  23865. c = t % 4;
  23866. __classPrivateFieldGet$2(this, _AES_Ke, "f")[r][c] = tk[i];
  23867. __classPrivateFieldGet$2(this, _AES_Kd, "f")[rounds - r][c] = tk[i++];
  23868. t++;
  23869. }
  23870. }
  23871. // inverse-cipher-ify the decryption round key (fips-197 section 5.3)
  23872. for (let r = 1; r < rounds; r++) {
  23873. for (let c = 0; c < 4; c++) {
  23874. tt = __classPrivateFieldGet$2(this, _AES_Kd, "f")[r][c];
  23875. __classPrivateFieldGet$2(this, _AES_Kd, "f")[r][c] = (U1[(tt >> 24) & 0xFF] ^
  23876. U2[(tt >> 16) & 0xFF] ^
  23877. U3[(tt >> 8) & 0xFF] ^
  23878. U4[tt & 0xFF]);
  23879. }
  23880. }
  23881. }
  23882. encrypt(plaintext) {
  23883. if (plaintext.length != 16) {
  23884. throw new TypeError('invalid plaintext size (must be 16 bytes)');
  23885. }
  23886. const rounds = __classPrivateFieldGet$2(this, _AES_Ke, "f").length - 1;
  23887. const a = [0, 0, 0, 0];
  23888. // convert plaintext to (ints ^ key)
  23889. let t = convertToInt32(plaintext);
  23890. for (let i = 0; i < 4; i++) {
  23891. t[i] ^= __classPrivateFieldGet$2(this, _AES_Ke, "f")[0][i];
  23892. }
  23893. // apply round transforms
  23894. for (let r = 1; r < rounds; r++) {
  23895. for (let i = 0; i < 4; i++) {
  23896. a[i] = (T1[(t[i] >> 24) & 0xff] ^
  23897. T2[(t[(i + 1) % 4] >> 16) & 0xff] ^
  23898. T3[(t[(i + 2) % 4] >> 8) & 0xff] ^
  23899. T4[t[(i + 3) % 4] & 0xff] ^
  23900. __classPrivateFieldGet$2(this, _AES_Ke, "f")[r][i]);
  23901. }
  23902. t = a.slice();
  23903. }
  23904. // the last round is special
  23905. const result = new Uint8Array(16);
  23906. let tt = 0;
  23907. for (let i = 0; i < 4; i++) {
  23908. tt = __classPrivateFieldGet$2(this, _AES_Ke, "f")[rounds][i];
  23909. result[4 * i] = (S[(t[i] >> 24) & 0xff] ^ (tt >> 24)) & 0xff;
  23910. result[4 * i + 1] = (S[(t[(i + 1) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff;
  23911. result[4 * i + 2] = (S[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff;
  23912. result[4 * i + 3] = (S[t[(i + 3) % 4] & 0xff] ^ tt) & 0xff;
  23913. }
  23914. return result;
  23915. }
  23916. decrypt(ciphertext) {
  23917. if (ciphertext.length != 16) {
  23918. throw new TypeError('invalid ciphertext size (must be 16 bytes)');
  23919. }
  23920. const rounds = __classPrivateFieldGet$2(this, _AES_Kd, "f").length - 1;
  23921. const a = [0, 0, 0, 0];
  23922. // convert plaintext to (ints ^ key)
  23923. let t = convertToInt32(ciphertext);
  23924. for (let i = 0; i < 4; i++) {
  23925. t[i] ^= __classPrivateFieldGet$2(this, _AES_Kd, "f")[0][i];
  23926. }
  23927. // apply round transforms
  23928. for (let r = 1; r < rounds; r++) {
  23929. for (let i = 0; i < 4; i++) {
  23930. a[i] = (T5[(t[i] >> 24) & 0xff] ^
  23931. T6[(t[(i + 3) % 4] >> 16) & 0xff] ^
  23932. T7[(t[(i + 2) % 4] >> 8) & 0xff] ^
  23933. T8[t[(i + 1) % 4] & 0xff] ^
  23934. __classPrivateFieldGet$2(this, _AES_Kd, "f")[r][i]);
  23935. }
  23936. t = a.slice();
  23937. }
  23938. // the last round is special
  23939. const result = new Uint8Array(16);
  23940. let tt = 0;
  23941. for (let i = 0; i < 4; i++) {
  23942. tt = __classPrivateFieldGet$2(this, _AES_Kd, "f")[rounds][i];
  23943. result[4 * i] = (Si[(t[i] >> 24) & 0xff] ^ (tt >> 24)) & 0xff;
  23944. result[4 * i + 1] = (Si[(t[(i + 3) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff;
  23945. result[4 * i + 2] = (Si[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff;
  23946. result[4 * i + 3] = (Si[t[(i + 1) % 4] & 0xff] ^ tt) & 0xff;
  23947. }
  23948. return result;
  23949. }
  23950. }
  23951. _AES_key = new WeakMap(), _AES_Kd = new WeakMap(), _AES_Ke = new WeakMap();
  23952. class ModeOfOperation {
  23953. constructor(name, key, cls) {
  23954. if (cls && !(this instanceof cls)) {
  23955. throw new Error(`${name} must be instantiated with "new"`);
  23956. }
  23957. Object.defineProperties(this, {
  23958. aes: { enumerable: true, value: new AES(key) },
  23959. name: { enumerable: true, value: name }
  23960. });
  23961. }
  23962. }
  23963. // Cipher Block Chaining
  23964. var __classPrivateFieldSet$1 = (__$G && __$G.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
  23965. if (kind === "m") throw new TypeError("Private method is not writable");
  23966. if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
  23967. 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");
  23968. return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
  23969. };
  23970. var __classPrivateFieldGet$1 = (__$G && __$G.__classPrivateFieldGet) || function (receiver, state, kind, f) {
  23971. if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
  23972. 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");
  23973. return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
  23974. };
  23975. var _CBC_iv, _CBC_lastBlock;
  23976. class CBC extends ModeOfOperation {
  23977. constructor(key, iv) {
  23978. super("ECC", key, CBC);
  23979. _CBC_iv.set(this, void 0);
  23980. _CBC_lastBlock.set(this, void 0);
  23981. if (iv) {
  23982. if (iv.length % 16) {
  23983. throw new TypeError("invalid iv size (must be 16 bytes)");
  23984. }
  23985. __classPrivateFieldSet$1(this, _CBC_iv, new Uint8Array(iv), "f");
  23986. }
  23987. else {
  23988. __classPrivateFieldSet$1(this, _CBC_iv, new Uint8Array(16), "f");
  23989. }
  23990. __classPrivateFieldSet$1(this, _CBC_lastBlock, this.iv, "f");
  23991. }
  23992. get iv() { return new Uint8Array(__classPrivateFieldGet$1(this, _CBC_iv, "f")); }
  23993. encrypt(plaintext) {
  23994. if (plaintext.length % 16) {
  23995. throw new TypeError("invalid plaintext size (must be multiple of 16 bytes)");
  23996. }
  23997. const ciphertext = new Uint8Array(plaintext.length);
  23998. for (let i = 0; i < plaintext.length; i += 16) {
  23999. for (let j = 0; j < 16; j++) {
  24000. __classPrivateFieldGet$1(this, _CBC_lastBlock, "f")[j] ^= plaintext[i + j];
  24001. }
  24002. __classPrivateFieldSet$1(this, _CBC_lastBlock, this.aes.encrypt(__classPrivateFieldGet$1(this, _CBC_lastBlock, "f")), "f");
  24003. ciphertext.set(__classPrivateFieldGet$1(this, _CBC_lastBlock, "f"), i);
  24004. }
  24005. return ciphertext;
  24006. }
  24007. decrypt(ciphertext) {
  24008. if (ciphertext.length % 16) {
  24009. throw new TypeError("invalid ciphertext size (must be multiple of 16 bytes)");
  24010. }
  24011. const plaintext = new Uint8Array(ciphertext.length);
  24012. for (let i = 0; i < ciphertext.length; i += 16) {
  24013. const block = this.aes.decrypt(ciphertext.subarray(i, i + 16));
  24014. for (let j = 0; j < 16; j++) {
  24015. plaintext[i + j] = block[j] ^ __classPrivateFieldGet$1(this, _CBC_lastBlock, "f")[j];
  24016. __classPrivateFieldGet$1(this, _CBC_lastBlock, "f")[j] = ciphertext[i + j];
  24017. }
  24018. }
  24019. return plaintext;
  24020. }
  24021. }
  24022. _CBC_iv = new WeakMap(), _CBC_lastBlock = new WeakMap();
  24023. // Counter Mode
  24024. var __classPrivateFieldSet = (__$G && __$G.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
  24025. if (kind === "m") throw new TypeError("Private method is not writable");
  24026. if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
  24027. 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");
  24028. return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
  24029. };
  24030. var __classPrivateFieldGet = (__$G && __$G.__classPrivateFieldGet) || function (receiver, state, kind, f) {
  24031. if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
  24032. 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");
  24033. return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
  24034. };
  24035. var _CTR_remaining, _CTR_remainingIndex, _CTR_counter;
  24036. class CTR extends ModeOfOperation {
  24037. constructor(key, initialValue) {
  24038. super("CTR", key, CTR);
  24039. // Remaining bytes for the one-time pad
  24040. _CTR_remaining.set(this, void 0);
  24041. _CTR_remainingIndex.set(this, void 0);
  24042. // The current counter
  24043. _CTR_counter.set(this, void 0);
  24044. __classPrivateFieldSet(this, _CTR_counter, new Uint8Array(16), "f");
  24045. __classPrivateFieldGet(this, _CTR_counter, "f").fill(0);
  24046. __classPrivateFieldSet(this, _CTR_remaining, __classPrivateFieldGet(this, _CTR_counter, "f"), "f"); // This will be discarded immediately
  24047. __classPrivateFieldSet(this, _CTR_remainingIndex, 16, "f");
  24048. if (initialValue == null) {
  24049. initialValue = 1;
  24050. }
  24051. if (typeof (initialValue) === "number") {
  24052. this.setCounterValue(initialValue);
  24053. }
  24054. else {
  24055. this.setCounterBytes(initialValue);
  24056. }
  24057. }
  24058. get counter() { return new Uint8Array(__classPrivateFieldGet(this, _CTR_counter, "f")); }
  24059. setCounterValue(value) {
  24060. if (!Number.isInteger(value) || value < 0 || value > Number.MAX_SAFE_INTEGER) {
  24061. throw new TypeError("invalid counter initial integer value");
  24062. }
  24063. for (let index = 15; index >= 0; --index) {
  24064. __classPrivateFieldGet(this, _CTR_counter, "f")[index] = value % 256;
  24065. value = Math.floor(value / 256);
  24066. }
  24067. }
  24068. setCounterBytes(value) {
  24069. if (value.length !== 16) {
  24070. throw new TypeError("invalid counter initial Uint8Array value length");
  24071. }
  24072. __classPrivateFieldGet(this, _CTR_counter, "f").set(value);
  24073. }
  24074. increment() {
  24075. for (let i = 15; i >= 0; i--) {
  24076. if (__classPrivateFieldGet(this, _CTR_counter, "f")[i] === 255) {
  24077. __classPrivateFieldGet(this, _CTR_counter, "f")[i] = 0;
  24078. }
  24079. else {
  24080. __classPrivateFieldGet(this, _CTR_counter, "f")[i]++;
  24081. break;
  24082. }
  24083. }
  24084. }
  24085. encrypt(plaintext) {
  24086. var _a, _b;
  24087. const crypttext = new Uint8Array(plaintext);
  24088. for (let i = 0; i < crypttext.length; i++) {
  24089. if (__classPrivateFieldGet(this, _CTR_remainingIndex, "f") === 16) {
  24090. __classPrivateFieldSet(this, _CTR_remaining, this.aes.encrypt(__classPrivateFieldGet(this, _CTR_counter, "f")), "f");
  24091. __classPrivateFieldSet(this, _CTR_remainingIndex, 0, "f");
  24092. this.increment();
  24093. }
  24094. crypttext[i] ^= __classPrivateFieldGet(this, _CTR_remaining, "f")[__classPrivateFieldSet(this, _CTR_remainingIndex, (_b = __classPrivateFieldGet(this, _CTR_remainingIndex, "f"), _a = _b++, _b), "f"), _a];
  24095. }
  24096. return crypttext;
  24097. }
  24098. decrypt(ciphertext) {
  24099. return this.encrypt(ciphertext);
  24100. }
  24101. }
  24102. _CTR_remaining = new WeakMap(), _CTR_remainingIndex = new WeakMap(), _CTR_counter = new WeakMap();
  24103. function pkcs7Strip(data) {
  24104. if (data.length < 16) {
  24105. throw new TypeError('PKCS#7 invalid length');
  24106. }
  24107. const padder = data[data.length - 1];
  24108. if (padder > 16) {
  24109. throw new TypeError('PKCS#7 padding byte out of range');
  24110. }
  24111. const length = data.length - padder;
  24112. for (let i = 0; i < padder; i++) {
  24113. if (data[length + i] !== padder) {
  24114. throw new TypeError('PKCS#7 invalid padding byte');
  24115. }
  24116. }
  24117. return new Uint8Array(data.subarray(0, length));
  24118. }
  24119. /**
  24120. * @_ignore
  24121. */
  24122. function looseArrayify(hexString) {
  24123. if (typeof (hexString) === "string" && !hexString.startsWith("0x")) {
  24124. hexString = "0x" + hexString;
  24125. }
  24126. return getBytesCopy(hexString);
  24127. }
  24128. function zpad$1(value, length) {
  24129. value = String(value);
  24130. while (value.length < length) {
  24131. value = '0' + value;
  24132. }
  24133. return value;
  24134. }
  24135. function getPassword(password) {
  24136. if (typeof (password) === 'string') {
  24137. return toUtf8Bytes(password, "NFKC");
  24138. }
  24139. return getBytesCopy(password);
  24140. }
  24141. function spelunk(object, _path) {
  24142. const match = _path.match(/^([a-z0-9$_.-]*)(:([a-z]+))?(!)?$/i);
  24143. assertArgument(match != null, "invalid path", "path", _path);
  24144. const path = match[1];
  24145. const type = match[3];
  24146. const reqd = (match[4] === "!");
  24147. let cur = object;
  24148. for (const comp of path.toLowerCase().split('.')) {
  24149. // Search for a child object with a case-insensitive matching key
  24150. if (Array.isArray(cur)) {
  24151. if (!comp.match(/^[0-9]+$/)) {
  24152. break;
  24153. }
  24154. cur = cur[parseInt(comp)];
  24155. }
  24156. else if (typeof (cur) === "object") {
  24157. let found = null;
  24158. for (const key in cur) {
  24159. if (key.toLowerCase() === comp) {
  24160. found = cur[key];
  24161. break;
  24162. }
  24163. }
  24164. cur = found;
  24165. }
  24166. else {
  24167. cur = null;
  24168. }
  24169. if (cur == null) {
  24170. break;
  24171. }
  24172. }
  24173. assertArgument(!reqd || cur != null, "missing required value", "path", path);
  24174. if (type && cur != null) {
  24175. if (type === "int") {
  24176. if (typeof (cur) === "string" && cur.match(/^-?[0-9]+$/)) {
  24177. return parseInt(cur);
  24178. }
  24179. else if (Number.isSafeInteger(cur)) {
  24180. return cur;
  24181. }
  24182. }
  24183. if (type === "number") {
  24184. if (typeof (cur) === "string" && cur.match(/^-?[0-9.]*$/)) {
  24185. return parseFloat(cur);
  24186. }
  24187. }
  24188. if (type === "data") {
  24189. if (typeof (cur) === "string") {
  24190. return looseArrayify(cur);
  24191. }
  24192. }
  24193. if (type === "array" && Array.isArray(cur)) {
  24194. return cur;
  24195. }
  24196. if (type === typeof (cur)) {
  24197. return cur;
  24198. }
  24199. assertArgument(false, `wrong type found for ${type} `, "path", path);
  24200. }
  24201. return cur;
  24202. }
  24203. /*
  24204. export function follow(object: any, path: string): null | string {
  24205. let currentChild = object;
  24206. for (const comp of path.toLowerCase().split('/')) {
  24207. // Search for a child object with a case-insensitive matching key
  24208. let matchingChild = null;
  24209. for (const key in currentChild) {
  24210. if (key.toLowerCase() === comp) {
  24211. matchingChild = currentChild[key];
  24212. break;
  24213. }
  24214. }
  24215. if (matchingChild === null) { return null; }
  24216. currentChild = matchingChild;
  24217. }
  24218. return currentChild;
  24219. }
  24220. // "path/to/something:type!"
  24221. export function followRequired(data: any, path: string): string {
  24222. const value = follow(data, path);
  24223. if (value != null) { return value; }
  24224. return logger.throwArgumentError("invalid value", `data:${ path }`,
  24225. JSON.stringify(data));
  24226. }
  24227. */
  24228. // See: https://www.ietf.org/rfc/rfc4122.txt (Section 4.4)
  24229. /*
  24230. export function uuidV4(randomBytes: BytesLike): string {
  24231. const bytes = getBytes(randomBytes, "randomBytes");
  24232. // Section: 4.1.3:
  24233. // - time_hi_and_version[12:16] = 0b0100
  24234. bytes[6] = (bytes[6] & 0x0f) | 0x40;
  24235. // Section 4.4
  24236. // - clock_seq_hi_and_reserved[6] = 0b0
  24237. // - clock_seq_hi_and_reserved[7] = 0b1
  24238. bytes[8] = (bytes[8] & 0x3f) | 0x80;
  24239. const value = hexlify(bytes);
  24240. return [
  24241. value.substring(2, 10),
  24242. value.substring(10, 14),
  24243. value.substring(14, 18),
  24244. value.substring(18, 22),
  24245. value.substring(22, 34),
  24246. ].join("-");
  24247. }
  24248. */
  24249. /**
  24250. * The JSON Wallet formats allow a simple way to store the private
  24251. * keys needed in Ethereum along with related information and allows
  24252. * for extensible forms of encryption.
  24253. *
  24254. * These utilities facilitate decrypting and encrypting the most common
  24255. * JSON Wallet formats.
  24256. *
  24257. * @_subsection: api/wallet:JSON Wallets [json-wallets]
  24258. */
  24259. const defaultPath$1 = "m/44'/60'/0'/0/0";
  24260. /**
  24261. * Returns true if %%json%% is a valid JSON Keystore Wallet.
  24262. */
  24263. function isKeystoreJson(json) {
  24264. try {
  24265. const data = JSON.parse(json);
  24266. const version = ((data.version != null) ? parseInt(data.version) : 0);
  24267. if (version === 3) {
  24268. return true;
  24269. }
  24270. }
  24271. catch (error) { }
  24272. return false;
  24273. }
  24274. function decrypt(data, key, ciphertext) {
  24275. const cipher = spelunk(data, "crypto.cipher:string");
  24276. if (cipher === "aes-128-ctr") {
  24277. const iv = spelunk(data, "crypto.cipherparams.iv:data!");
  24278. const aesCtr = new CTR(key, iv);
  24279. return hexlify(aesCtr.decrypt(ciphertext));
  24280. }
  24281. assert(false, "unsupported cipher", "UNSUPPORTED_OPERATION", {
  24282. operation: "decrypt"
  24283. });
  24284. }
  24285. function getAccount(data, _key) {
  24286. const key = getBytes(_key);
  24287. const ciphertext = spelunk(data, "crypto.ciphertext:data!");
  24288. const computedMAC = hexlify(keccak256(concat([key.slice(16, 32), ciphertext]))).substring(2);
  24289. assertArgument(computedMAC === spelunk(data, "crypto.mac:string!").toLowerCase(), "incorrect password", "password", "[ REDACTED ]");
  24290. const privateKey = decrypt(data, key.slice(0, 16), ciphertext);
  24291. const address = computeAddress(privateKey);
  24292. if (data.address) {
  24293. let check = data.address.toLowerCase();
  24294. if (!check.startsWith("0x")) {
  24295. check = "0x" + check;
  24296. }
  24297. assertArgument(getAddress(check) === address, "keystore address/privateKey mismatch", "address", data.address);
  24298. }
  24299. const account = { address, privateKey };
  24300. // Version 0.1 x-ethers metadata must contain an encrypted mnemonic phrase
  24301. const version = spelunk(data, "x-ethers.version:string");
  24302. if (version === "0.1") {
  24303. const mnemonicKey = key.slice(32, 64);
  24304. const mnemonicCiphertext = spelunk(data, "x-ethers.mnemonicCiphertext:data!");
  24305. const mnemonicIv = spelunk(data, "x-ethers.mnemonicCounter:data!");
  24306. const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv);
  24307. account.mnemonic = {
  24308. path: (spelunk(data, "x-ethers.path:string") || defaultPath$1),
  24309. locale: (spelunk(data, "x-ethers.locale:string") || "en"),
  24310. entropy: hexlify(getBytes(mnemonicAesCtr.decrypt(mnemonicCiphertext)))
  24311. };
  24312. }
  24313. return account;
  24314. }
  24315. function getDecryptKdfParams(data) {
  24316. const kdf = spelunk(data, "crypto.kdf:string");
  24317. if (kdf && typeof (kdf) === "string") {
  24318. if (kdf.toLowerCase() === "scrypt") {
  24319. const salt = spelunk(data, "crypto.kdfparams.salt:data!");
  24320. const N = spelunk(data, "crypto.kdfparams.n:int!");
  24321. const r = spelunk(data, "crypto.kdfparams.r:int!");
  24322. const p = spelunk(data, "crypto.kdfparams.p:int!");
  24323. // Make sure N is a power of 2
  24324. assertArgument(N > 0 && (N & (N - 1)) === 0, "invalid kdf.N", "kdf.N", N);
  24325. assertArgument(r > 0 && p > 0, "invalid kdf", "kdf", kdf);
  24326. const dkLen = spelunk(data, "crypto.kdfparams.dklen:int!");
  24327. assertArgument(dkLen === 32, "invalid kdf.dklen", "kdf.dflen", dkLen);
  24328. return { name: "scrypt", salt, N, r, p, dkLen: 64 };
  24329. }
  24330. else if (kdf.toLowerCase() === "pbkdf2") {
  24331. const salt = spelunk(data, "crypto.kdfparams.salt:data!");
  24332. const prf = spelunk(data, "crypto.kdfparams.prf:string!");
  24333. const algorithm = prf.split("-").pop();
  24334. assertArgument(algorithm === "sha256" || algorithm === "sha512", "invalid kdf.pdf", "kdf.pdf", prf);
  24335. const count = spelunk(data, "crypto.kdfparams.c:int!");
  24336. const dkLen = spelunk(data, "crypto.kdfparams.dklen:int!");
  24337. assertArgument(dkLen === 32, "invalid kdf.dklen", "kdf.dklen", dkLen);
  24338. return { name: "pbkdf2", salt, count, dkLen, algorithm };
  24339. }
  24340. }
  24341. assertArgument(false, "unsupported key-derivation function", "kdf", kdf);
  24342. }
  24343. /**
  24344. * Returns the account details for the JSON Keystore Wallet %%json%%
  24345. * using %%password%%.
  24346. *
  24347. * It is preferred to use the [async version](decryptKeystoreJson)
  24348. * instead, which allows a [[ProgressCallback]] to keep the user informed
  24349. * as to the decryption status.
  24350. *
  24351. * This method will block the event loop (freezing all UI) until decryption
  24352. * is complete, which can take quite some time, depending on the wallet
  24353. * paramters and platform.
  24354. */
  24355. function decryptKeystoreJsonSync(json, _password) {
  24356. const data = JSON.parse(json);
  24357. const password = getPassword(_password);
  24358. const params = getDecryptKdfParams(data);
  24359. if (params.name === "pbkdf2") {
  24360. const { salt, count, dkLen, algorithm } = params;
  24361. const key = pbkdf2(password, salt, count, dkLen, algorithm);
  24362. return getAccount(data, key);
  24363. }
  24364. assert(params.name === "scrypt", "cannot be reached", "UNKNOWN_ERROR", { params });
  24365. const { salt, N, r, p, dkLen } = params;
  24366. const key = scryptSync(password, salt, N, r, p, dkLen);
  24367. return getAccount(data, key);
  24368. }
  24369. function stall$1(duration) {
  24370. return new Promise((resolve) => { setTimeout(() => { resolve(); }, duration); });
  24371. }
  24372. /**
  24373. * Resolves to the decrypted JSON Keystore Wallet %%json%% using the
  24374. * %%password%%.
  24375. *
  24376. * If provided, %%progress%% will be called periodically during the
  24377. * decrpytion to provide feedback, and if the function returns
  24378. * ``false`` will halt decryption.
  24379. *
  24380. * The %%progressCallback%% will **always** receive ``0`` before
  24381. * decryption begins and ``1`` when complete.
  24382. */
  24383. async function decryptKeystoreJson(json, _password, progress) {
  24384. const data = JSON.parse(json);
  24385. const password = getPassword(_password);
  24386. const params = getDecryptKdfParams(data);
  24387. if (params.name === "pbkdf2") {
  24388. if (progress) {
  24389. progress(0);
  24390. await stall$1(0);
  24391. }
  24392. const { salt, count, dkLen, algorithm } = params;
  24393. const key = pbkdf2(password, salt, count, dkLen, algorithm);
  24394. if (progress) {
  24395. progress(1);
  24396. await stall$1(0);
  24397. }
  24398. return getAccount(data, key);
  24399. }
  24400. assert(params.name === "scrypt", "cannot be reached", "UNKNOWN_ERROR", { params });
  24401. const { salt, N, r, p, dkLen } = params;
  24402. const key = await scrypt(password, salt, N, r, p, dkLen, progress);
  24403. return getAccount(data, key);
  24404. }
  24405. function getEncryptKdfParams(options) {
  24406. // Check/generate the salt
  24407. const salt = (options.salt != null) ? getBytes(options.salt, "options.salt") : randomBytes(32);
  24408. // Override the scrypt password-based key derivation function parameters
  24409. let N = (1 << 17), r = 8, p = 1;
  24410. if (options.scrypt) {
  24411. if (options.scrypt.N) {
  24412. N = options.scrypt.N;
  24413. }
  24414. if (options.scrypt.r) {
  24415. r = options.scrypt.r;
  24416. }
  24417. if (options.scrypt.p) {
  24418. p = options.scrypt.p;
  24419. }
  24420. }
  24421. assertArgument(typeof (N) === "number" && N > 0 && Number.isSafeInteger(N) && (BigInt(N) & BigInt(N - 1)) === BigInt(0), "invalid scrypt N parameter", "options.N", N);
  24422. assertArgument(typeof (r) === "number" && r > 0 && Number.isSafeInteger(r), "invalid scrypt r parameter", "options.r", r);
  24423. assertArgument(typeof (p) === "number" && p > 0 && Number.isSafeInteger(p), "invalid scrypt p parameter", "options.p", p);
  24424. return { name: "scrypt", dkLen: 32, salt, N, r, p };
  24425. }
  24426. function _encryptKeystore(key, kdf, account, options) {
  24427. const privateKey = getBytes(account.privateKey, "privateKey");
  24428. // Override initialization vector
  24429. const iv = (options.iv != null) ? getBytes(options.iv, "options.iv") : randomBytes(16);
  24430. assertArgument(iv.length === 16, "invalid options.iv length", "options.iv", options.iv);
  24431. // Override the uuid
  24432. const uuidRandom = (options.uuid != null) ? getBytes(options.uuid, "options.uuid") : randomBytes(16);
  24433. assertArgument(uuidRandom.length === 16, "invalid options.uuid length", "options.uuid", options.iv);
  24434. // This will be used to encrypt the wallet (as per Web3 secret storage)
  24435. // - 32 bytes As normal for the Web3 secret storage (derivedKey, macPrefix)
  24436. // - 32 bytes AES key to encrypt mnemonic with (required here to be Ethers Wallet)
  24437. const derivedKey = key.slice(0, 16);
  24438. const macPrefix = key.slice(16, 32);
  24439. // Encrypt the private key
  24440. const aesCtr = new CTR(derivedKey, iv);
  24441. const ciphertext = getBytes(aesCtr.encrypt(privateKey));
  24442. // Compute the message authentication code, used to check the password
  24443. const mac = keccak256(concat([macPrefix, ciphertext]));
  24444. // See: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition
  24445. const data = {
  24446. address: account.address.substring(2).toLowerCase(),
  24447. id: uuidV4(uuidRandom),
  24448. version: 3,
  24449. Crypto: {
  24450. cipher: "aes-128-ctr",
  24451. cipherparams: {
  24452. iv: hexlify(iv).substring(2),
  24453. },
  24454. ciphertext: hexlify(ciphertext).substring(2),
  24455. kdf: "scrypt",
  24456. kdfparams: {
  24457. salt: hexlify(kdf.salt).substring(2),
  24458. n: kdf.N,
  24459. dklen: 32,
  24460. p: kdf.p,
  24461. r: kdf.r
  24462. },
  24463. mac: mac.substring(2)
  24464. }
  24465. };
  24466. // If we have a mnemonic, encrypt it into the JSON wallet
  24467. if (account.mnemonic) {
  24468. const client = (options.client != null) ? options.client : `ethers/${version}`;
  24469. const path = account.mnemonic.path || defaultPath$1;
  24470. const locale = account.mnemonic.locale || "en";
  24471. const mnemonicKey = key.slice(32, 64);
  24472. const entropy = getBytes(account.mnemonic.entropy, "account.mnemonic.entropy");
  24473. const mnemonicIv = randomBytes(16);
  24474. const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv);
  24475. const mnemonicCiphertext = getBytes(mnemonicAesCtr.encrypt(entropy));
  24476. const now = new Date();
  24477. const timestamp = (now.getUTCFullYear() + "-" +
  24478. zpad$1(now.getUTCMonth() + 1, 2) + "-" +
  24479. zpad$1(now.getUTCDate(), 2) + "T" +
  24480. zpad$1(now.getUTCHours(), 2) + "-" +
  24481. zpad$1(now.getUTCMinutes(), 2) + "-" +
  24482. zpad$1(now.getUTCSeconds(), 2) + ".0Z");
  24483. const gethFilename = ("UTC--" + timestamp + "--" + data.address);
  24484. data["x-ethers"] = {
  24485. client, gethFilename, path, locale,
  24486. mnemonicCounter: hexlify(mnemonicIv).substring(2),
  24487. mnemonicCiphertext: hexlify(mnemonicCiphertext).substring(2),
  24488. version: "0.1"
  24489. };
  24490. }
  24491. return JSON.stringify(data);
  24492. }
  24493. /**
  24494. * Return the JSON Keystore Wallet for %%account%% encrypted with
  24495. * %%password%%.
  24496. *
  24497. * The %%options%% can be used to tune the password-based key
  24498. * derivation function parameters, explicitly set the random values
  24499. * used. Any provided [[ProgressCallback]] is ignord.
  24500. */
  24501. function encryptKeystoreJsonSync(account, password, options) {
  24502. if (options == null) {
  24503. options = {};
  24504. }
  24505. const passwordBytes = getPassword(password);
  24506. const kdf = getEncryptKdfParams(options);
  24507. const key = scryptSync(passwordBytes, kdf.salt, kdf.N, kdf.r, kdf.p, 64);
  24508. return _encryptKeystore(getBytes(key), kdf, account, options);
  24509. }
  24510. /**
  24511. * Resolved to the JSON Keystore Wallet for %%account%% encrypted
  24512. * with %%password%%.
  24513. *
  24514. * The %%options%% can be used to tune the password-based key
  24515. * derivation function parameters, explicitly set the random values
  24516. * used and provide a [[ProgressCallback]] to receive periodic updates
  24517. * on the completion status..
  24518. */
  24519. async function encryptKeystoreJson(account, password, options) {
  24520. if (options == null) {
  24521. options = {};
  24522. }
  24523. const passwordBytes = getPassword(password);
  24524. const kdf = getEncryptKdfParams(options);
  24525. const key = await scrypt(passwordBytes, kdf.salt, kdf.N, kdf.r, kdf.p, 64, options.progressCallback);
  24526. return _encryptKeystore(getBytes(key), kdf, account, options);
  24527. }
  24528. /**
  24529. * Explain HD Wallets..
  24530. *
  24531. * @_subsection: api/wallet:HD Wallets [hd-wallets]
  24532. */
  24533. /**
  24534. * The default derivation path for Ethereum HD Nodes. (i.e. ``"m/44'/60'/0'/0/0"``)
  24535. */
  24536. const defaultPath = "m/44'/60'/0'/0/0";
  24537. // "Bitcoin seed"
  24538. const MasterSecret = new Uint8Array([66, 105, 116, 99, 111, 105, 110, 32, 115, 101, 101, 100]);
  24539. const HardenedBit = 0x80000000;
  24540. const N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");
  24541. const Nibbles = "0123456789abcdef";
  24542. function zpad(value, length) {
  24543. let result = "";
  24544. while (value) {
  24545. result = Nibbles[value % 16] + result;
  24546. value = Math.trunc(value / 16);
  24547. }
  24548. while (result.length < length * 2) {
  24549. result = "0" + result;
  24550. }
  24551. return "0x" + result;
  24552. }
  24553. function encodeBase58Check(_value) {
  24554. const value = getBytes(_value);
  24555. const check = dataSlice(sha256(sha256(value)), 0, 4);
  24556. const bytes = concat([value, check]);
  24557. return encodeBase58(bytes);
  24558. }
  24559. const _guard = {};
  24560. function ser_I(index, chainCode, publicKey, privateKey) {
  24561. const data = new Uint8Array(37);
  24562. if (index & HardenedBit) {
  24563. assert(privateKey != null, "cannot derive child of neutered node", "UNSUPPORTED_OPERATION", {
  24564. operation: "deriveChild"
  24565. });
  24566. // Data = 0x00 || ser_256(k_par)
  24567. data.set(getBytes(privateKey), 1);
  24568. }
  24569. else {
  24570. // Data = ser_p(point(k_par))
  24571. data.set(getBytes(publicKey));
  24572. }
  24573. // Data += ser_32(i)
  24574. for (let i = 24; i >= 0; i -= 8) {
  24575. data[33 + (i >> 3)] = ((index >> (24 - i)) & 0xff);
  24576. }
  24577. const I = getBytes(computeHmac("sha512", chainCode, data));
  24578. return { IL: I.slice(0, 32), IR: I.slice(32) };
  24579. }
  24580. function derivePath(node, path) {
  24581. const components = path.split("/");
  24582. assertArgument(components.length > 0, "invalid path", "path", path);
  24583. if (components[0] === "m") {
  24584. 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);
  24585. components.shift();
  24586. }
  24587. let result = node;
  24588. for (let i = 0; i < components.length; i++) {
  24589. const component = components[i];
  24590. if (component.match(/^[0-9]+'$/)) {
  24591. const index = parseInt(component.substring(0, component.length - 1));
  24592. assertArgument(index < HardenedBit, "invalid path index", `path[${i}]`, component);
  24593. result = result.deriveChild(HardenedBit + index);
  24594. }
  24595. else if (component.match(/^[0-9]+$/)) {
  24596. const index = parseInt(component);
  24597. assertArgument(index < HardenedBit, "invalid path index", `path[${i}]`, component);
  24598. result = result.deriveChild(index);
  24599. }
  24600. else {
  24601. assertArgument(false, "invalid path component", `path[${i}]`, component);
  24602. }
  24603. }
  24604. return result;
  24605. }
  24606. /**
  24607. * An **HDNodeWallet** is a [[Signer]] backed by the private key derived
  24608. * from an HD Node using the [[link-bip-32]] stantard.
  24609. *
  24610. * An HD Node forms a hierarchal structure with each HD Node having a
  24611. * private key and the ability to derive child HD Nodes, defined by
  24612. * a path indicating the index of each child.
  24613. */
  24614. class HDNodeWallet extends BaseWallet {
  24615. /**
  24616. * The compressed public key.
  24617. */
  24618. publicKey;
  24619. /**
  24620. * The fingerprint.
  24621. *
  24622. * A fingerprint allows quick qay to detect parent and child nodes,
  24623. * but developers should be prepared to deal with collisions as it
  24624. * is only 4 bytes.
  24625. */
  24626. fingerprint;
  24627. /**
  24628. * The parent fingerprint.
  24629. */
  24630. parentFingerprint;
  24631. /**
  24632. * The mnemonic used to create this HD Node, if available.
  24633. *
  24634. * Sources such as extended keys do not encode the mnemonic, in
  24635. * which case this will be ``null``.
  24636. */
  24637. mnemonic;
  24638. /**
  24639. * The chaincode, which is effectively a public key used
  24640. * to derive children.
  24641. */
  24642. chainCode;
  24643. /**
  24644. * The derivation path of this wallet.
  24645. *
  24646. * Since extended keys do not provide full path details, this
  24647. * may be ``null``, if instantiated from a source that does not
  24648. * encode it.
  24649. */
  24650. path;
  24651. /**
  24652. * The child index of this wallet. Values over ``2 *\* 31`` indicate
  24653. * the node is hardened.
  24654. */
  24655. index;
  24656. /**
  24657. * The depth of this wallet, which is the number of components
  24658. * in its path.
  24659. */
  24660. depth;
  24661. /**
  24662. * @private
  24663. */
  24664. constructor(guard, signingKey, parentFingerprint, chainCode, path, index, depth, mnemonic, provider) {
  24665. super(signingKey, provider);
  24666. assertPrivate(guard, _guard, "HDNodeWallet");
  24667. defineProperties(this, { publicKey: signingKey.compressedPublicKey });
  24668. const fingerprint = dataSlice(ripemd160(sha256(this.publicKey)), 0, 4);
  24669. defineProperties(this, {
  24670. parentFingerprint, fingerprint,
  24671. chainCode, path, index, depth
  24672. });
  24673. defineProperties(this, { mnemonic });
  24674. }
  24675. connect(provider) {
  24676. return new HDNodeWallet(_guard, this.signingKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.mnemonic, provider);
  24677. }
  24678. #account() {
  24679. const account = { address: this.address, privateKey: this.privateKey };
  24680. const m = this.mnemonic;
  24681. if (this.path && m && m.wordlist.locale === "en" && m.password === "") {
  24682. account.mnemonic = {
  24683. path: this.path,
  24684. locale: "en",
  24685. entropy: m.entropy
  24686. };
  24687. }
  24688. return account;
  24689. }
  24690. /**
  24691. * Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with
  24692. * %%password%%.
  24693. *
  24694. * If %%progressCallback%% is specified, it will receive periodic
  24695. * updates as the encryption process progreses.
  24696. */
  24697. async encrypt(password, progressCallback) {
  24698. return await encryptKeystoreJson(this.#account(), password, { progressCallback });
  24699. }
  24700. /**
  24701. * Returns a [JSON Keystore Wallet](json-wallets) encryped with
  24702. * %%password%%.
  24703. *
  24704. * It is preferred to use the [async version](encrypt) instead,
  24705. * which allows a [[ProgressCallback]] to keep the user informed.
  24706. *
  24707. * This method will block the event loop (freezing all UI) until
  24708. * it is complete, which may be a non-trivial duration.
  24709. */
  24710. encryptSync(password) {
  24711. return encryptKeystoreJsonSync(this.#account(), password);
  24712. }
  24713. /**
  24714. * The extended key.
  24715. *
  24716. * This key will begin with the prefix ``xpriv`` and can be used to
  24717. * reconstruct this HD Node to derive its children.
  24718. */
  24719. get extendedKey() {
  24720. // We only support the mainnet values for now, but if anyone needs
  24721. // testnet values, let me know. I believe current sentiment is that
  24722. // we should always use mainnet, and use BIP-44 to derive the network
  24723. // - Mainnet: public=0x0488B21E, private=0x0488ADE4
  24724. // - Testnet: public=0x043587CF, private=0x04358394
  24725. assert(this.depth < 256, "Depth too deep", "UNSUPPORTED_OPERATION", { operation: "extendedKey" });
  24726. return encodeBase58Check(concat([
  24727. "0x0488ADE4", zpad(this.depth, 1), this.parentFingerprint,
  24728. zpad(this.index, 4), this.chainCode,
  24729. concat(["0x00", this.privateKey])
  24730. ]));
  24731. }
  24732. /**
  24733. * Returns true if this wallet has a path, providing a Type Guard
  24734. * that the path is non-null.
  24735. */
  24736. hasPath() { return (this.path != null); }
  24737. /**
  24738. * Returns a neutered HD Node, which removes the private details
  24739. * of an HD Node.
  24740. *
  24741. * A neutered node has no private key, but can be used to derive
  24742. * child addresses and other public data about the HD Node.
  24743. */
  24744. neuter() {
  24745. return new HDNodeVoidWallet(_guard, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.provider);
  24746. }
  24747. /**
  24748. * Return the child for %%index%%.
  24749. */
  24750. deriveChild(_index) {
  24751. const index = getNumber(_index, "index");
  24752. assertArgument(index <= 0xffffffff, "invalid index", "index", index);
  24753. // Base path
  24754. let path = this.path;
  24755. if (path) {
  24756. path += "/" + (index & ~HardenedBit);
  24757. if (index & HardenedBit) {
  24758. path += "'";
  24759. }
  24760. }
  24761. const { IR, IL } = ser_I(index, this.chainCode, this.publicKey, this.privateKey);
  24762. const ki = new SigningKey(toBeHex((toBigInt(IL) + BigInt(this.privateKey)) % N, 32));
  24763. return new HDNodeWallet(_guard, ki, this.fingerprint, hexlify(IR), path, index, this.depth + 1, this.mnemonic, this.provider);
  24764. }
  24765. /**
  24766. * Return the HDNode for %%path%% from this node.
  24767. */
  24768. derivePath(path) {
  24769. return derivePath(this, path);
  24770. }
  24771. static #fromSeed(_seed, mnemonic) {
  24772. assertArgument(isBytesLike(_seed), "invalid seed", "seed", "[REDACTED]");
  24773. const seed = getBytes(_seed, "seed");
  24774. assertArgument(seed.length >= 16 && seed.length <= 64, "invalid seed", "seed", "[REDACTED]");
  24775. const I = getBytes(computeHmac("sha512", MasterSecret, seed));
  24776. const signingKey = new SigningKey(hexlify(I.slice(0, 32)));
  24777. return new HDNodeWallet(_guard, signingKey, "0x00000000", hexlify(I.slice(32)), "m", 0, 0, mnemonic, null);
  24778. }
  24779. /**
  24780. * Creates a new HD Node from %%extendedKey%%.
  24781. *
  24782. * If the %%extendedKey%% will either have a prefix or ``xpub`` or
  24783. * ``xpriv``, returning a neutered HD Node ([[HDNodeVoidWallet]])
  24784. * or full HD Node ([[HDNodeWallet) respectively.
  24785. */
  24786. static fromExtendedKey(extendedKey) {
  24787. const bytes = toBeArray(decodeBase58(extendedKey)); // @TODO: redact
  24788. assertArgument(bytes.length === 82 || encodeBase58Check(bytes.slice(0, 78)) === extendedKey, "invalid extended key", "extendedKey", "[ REDACTED ]");
  24789. const depth = bytes[4];
  24790. const parentFingerprint = hexlify(bytes.slice(5, 9));
  24791. const index = parseInt(hexlify(bytes.slice(9, 13)).substring(2), 16);
  24792. const chainCode = hexlify(bytes.slice(13, 45));
  24793. const key = bytes.slice(45, 78);
  24794. switch (hexlify(bytes.slice(0, 4))) {
  24795. // Public Key
  24796. case "0x0488b21e":
  24797. case "0x043587cf": {
  24798. const publicKey = hexlify(key);
  24799. return new HDNodeVoidWallet(_guard, computeAddress(publicKey), publicKey, parentFingerprint, chainCode, null, index, depth, null);
  24800. }
  24801. // Private Key
  24802. case "0x0488ade4":
  24803. case "0x04358394 ":
  24804. if (key[0] !== 0) {
  24805. break;
  24806. }
  24807. return new HDNodeWallet(_guard, new SigningKey(key.slice(1)), parentFingerprint, chainCode, null, index, depth, null, null);
  24808. }
  24809. assertArgument(false, "invalid extended key prefix", "extendedKey", "[ REDACTED ]");
  24810. }
  24811. /**
  24812. * Creates a new random HDNode.
  24813. */
  24814. static createRandom(password, path, wordlist) {
  24815. if (password == null) {
  24816. password = "";
  24817. }
  24818. if (path == null) {
  24819. path = defaultPath;
  24820. }
  24821. if (wordlist == null) {
  24822. wordlist = LangEn.wordlist();
  24823. }
  24824. const mnemonic = Mnemonic.fromEntropy(randomBytes(16), password, wordlist);
  24825. return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path);
  24826. }
  24827. /**
  24828. * Create an HD Node from %%mnemonic%%.
  24829. */
  24830. static fromMnemonic(mnemonic, path) {
  24831. if (!path) {
  24832. path = defaultPath;
  24833. }
  24834. return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path);
  24835. }
  24836. /**
  24837. * Creates an HD Node from a mnemonic %%phrase%%.
  24838. */
  24839. static fromPhrase(phrase, password, path, wordlist) {
  24840. if (password == null) {
  24841. password = "";
  24842. }
  24843. if (path == null) {
  24844. path = defaultPath;
  24845. }
  24846. if (wordlist == null) {
  24847. wordlist = LangEn.wordlist();
  24848. }
  24849. const mnemonic = Mnemonic.fromPhrase(phrase, password, wordlist);
  24850. return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path);
  24851. }
  24852. /**
  24853. * Creates an HD Node from a %%seed%%.
  24854. */
  24855. static fromSeed(seed) {
  24856. return HDNodeWallet.#fromSeed(seed, null);
  24857. }
  24858. }
  24859. /**
  24860. * A **HDNodeVoidWallet** cannot sign, but provides access to
  24861. * the children nodes of a [[link-bip-32]] HD wallet addresses.
  24862. *
  24863. * The can be created by using an extended ``xpub`` key to
  24864. * [[HDNodeWallet_fromExtendedKey]] or by
  24865. * [nuetering](HDNodeWallet-neuter) a [[HDNodeWallet]].
  24866. */
  24867. class HDNodeVoidWallet extends VoidSigner {
  24868. /**
  24869. * The compressed public key.
  24870. */
  24871. publicKey;
  24872. /**
  24873. * The fingerprint.
  24874. *
  24875. * A fingerprint allows quick qay to detect parent and child nodes,
  24876. * but developers should be prepared to deal with collisions as it
  24877. * is only 4 bytes.
  24878. */
  24879. fingerprint;
  24880. /**
  24881. * The parent node fingerprint.
  24882. */
  24883. parentFingerprint;
  24884. /**
  24885. * The chaincode, which is effectively a public key used
  24886. * to derive children.
  24887. */
  24888. chainCode;
  24889. /**
  24890. * The derivation path of this wallet.
  24891. *
  24892. * Since extended keys do not provider full path details, this
  24893. * may be ``null``, if instantiated from a source that does not
  24894. * enocde it.
  24895. */
  24896. path;
  24897. /**
  24898. * The child index of this wallet. Values over ``2 *\* 31`` indicate
  24899. * the node is hardened.
  24900. */
  24901. index;
  24902. /**
  24903. * The depth of this wallet, which is the number of components
  24904. * in its path.
  24905. */
  24906. depth;
  24907. /**
  24908. * @private
  24909. */
  24910. constructor(guard, address, publicKey, parentFingerprint, chainCode, path, index, depth, provider) {
  24911. super(address, provider);
  24912. assertPrivate(guard, _guard, "HDNodeVoidWallet");
  24913. defineProperties(this, { publicKey });
  24914. const fingerprint = dataSlice(ripemd160(sha256(publicKey)), 0, 4);
  24915. defineProperties(this, {
  24916. publicKey, fingerprint, parentFingerprint, chainCode, path, index, depth
  24917. });
  24918. }
  24919. connect(provider) {
  24920. return new HDNodeVoidWallet(_guard, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, provider);
  24921. }
  24922. /**
  24923. * The extended key.
  24924. *
  24925. * This key will begin with the prefix ``xpub`` and can be used to
  24926. * reconstruct this neutered key to derive its children addresses.
  24927. */
  24928. get extendedKey() {
  24929. // We only support the mainnet values for now, but if anyone needs
  24930. // testnet values, let me know. I believe current sentiment is that
  24931. // we should always use mainnet, and use BIP-44 to derive the network
  24932. // - Mainnet: public=0x0488B21E, private=0x0488ADE4
  24933. // - Testnet: public=0x043587CF, private=0x04358394
  24934. assert(this.depth < 256, "Depth too deep", "UNSUPPORTED_OPERATION", { operation: "extendedKey" });
  24935. return encodeBase58Check(concat([
  24936. "0x0488B21E",
  24937. zpad(this.depth, 1),
  24938. this.parentFingerprint,
  24939. zpad(this.index, 4),
  24940. this.chainCode,
  24941. this.publicKey,
  24942. ]));
  24943. }
  24944. /**
  24945. * Returns true if this wallet has a path, providing a Type Guard
  24946. * that the path is non-null.
  24947. */
  24948. hasPath() { return (this.path != null); }
  24949. /**
  24950. * Return the child for %%index%%.
  24951. */
  24952. deriveChild(_index) {
  24953. const index = getNumber(_index, "index");
  24954. assertArgument(index <= 0xffffffff, "invalid index", "index", index);
  24955. // Base path
  24956. let path = this.path;
  24957. if (path) {
  24958. path += "/" + (index & ~HardenedBit);
  24959. if (index & HardenedBit) {
  24960. path += "'";
  24961. }
  24962. }
  24963. const { IR, IL } = ser_I(index, this.chainCode, this.publicKey, null);
  24964. const Ki = SigningKey.addPoints(IL, this.publicKey, true);
  24965. const address = computeAddress(Ki);
  24966. return new HDNodeVoidWallet(_guard, address, Ki, this.fingerprint, hexlify(IR), path, index, this.depth + 1, this.provider);
  24967. }
  24968. /**
  24969. * Return the signer for %%path%% from this node.
  24970. */
  24971. derivePath(path) {
  24972. return derivePath(this, path);
  24973. }
  24974. }
  24975. /*
  24976. export class HDNodeWalletManager {
  24977. #root: HDNodeWallet;
  24978. constructor(phrase: string, password?: null | string, path?: null | string, locale?: null | Wordlist) {
  24979. if (password == null) { password = ""; }
  24980. if (path == null) { path = "m/44'/60'/0'/0"; }
  24981. if (locale == null) { locale = LangEn.wordlist(); }
  24982. this.#root = HDNodeWallet.fromPhrase(phrase, password, path, locale);
  24983. }
  24984. getSigner(index?: number): HDNodeWallet {
  24985. return this.#root.deriveChild((index == null) ? 0: index);
  24986. }
  24987. }
  24988. */
  24989. /**
  24990. * Returns the [[link-bip-32]] path for the account at %%index%%.
  24991. *
  24992. * This is the pattern used by wallets like Ledger.
  24993. *
  24994. * There is also an [alternate pattern](getIndexedAccountPath) used by
  24995. * some software.
  24996. */
  24997. function getAccountPath(_index) {
  24998. const index = getNumber(_index, "index");
  24999. assertArgument(index >= 0 && index < HardenedBit, "invalid account index", "index", index);
  25000. return `m/44'/60'/${index}'/0/0`;
  25001. }
  25002. /**
  25003. * Returns the path using an alternative pattern for deriving accounts,
  25004. * at %%index%%.
  25005. *
  25006. * This derivation path uses the //index// component rather than the
  25007. * //account// component to derive sequential accounts.
  25008. *
  25009. * This is the pattern used by wallets like MetaMask.
  25010. */
  25011. function getIndexedAccountPath(_index) {
  25012. const index = getNumber(_index, "index");
  25013. assertArgument(index >= 0 && index < HardenedBit, "invalid account index", "index", index);
  25014. return `m/44'/60'/0'/0/${index}`;
  25015. }
  25016. /**
  25017. * @_subsection: api/wallet:JSON Wallets [json-wallets]
  25018. */
  25019. /**
  25020. * Returns true if %%json%% is a valid JSON Crowdsale wallet.
  25021. */
  25022. function isCrowdsaleJson(json) {
  25023. try {
  25024. const data = JSON.parse(json);
  25025. if (data.encseed) {
  25026. return true;
  25027. }
  25028. }
  25029. catch (error) { }
  25030. return false;
  25031. }
  25032. // See: https://github.com/ethereum/pyethsaletool
  25033. /**
  25034. * Before Ethereum launched, it was necessary to create a wallet
  25035. * format for backers to use, which would be used to receive ether
  25036. * as a reward for contributing to the project.
  25037. *
  25038. * The [[link-crowdsale]] format is now obsolete, but it is still
  25039. * useful to support and the additional code is fairly trivial as
  25040. * all the primitives required are used through core portions of
  25041. * the library.
  25042. */
  25043. function decryptCrowdsaleJson(json, _password) {
  25044. const data = JSON.parse(json);
  25045. const password = getPassword(_password);
  25046. // Ethereum Address
  25047. const address = getAddress(spelunk(data, "ethaddr:string!"));
  25048. // Encrypted Seed
  25049. const encseed = looseArrayify(spelunk(data, "encseed:string!"));
  25050. assertArgument(encseed && (encseed.length % 16) === 0, "invalid encseed", "json", json);
  25051. const key = getBytes(pbkdf2(password, password, 2000, 32, "sha256")).slice(0, 16);
  25052. const iv = encseed.slice(0, 16);
  25053. const encryptedSeed = encseed.slice(16);
  25054. // Decrypt the seed
  25055. const aesCbc = new CBC(key, iv);
  25056. const seed = pkcs7Strip(getBytes(aesCbc.decrypt(encryptedSeed)));
  25057. // This wallet format is weird... Convert the binary encoded hex to a string.
  25058. let seedHex = "";
  25059. for (let i = 0; i < seed.length; i++) {
  25060. seedHex += String.fromCharCode(seed[i]);
  25061. }
  25062. return { address, privateKey: id(seedHex) };
  25063. }
  25064. function stall(duration) {
  25065. return new Promise((resolve) => { setTimeout(() => { resolve(); }, duration); });
  25066. }
  25067. /**
  25068. * A **Wallet** manages a single private key which is used to sign
  25069. * transactions, messages and other common payloads.
  25070. *
  25071. * This class is generally the main entry point for developers
  25072. * that wish to use a private key directly, as it can create
  25073. * instances from a large variety of common sources, including
  25074. * raw private key, [[link-bip-39]] mnemonics and encrypte JSON
  25075. * wallets.
  25076. */
  25077. class Wallet extends BaseWallet {
  25078. /**
  25079. * Create a new wallet for the private %%key%%, optionally connected
  25080. * to %%provider%%.
  25081. */
  25082. constructor(key, provider) {
  25083. if (typeof (key) === "string" && !key.startsWith("0x")) {
  25084. key = "0x" + key;
  25085. }
  25086. let signingKey = (typeof (key) === "string") ? new SigningKey(key) : key;
  25087. super(signingKey, provider);
  25088. }
  25089. connect(provider) {
  25090. return new Wallet(this.signingKey, provider);
  25091. }
  25092. /**
  25093. * Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with
  25094. * %%password%%.
  25095. *
  25096. * If %%progressCallback%% is specified, it will receive periodic
  25097. * updates as the encryption process progreses.
  25098. */
  25099. async encrypt(password, progressCallback) {
  25100. const account = { address: this.address, privateKey: this.privateKey };
  25101. return await encryptKeystoreJson(account, password, { progressCallback });
  25102. }
  25103. /**
  25104. * Returns a [JSON Keystore Wallet](json-wallets) encryped with
  25105. * %%password%%.
  25106. *
  25107. * It is preferred to use the [async version](encrypt) instead,
  25108. * which allows a [[ProgressCallback]] to keep the user informed.
  25109. *
  25110. * This method will block the event loop (freezing all UI) until
  25111. * it is complete, which may be a non-trivial duration.
  25112. */
  25113. encryptSync(password) {
  25114. const account = { address: this.address, privateKey: this.privateKey };
  25115. return encryptKeystoreJsonSync(account, password);
  25116. }
  25117. static #fromAccount(account) {
  25118. assertArgument(account, "invalid JSON wallet", "json", "[ REDACTED ]");
  25119. if ("mnemonic" in account && account.mnemonic && account.mnemonic.locale === "en") {
  25120. const mnemonic = Mnemonic.fromEntropy(account.mnemonic.entropy);
  25121. const wallet = HDNodeWallet.fromMnemonic(mnemonic, account.mnemonic.path);
  25122. if (wallet.address === account.address && wallet.privateKey === account.privateKey) {
  25123. return wallet;
  25124. }
  25125. console.log("WARNING: JSON mismatch address/privateKey != mnemonic; fallback onto private key");
  25126. }
  25127. const wallet = new Wallet(account.privateKey);
  25128. assertArgument(wallet.address === account.address, "address/privateKey mismatch", "json", "[ REDACTED ]");
  25129. return wallet;
  25130. }
  25131. /**
  25132. * Creates (asynchronously) a **Wallet** by decrypting the %%json%%
  25133. * with %%password%%.
  25134. *
  25135. * If %%progress%% is provided, it is called periodically during
  25136. * decryption so that any UI can be updated.
  25137. */
  25138. static async fromEncryptedJson(json, password, progress) {
  25139. let account = null;
  25140. if (isKeystoreJson(json)) {
  25141. account = await decryptKeystoreJson(json, password, progress);
  25142. }
  25143. else if (isCrowdsaleJson(json)) {
  25144. if (progress) {
  25145. progress(0);
  25146. await stall(0);
  25147. }
  25148. account = decryptCrowdsaleJson(json, password);
  25149. if (progress) {
  25150. progress(1);
  25151. await stall(0);
  25152. }
  25153. }
  25154. return Wallet.#fromAccount(account);
  25155. }
  25156. /**
  25157. * Creates a **Wallet** by decrypting the %%json%% with %%password%%.
  25158. *
  25159. * The [[fromEncryptedJson]] method is preferred, as this method
  25160. * will lock up and freeze the UI during decryption, which may take
  25161. * some time.
  25162. */
  25163. static fromEncryptedJsonSync(json, password) {
  25164. let account = null;
  25165. if (isKeystoreJson(json)) {
  25166. account = decryptKeystoreJsonSync(json, password);
  25167. }
  25168. else if (isCrowdsaleJson(json)) {
  25169. account = decryptCrowdsaleJson(json, password);
  25170. }
  25171. else {
  25172. assertArgument(false, "invalid JSON wallet", "json", "[ REDACTED ]");
  25173. }
  25174. return Wallet.#fromAccount(account);
  25175. }
  25176. /**
  25177. * Creates a new random [[HDNodeWallet]] using the available
  25178. * [cryptographic random source](randomBytes).
  25179. *
  25180. * If there is no crytographic random source, this will throw.
  25181. */
  25182. static createRandom(provider) {
  25183. const wallet = HDNodeWallet.createRandom();
  25184. if (provider) {
  25185. return wallet.connect(provider);
  25186. }
  25187. return wallet;
  25188. }
  25189. /**
  25190. * Creates a [[HDNodeWallet]] for %%phrase%%.
  25191. */
  25192. static fromPhrase(phrase, provider) {
  25193. const wallet = HDNodeWallet.fromPhrase(phrase);
  25194. if (provider) {
  25195. return wallet.connect(provider);
  25196. }
  25197. return wallet;
  25198. }
  25199. }
  25200. const Base64 = ")!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_";
  25201. /**
  25202. * @_ignore
  25203. */
  25204. function decodeBits(width, data) {
  25205. const maxValue = (1 << width) - 1;
  25206. const result = [];
  25207. let accum = 0, bits = 0, flood = 0;
  25208. for (let i = 0; i < data.length; i++) {
  25209. // Accumulate 6 bits of data
  25210. accum = ((accum << 6) | Base64.indexOf(data[i]));
  25211. bits += 6;
  25212. // While we have enough for a word...
  25213. while (bits >= width) {
  25214. // ...read the word
  25215. const value = (accum >> (bits - width));
  25216. accum &= (1 << (bits - width)) - 1;
  25217. bits -= width;
  25218. // A value of 0 indicates we exceeded maxValue, it
  25219. // floods over into the next value
  25220. if (value === 0) {
  25221. flood += maxValue;
  25222. }
  25223. else {
  25224. result.push(value + flood);
  25225. flood = 0;
  25226. }
  25227. }
  25228. }
  25229. return result;
  25230. }
  25231. /**
  25232. * @_ignore
  25233. */
  25234. function decodeOwlA(data, accents) {
  25235. let words = decodeOwl(data).join(",");
  25236. // Inject the accents
  25237. accents.split(/,/g).forEach((accent) => {
  25238. const match = accent.match(/^([a-z]*)([0-9]+)([0-9])(.*)$/);
  25239. assertArgument(match !== null, "internal error parsing accents", "accents", accents);
  25240. let posOffset = 0;
  25241. const positions = decodeBits(parseInt(match[3]), match[4]);
  25242. const charCode = parseInt(match[2]);
  25243. const regex = new RegExp(`([${match[1]}])`, "g");
  25244. words = words.replace(regex, (all, letter) => {
  25245. const rem = --positions[posOffset];
  25246. if (rem === 0) {
  25247. letter = String.fromCharCode(letter.charCodeAt(0), charCode);
  25248. posOffset++;
  25249. }
  25250. return letter;
  25251. });
  25252. });
  25253. return words.split(",");
  25254. }
  25255. /**
  25256. * An OWL-A format Wordlist extends the OWL format to add an
  25257. * overlay onto an OWL format Wordlist to support diacritic
  25258. * marks.
  25259. *
  25260. * This class is generally not useful to most developers as
  25261. * it is used mainly internally to keep Wordlists for languages
  25262. * based on latin-1 small.
  25263. *
  25264. * If necessary, there are tools within the ``generation/`` folder
  25265. * to create the necessary data.
  25266. */
  25267. class WordlistOwlA extends WordlistOwl {
  25268. #accent;
  25269. /**
  25270. * Creates a new Wordlist for %%locale%% using the OWLA %%data%%
  25271. * and %%accent%% data and validated against the %%checksum%%.
  25272. */
  25273. constructor(locale, data, accent, checksum) {
  25274. super(locale, data, checksum);
  25275. this.#accent = accent;
  25276. }
  25277. /**
  25278. * The OWLA-encoded accent data.
  25279. */
  25280. get _accent() { return this.#accent; }
  25281. /**
  25282. * Decode all the words for the wordlist.
  25283. */
  25284. _decodeWords() {
  25285. return decodeOwlA(this._data, this._accent);
  25286. }
  25287. }
  25288. const wordlists = {
  25289. en: LangEn.wordlist(),
  25290. };
  25291. /////////////////////////////
  25292. //
  25293. // dummy change; to pick-up ws security issue changes
  25294. var ethers = /*#__PURE__*/Object.freeze({
  25295. __proto__: null,
  25296. AbiCoder: AbiCoder,
  25297. AbstractProvider: AbstractProvider,
  25298. AbstractSigner: AbstractSigner,
  25299. AlchemyProvider: AlchemyProvider,
  25300. AnkrProvider: AnkrProvider,
  25301. BaseContract: BaseContract,
  25302. BaseWallet: BaseWallet,
  25303. Block: Block,
  25304. BrowserProvider: BrowserProvider,
  25305. ChainstackProvider: ChainstackProvider,
  25306. CloudflareProvider: CloudflareProvider,
  25307. ConstructorFragment: ConstructorFragment,
  25308. Contract: Contract,
  25309. ContractEventPayload: ContractEventPayload,
  25310. ContractFactory: ContractFactory,
  25311. ContractTransactionReceipt: ContractTransactionReceipt,
  25312. ContractTransactionResponse: ContractTransactionResponse,
  25313. ContractUnknownEventPayload: ContractUnknownEventPayload,
  25314. EnsPlugin: EnsPlugin,
  25315. EnsResolver: EnsResolver,
  25316. ErrorDescription: ErrorDescription,
  25317. ErrorFragment: ErrorFragment,
  25318. EtherSymbol: EtherSymbol,
  25319. EtherscanPlugin: EtherscanPlugin,
  25320. EtherscanProvider: EtherscanProvider,
  25321. EventFragment: EventFragment,
  25322. EventLog: EventLog,
  25323. EventPayload: EventPayload,
  25324. FallbackFragment: FallbackFragment,
  25325. FallbackProvider: FallbackProvider,
  25326. FeeData: FeeData,
  25327. FeeDataNetworkPlugin: FeeDataNetworkPlugin,
  25328. FetchCancelSignal: FetchCancelSignal,
  25329. FetchRequest: FetchRequest,
  25330. FetchResponse: FetchResponse,
  25331. FetchUrlFeeDataNetworkPlugin: FetchUrlFeeDataNetworkPlugin,
  25332. FixedNumber: FixedNumber,
  25333. Fragment: Fragment,
  25334. FunctionFragment: FunctionFragment,
  25335. GasCostPlugin: GasCostPlugin,
  25336. HDNodeVoidWallet: HDNodeVoidWallet,
  25337. HDNodeWallet: HDNodeWallet,
  25338. Indexed: Indexed,
  25339. InfuraProvider: InfuraProvider,
  25340. InfuraWebSocketProvider: InfuraWebSocketProvider,
  25341. Interface: Interface,
  25342. IpcSocketProvider: IpcSocketProvider,
  25343. JsonRpcApiProvider: JsonRpcApiProvider,
  25344. JsonRpcProvider: JsonRpcProvider,
  25345. JsonRpcSigner: JsonRpcSigner,
  25346. LangEn: LangEn,
  25347. Log: Log,
  25348. LogDescription: LogDescription,
  25349. MaxInt256: MaxInt256,
  25350. MaxUint256: MaxUint256,
  25351. MessagePrefix: MessagePrefix,
  25352. MinInt256: MinInt256,
  25353. Mnemonic: Mnemonic,
  25354. MulticoinProviderPlugin: MulticoinProviderPlugin,
  25355. N: N$1,
  25356. NamedFragment: NamedFragment,
  25357. Network: Network,
  25358. NetworkPlugin: NetworkPlugin,
  25359. NonceManager: NonceManager,
  25360. ParamType: ParamType,
  25361. PocketProvider: PocketProvider,
  25362. QuickNodeProvider: QuickNodeProvider,
  25363. Result: Result,
  25364. Signature: Signature,
  25365. SigningKey: SigningKey,
  25366. SocketBlockSubscriber: SocketBlockSubscriber,
  25367. SocketEventSubscriber: SocketEventSubscriber,
  25368. SocketPendingSubscriber: SocketPendingSubscriber,
  25369. SocketProvider: SocketProvider,
  25370. SocketSubscriber: SocketSubscriber,
  25371. StructFragment: StructFragment,
  25372. Transaction: Transaction,
  25373. TransactionDescription: TransactionDescription,
  25374. TransactionReceipt: TransactionReceipt,
  25375. TransactionResponse: TransactionResponse,
  25376. Typed: Typed,
  25377. TypedDataEncoder: TypedDataEncoder,
  25378. UndecodedEventLog: UndecodedEventLog,
  25379. UnmanagedSubscriber: UnmanagedSubscriber,
  25380. Utf8ErrorFuncs: Utf8ErrorFuncs,
  25381. VoidSigner: VoidSigner,
  25382. Wallet: Wallet,
  25383. WebSocketProvider: WebSocketProvider,
  25384. WeiPerEther: WeiPerEther,
  25385. Wordlist: Wordlist,
  25386. WordlistOwl: WordlistOwl,
  25387. WordlistOwlA: WordlistOwlA,
  25388. ZeroAddress: ZeroAddress,
  25389. ZeroHash: ZeroHash,
  25390. accessListify: accessListify,
  25391. assert: assert,
  25392. assertArgument: assertArgument,
  25393. assertArgumentCount: assertArgumentCount,
  25394. assertNormalize: assertNormalize,
  25395. assertPrivate: assertPrivate,
  25396. checkResultErrors: checkResultErrors,
  25397. computeAddress: computeAddress,
  25398. computeHmac: computeHmac,
  25399. concat: concat,
  25400. copyRequest: copyRequest,
  25401. dataLength: dataLength,
  25402. dataSlice: dataSlice,
  25403. decodeBase58: decodeBase58,
  25404. decodeBase64: decodeBase64,
  25405. decodeBytes32String: decodeBytes32String,
  25406. decodeRlp: decodeRlp,
  25407. decryptCrowdsaleJson: decryptCrowdsaleJson,
  25408. decryptKeystoreJson: decryptKeystoreJson,
  25409. decryptKeystoreJsonSync: decryptKeystoreJsonSync,
  25410. defaultPath: defaultPath,
  25411. defineProperties: defineProperties,
  25412. dnsEncode: dnsEncode,
  25413. encodeBase58: encodeBase58,
  25414. encodeBase64: encodeBase64,
  25415. encodeBytes32String: encodeBytes32String,
  25416. encodeRlp: encodeRlp,
  25417. encryptKeystoreJson: encryptKeystoreJson,
  25418. encryptKeystoreJsonSync: encryptKeystoreJsonSync,
  25419. ensNormalize: ensNormalize,
  25420. formatEther: formatEther,
  25421. formatUnits: formatUnits,
  25422. fromTwos: fromTwos,
  25423. getAccountPath: getAccountPath,
  25424. getAddress: getAddress,
  25425. getBigInt: getBigInt,
  25426. getBytes: getBytes,
  25427. getBytesCopy: getBytesCopy,
  25428. getCreate2Address: getCreate2Address,
  25429. getCreateAddress: getCreateAddress,
  25430. getDefaultProvider: getDefaultProvider,
  25431. getIcapAddress: getIcapAddress,
  25432. getIndexedAccountPath: getIndexedAccountPath,
  25433. getNumber: getNumber,
  25434. getUint: getUint,
  25435. hashMessage: hashMessage,
  25436. hexlify: hexlify,
  25437. id: id,
  25438. isAddress: isAddress,
  25439. isAddressable: isAddressable,
  25440. isBytesLike: isBytesLike,
  25441. isCallException: isCallException,
  25442. isCrowdsaleJson: isCrowdsaleJson,
  25443. isError: isError,
  25444. isHexString: isHexString,
  25445. isKeystoreJson: isKeystoreJson,
  25446. isValidName: isValidName,
  25447. keccak256: keccak256,
  25448. lock: lock,
  25449. makeError: makeError,
  25450. mask: mask,
  25451. namehash: namehash,
  25452. parseEther: parseEther,
  25453. parseUnits: parseUnits$1,
  25454. pbkdf2: pbkdf2,
  25455. randomBytes: randomBytes,
  25456. recoverAddress: recoverAddress,
  25457. resolveAddress: resolveAddress,
  25458. resolveProperties: resolveProperties,
  25459. ripemd160: ripemd160,
  25460. scrypt: scrypt,
  25461. scryptSync: scryptSync,
  25462. sha256: sha256,
  25463. sha512: sha512,
  25464. showThrottleMessage: showThrottleMessage,
  25465. solidityPacked: solidityPacked,
  25466. solidityPackedKeccak256: solidityPackedKeccak256,
  25467. solidityPackedSha256: solidityPackedSha256,
  25468. stripZerosLeft: stripZerosLeft,
  25469. toBeArray: toBeArray,
  25470. toBeHex: toBeHex,
  25471. toBigInt: toBigInt,
  25472. toNumber: toNumber,
  25473. toQuantity: toQuantity,
  25474. toTwos: toTwos,
  25475. toUtf8Bytes: toUtf8Bytes,
  25476. toUtf8CodePoints: toUtf8CodePoints,
  25477. toUtf8String: toUtf8String,
  25478. uuidV4: uuidV4,
  25479. verifyMessage: verifyMessage,
  25480. verifyTypedData: verifyTypedData,
  25481. version: version,
  25482. wordlists: wordlists,
  25483. zeroPadBytes: zeroPadBytes,
  25484. zeroPadValue: zeroPadValue
  25485. });
  25486. export { AbiCoder, AbstractProvider, AbstractSigner, AlchemyProvider, AnkrProvider, BaseContract, BaseWallet, Block, BrowserProvider, ChainstackProvider, CloudflareProvider, ConstructorFragment, Contract, ContractEventPayload, ContractFactory, ContractTransactionReceipt, ContractTransactionResponse, ContractUnknownEventPayload, EnsPlugin, EnsResolver, ErrorDescription, ErrorFragment, EtherSymbol, EtherscanPlugin, EtherscanProvider, EventFragment, EventLog, EventPayload, FallbackFragment, FallbackProvider, FeeData, FeeDataNetworkPlugin, FetchCancelSignal, FetchRequest, FetchResponse, FetchUrlFeeDataNetworkPlugin, FixedNumber, Fragment, FunctionFragment, GasCostPlugin, HDNodeVoidWallet, HDNodeWallet, Indexed, InfuraProvider, InfuraWebSocketProvider, Interface, IpcSocketProvider, JsonRpcApiProvider, JsonRpcProvider, JsonRpcSigner, LangEn, Log, LogDescription, MaxInt256, MaxUint256, MessagePrefix, MinInt256, Mnemonic, MulticoinProviderPlugin, N$1 as N, NamedFragment, Network, NetworkPlugin, NonceManager, ParamType, PocketProvider, QuickNodeProvider, Result, Signature, SigningKey, SocketBlockSubscriber, SocketEventSubscriber, SocketPendingSubscriber, SocketProvider, SocketSubscriber, StructFragment, Transaction, TransactionDescription, TransactionReceipt, TransactionResponse, Typed, TypedDataEncoder, UndecodedEventLog, UnmanagedSubscriber, Utf8ErrorFuncs, VoidSigner, Wallet, WebSocketProvider, WeiPerEther, Wordlist, WordlistOwl, WordlistOwlA, ZeroAddress, ZeroHash, accessListify, assert, assertArgument, assertArgumentCount, assertNormalize, assertPrivate, checkResultErrors, computeAddress, computeHmac, concat, copyRequest, dataLength, dataSlice, decodeBase58, decodeBase64, decodeBytes32String, decodeRlp, decryptCrowdsaleJson, decryptKeystoreJson, decryptKeystoreJsonSync, defaultPath, defineProperties, dnsEncode, encodeBase58, encodeBase64, encodeBytes32String, encodeRlp, encryptKeystoreJson, encryptKeystoreJsonSync, ensNormalize, ethers, formatEther, formatUnits, fromTwos, getAccountPath, getAddress, getBigInt, getBytes, getBytesCopy, getCreate2Address, getCreateAddress, getDefaultProvider, getIcapAddress, getIndexedAccountPath, getNumber, getUint, hashMessage, hexlify, id, isAddress, isAddressable, isBytesLike, isCallException, isCrowdsaleJson, isError, isHexString, isKeystoreJson, isValidName, keccak256, lock, makeError, mask, namehash, parseEther, parseUnits$1 as parseUnits, pbkdf2, randomBytes, recoverAddress, resolveAddress, resolveProperties, ripemd160, scrypt, scryptSync, sha256, sha512, showThrottleMessage, solidityPacked, solidityPackedKeccak256, solidityPackedSha256, stripZerosLeft, toBeArray, toBeHex, toBigInt, toNumber, toQuantity, toTwos, toUtf8Bytes, toUtf8CodePoints, toUtf8String, uuidV4, verifyMessage, verifyTypedData, version, wordlists, zeroPadBytes, zeroPadValue };
  25487. //# sourceMappingURL=ethers.js.map