12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406 |
- (function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
- typeof define === 'function' && define.amd ? define(factory) :
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.ethers = factory());
- }(this, (function () { 'use strict';
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
- function getDefaultExportFromCjs (x) {
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
- }
- function createCommonjsModule(fn, basedir, module) {
- return module = {
- path: basedir,
- exports: {},
- require: function (path, base) {
- return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
- }
- }, fn(module, module.exports), module.exports;
- }
- function getDefaultExportFromNamespaceIfPresent (n) {
- return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
- }
- function getDefaultExportFromNamespaceIfNotNamed (n) {
- return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
- }
- function getAugmentedNamespace(n) {
- if (n.__esModule) return n;
- var a = Object.defineProperty({}, '__esModule', {value: true});
- Object.keys(n).forEach(function (k) {
- var d = Object.getOwnPropertyDescriptor(n, k);
- Object.defineProperty(a, k, d.get ? d : {
- enumerable: true,
- get: function () {
- return n[k];
- }
- });
- });
- return a;
- }
- function commonjsRequire () {
- throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
- }
- var bn = createCommonjsModule(function (module) {
- (function (module, exports) {
- 'use strict';
- // Utils
- function assert (val, msg) {
- if (!val) throw new Error(msg || 'Assertion failed');
- }
- // Could use `inherits` module, but don't want to move from single file
- // architecture yet.
- function inherits (ctor, superCtor) {
- ctor.super_ = superCtor;
- var TempCtor = function () {};
- TempCtor.prototype = superCtor.prototype;
- ctor.prototype = new TempCtor();
- ctor.prototype.constructor = ctor;
- }
- // BN
- function BN (number, base, endian) {
- if (BN.isBN(number)) {
- return number;
- }
- this.negative = 0;
- this.words = null;
- this.length = 0;
- // Reduction context
- this.red = null;
- if (number !== null) {
- if (base === 'le' || base === 'be') {
- endian = base;
- base = 10;
- }
- this._init(number || 0, base || 10, endian || 'be');
- }
- }
- if (typeof module === 'object') {
- module.exports = BN;
- } else {
- exports.BN = BN;
- }
- BN.BN = BN;
- BN.wordSize = 26;
- var Buffer;
- try {
- if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {
- Buffer = window.Buffer;
- } else {
- Buffer = /*RicMoo:ethers:require(buffer)*/(null).Buffer;
- }
- } catch (e) {
- }
- BN.isBN = function isBN (num) {
- if (num instanceof BN) {
- return true;
- }
- return num !== null && typeof num === 'object' &&
- num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
- };
- BN.max = function max (left, right) {
- if (left.cmp(right) > 0) return left;
- return right;
- };
- BN.min = function min (left, right) {
- if (left.cmp(right) < 0) return left;
- return right;
- };
- BN.prototype._init = function init (number, base, endian) {
- if (typeof number === 'number') {
- return this._initNumber(number, base, endian);
- }
- if (typeof number === 'object') {
- return this._initArray(number, base, endian);
- }
- if (base === 'hex') {
- base = 16;
- }
- assert(base === (base | 0) && base >= 2 && base <= 36);
- number = number.toString().replace(/\s+/g, '');
- var start = 0;
- if (number[0] === '-') {
- start++;
- this.negative = 1;
- }
- if (start < number.length) {
- if (base === 16) {
- this._parseHex(number, start, endian);
- } else {
- this._parseBase(number, base, start);
- if (endian === 'le') {
- this._initArray(this.toArray(), base, endian);
- }
- }
- }
- };
- BN.prototype._initNumber = function _initNumber (number, base, endian) {
- if (number < 0) {
- this.negative = 1;
- number = -number;
- }
- if (number < 0x4000000) {
- this.words = [ number & 0x3ffffff ];
- this.length = 1;
- } else if (number < 0x10000000000000) {
- this.words = [
- number & 0x3ffffff,
- (number / 0x4000000) & 0x3ffffff
- ];
- this.length = 2;
- } else {
- assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
- this.words = [
- number & 0x3ffffff,
- (number / 0x4000000) & 0x3ffffff,
- 1
- ];
- this.length = 3;
- }
- if (endian !== 'le') return;
- // Reverse the bytes
- this._initArray(this.toArray(), base, endian);
- };
- BN.prototype._initArray = function _initArray (number, base, endian) {
- // Perhaps a Uint8Array
- assert(typeof number.length === 'number');
- if (number.length <= 0) {
- this.words = [ 0 ];
- this.length = 1;
- return this;
- }
- this.length = Math.ceil(number.length / 3);
- this.words = new Array(this.length);
- for (var i = 0; i < this.length; i++) {
- this.words[i] = 0;
- }
- var j, w;
- var off = 0;
- if (endian === 'be') {
- for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
- w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
- this.words[j] |= (w << off) & 0x3ffffff;
- this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
- off += 24;
- if (off >= 26) {
- off -= 26;
- j++;
- }
- }
- } else if (endian === 'le') {
- for (i = 0, j = 0; i < number.length; i += 3) {
- w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
- this.words[j] |= (w << off) & 0x3ffffff;
- this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
- off += 24;
- if (off >= 26) {
- off -= 26;
- j++;
- }
- }
- }
- return this.strip();
- };
- function parseHex4Bits (string, index) {
- var c = string.charCodeAt(index);
- // 'A' - 'F'
- if (c >= 65 && c <= 70) {
- return c - 55;
- // 'a' - 'f'
- } else if (c >= 97 && c <= 102) {
- return c - 87;
- // '0' - '9'
- } else {
- return (c - 48) & 0xf;
- }
- }
- function parseHexByte (string, lowerBound, index) {
- var r = parseHex4Bits(string, index);
- if (index - 1 >= lowerBound) {
- r |= parseHex4Bits(string, index - 1) << 4;
- }
- return r;
- }
- BN.prototype._parseHex = function _parseHex (number, start, endian) {
- // Create possibly bigger array to ensure that it fits the number
- this.length = Math.ceil((number.length - start) / 6);
- this.words = new Array(this.length);
- for (var i = 0; i < this.length; i++) {
- this.words[i] = 0;
- }
- // 24-bits chunks
- var off = 0;
- var j = 0;
- var w;
- if (endian === 'be') {
- for (i = number.length - 1; i >= start; i -= 2) {
- w = parseHexByte(number, start, i) << off;
- this.words[j] |= w & 0x3ffffff;
- if (off >= 18) {
- off -= 18;
- j += 1;
- this.words[j] |= w >>> 26;
- } else {
- off += 8;
- }
- }
- } else {
- var parseLength = number.length - start;
- for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {
- w = parseHexByte(number, start, i) << off;
- this.words[j] |= w & 0x3ffffff;
- if (off >= 18) {
- off -= 18;
- j += 1;
- this.words[j] |= w >>> 26;
- } else {
- off += 8;
- }
- }
- }
- this.strip();
- };
- function parseBase (str, start, end, mul) {
- var r = 0;
- var len = Math.min(str.length, end);
- for (var i = start; i < len; i++) {
- var c = str.charCodeAt(i) - 48;
- r *= mul;
- // 'a'
- if (c >= 49) {
- r += c - 49 + 0xa;
- // 'A'
- } else if (c >= 17) {
- r += c - 17 + 0xa;
- // '0' - '9'
- } else {
- r += c;
- }
- }
- return r;
- }
- BN.prototype._parseBase = function _parseBase (number, base, start) {
- // Initialize as zero
- this.words = [ 0 ];
- this.length = 1;
- // Find length of limb in base
- for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
- limbLen++;
- }
- limbLen--;
- limbPow = (limbPow / base) | 0;
- var total = number.length - start;
- var mod = total % limbLen;
- var end = Math.min(total, total - mod) + start;
- var word = 0;
- for (var i = start; i < end; i += limbLen) {
- word = parseBase(number, i, i + limbLen, base);
- this.imuln(limbPow);
- if (this.words[0] + word < 0x4000000) {
- this.words[0] += word;
- } else {
- this._iaddn(word);
- }
- }
- if (mod !== 0) {
- var pow = 1;
- word = parseBase(number, i, number.length, base);
- for (i = 0; i < mod; i++) {
- pow *= base;
- }
- this.imuln(pow);
- if (this.words[0] + word < 0x4000000) {
- this.words[0] += word;
- } else {
- this._iaddn(word);
- }
- }
- this.strip();
- };
- BN.prototype.copy = function copy (dest) {
- dest.words = new Array(this.length);
- for (var i = 0; i < this.length; i++) {
- dest.words[i] = this.words[i];
- }
- dest.length = this.length;
- dest.negative = this.negative;
- dest.red = this.red;
- };
- BN.prototype.clone = function clone () {
- var r = new BN(null);
- this.copy(r);
- return r;
- };
- BN.prototype._expand = function _expand (size) {
- while (this.length < size) {
- this.words[this.length++] = 0;
- }
- return this;
- };
- // Remove leading `0` from `this`
- BN.prototype.strip = function strip () {
- while (this.length > 1 && this.words[this.length - 1] === 0) {
- this.length--;
- }
- return this._normSign();
- };
- BN.prototype._normSign = function _normSign () {
- // -0 = 0
- if (this.length === 1 && this.words[0] === 0) {
- this.negative = 0;
- }
- return this;
- };
- BN.prototype.inspect = function inspect () {
- return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
- };
- /*
- var zeros = [];
- var groupSizes = [];
- var groupBases = [];
- var s = '';
- var i = -1;
- while (++i < BN.wordSize) {
- zeros[i] = s;
- s += '0';
- }
- groupSizes[0] = 0;
- groupSizes[1] = 0;
- groupBases[0] = 0;
- groupBases[1] = 0;
- var base = 2 - 1;
- while (++base < 36 + 1) {
- var groupSize = 0;
- var groupBase = 1;
- while (groupBase < (1 << BN.wordSize) / base) {
- groupBase *= base;
- groupSize += 1;
- }
- groupSizes[base] = groupSize;
- groupBases[base] = groupBase;
- }
- */
- var zeros = [
- '',
- '0',
- '00',
- '000',
- '0000',
- '00000',
- '000000',
- '0000000',
- '00000000',
- '000000000',
- '0000000000',
- '00000000000',
- '000000000000',
- '0000000000000',
- '00000000000000',
- '000000000000000',
- '0000000000000000',
- '00000000000000000',
- '000000000000000000',
- '0000000000000000000',
- '00000000000000000000',
- '000000000000000000000',
- '0000000000000000000000',
- '00000000000000000000000',
- '000000000000000000000000',
- '0000000000000000000000000'
- ];
- var groupSizes = [
- 0, 0,
- 25, 16, 12, 11, 10, 9, 8,
- 8, 7, 7, 7, 7, 6, 6,
- 6, 6, 6, 6, 6, 5, 5,
- 5, 5, 5, 5, 5, 5, 5,
- 5, 5, 5, 5, 5, 5, 5
- ];
- var groupBases = [
- 0, 0,
- 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
- 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
- 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
- 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
- 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
- ];
- BN.prototype.toString = function toString (base, padding) {
- base = base || 10;
- padding = padding | 0 || 1;
- var out;
- if (base === 16 || base === 'hex') {
- out = '';
- var off = 0;
- var carry = 0;
- for (var i = 0; i < this.length; i++) {
- var w = this.words[i];
- var word = (((w << off) | carry) & 0xffffff).toString(16);
- carry = (w >>> (24 - off)) & 0xffffff;
- if (carry !== 0 || i !== this.length - 1) {
- out = zeros[6 - word.length] + word + out;
- } else {
- out = word + out;
- }
- off += 2;
- if (off >= 26) {
- off -= 26;
- i--;
- }
- }
- if (carry !== 0) {
- out = carry.toString(16) + out;
- }
- while (out.length % padding !== 0) {
- out = '0' + out;
- }
- if (this.negative !== 0) {
- out = '-' + out;
- }
- return out;
- }
- if (base === (base | 0) && base >= 2 && base <= 36) {
- // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
- var groupSize = groupSizes[base];
- // var groupBase = Math.pow(base, groupSize);
- var groupBase = groupBases[base];
- out = '';
- var c = this.clone();
- c.negative = 0;
- while (!c.isZero()) {
- var r = c.modn(groupBase).toString(base);
- c = c.idivn(groupBase);
- if (!c.isZero()) {
- out = zeros[groupSize - r.length] + r + out;
- } else {
- out = r + out;
- }
- }
- if (this.isZero()) {
- out = '0' + out;
- }
- while (out.length % padding !== 0) {
- out = '0' + out;
- }
- if (this.negative !== 0) {
- out = '-' + out;
- }
- return out;
- }
- assert(false, 'Base should be between 2 and 36');
- };
- BN.prototype.toNumber = function toNumber () {
- var ret = this.words[0];
- if (this.length === 2) {
- ret += this.words[1] * 0x4000000;
- } else if (this.length === 3 && this.words[2] === 0x01) {
- // NOTE: at this stage it is known that the top bit is set
- ret += 0x10000000000000 + (this.words[1] * 0x4000000);
- } else if (this.length > 2) {
- assert(false, 'Number can only safely store up to 53 bits');
- }
- return (this.negative !== 0) ? -ret : ret;
- };
- BN.prototype.toJSON = function toJSON () {
- return this.toString(16);
- };
- BN.prototype.toBuffer = function toBuffer (endian, length) {
- assert(typeof Buffer !== 'undefined');
- return this.toArrayLike(Buffer, endian, length);
- };
- BN.prototype.toArray = function toArray (endian, length) {
- return this.toArrayLike(Array, endian, length);
- };
- BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
- var byteLength = this.byteLength();
- var reqLength = length || Math.max(1, byteLength);
- assert(byteLength <= reqLength, 'byte array longer than desired length');
- assert(reqLength > 0, 'Requested array length <= 0');
- this.strip();
- var littleEndian = endian === 'le';
- var res = new ArrayType(reqLength);
- var b, i;
- var q = this.clone();
- if (!littleEndian) {
- // Assume big-endian
- for (i = 0; i < reqLength - byteLength; i++) {
- res[i] = 0;
- }
- for (i = 0; !q.isZero(); i++) {
- b = q.andln(0xff);
- q.iushrn(8);
- res[reqLength - i - 1] = b;
- }
- } else {
- for (i = 0; !q.isZero(); i++) {
- b = q.andln(0xff);
- q.iushrn(8);
- res[i] = b;
- }
- for (; i < reqLength; i++) {
- res[i] = 0;
- }
- }
- return res;
- };
- if (Math.clz32) {
- BN.prototype._countBits = function _countBits (w) {
- return 32 - Math.clz32(w);
- };
- } else {
- BN.prototype._countBits = function _countBits (w) {
- var t = w;
- var r = 0;
- if (t >= 0x1000) {
- r += 13;
- t >>>= 13;
- }
- if (t >= 0x40) {
- r += 7;
- t >>>= 7;
- }
- if (t >= 0x8) {
- r += 4;
- t >>>= 4;
- }
- if (t >= 0x02) {
- r += 2;
- t >>>= 2;
- }
- return r + t;
- };
- }
- BN.prototype._zeroBits = function _zeroBits (w) {
- // Short-cut
- if (w === 0) return 26;
- var t = w;
- var r = 0;
- if ((t & 0x1fff) === 0) {
- r += 13;
- t >>>= 13;
- }
- if ((t & 0x7f) === 0) {
- r += 7;
- t >>>= 7;
- }
- if ((t & 0xf) === 0) {
- r += 4;
- t >>>= 4;
- }
- if ((t & 0x3) === 0) {
- r += 2;
- t >>>= 2;
- }
- if ((t & 0x1) === 0) {
- r++;
- }
- return r;
- };
- // Return number of used bits in a BN
- BN.prototype.bitLength = function bitLength () {
- var w = this.words[this.length - 1];
- var hi = this._countBits(w);
- return (this.length - 1) * 26 + hi;
- };
- function toBitArray (num) {
- var w = new Array(num.bitLength());
- for (var bit = 0; bit < w.length; bit++) {
- var off = (bit / 26) | 0;
- var wbit = bit % 26;
- w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
- }
- return w;
- }
- // Number of trailing zero bits
- BN.prototype.zeroBits = function zeroBits () {
- if (this.isZero()) return 0;
- var r = 0;
- for (var i = 0; i < this.length; i++) {
- var b = this._zeroBits(this.words[i]);
- r += b;
- if (b !== 26) break;
- }
- return r;
- };
- BN.prototype.byteLength = function byteLength () {
- return Math.ceil(this.bitLength() / 8);
- };
- BN.prototype.toTwos = function toTwos (width) {
- if (this.negative !== 0) {
- return this.abs().inotn(width).iaddn(1);
- }
- return this.clone();
- };
- BN.prototype.fromTwos = function fromTwos (width) {
- if (this.testn(width - 1)) {
- return this.notn(width).iaddn(1).ineg();
- }
- return this.clone();
- };
- BN.prototype.isNeg = function isNeg () {
- return this.negative !== 0;
- };
- // Return negative clone of `this`
- BN.prototype.neg = function neg () {
- return this.clone().ineg();
- };
- BN.prototype.ineg = function ineg () {
- if (!this.isZero()) {
- this.negative ^= 1;
- }
- return this;
- };
- // Or `num` with `this` in-place
- BN.prototype.iuor = function iuor (num) {
- while (this.length < num.length) {
- this.words[this.length++] = 0;
- }
- for (var i = 0; i < num.length; i++) {
- this.words[i] = this.words[i] | num.words[i];
- }
- return this.strip();
- };
- BN.prototype.ior = function ior (num) {
- assert((this.negative | num.negative) === 0);
- return this.iuor(num);
- };
- // Or `num` with `this`
- BN.prototype.or = function or (num) {
- if (this.length > num.length) return this.clone().ior(num);
- return num.clone().ior(this);
- };
- BN.prototype.uor = function uor (num) {
- if (this.length > num.length) return this.clone().iuor(num);
- return num.clone().iuor(this);
- };
- // And `num` with `this` in-place
- BN.prototype.iuand = function iuand (num) {
- // b = min-length(num, this)
- var b;
- if (this.length > num.length) {
- b = num;
- } else {
- b = this;
- }
- for (var i = 0; i < b.length; i++) {
- this.words[i] = this.words[i] & num.words[i];
- }
- this.length = b.length;
- return this.strip();
- };
- BN.prototype.iand = function iand (num) {
- assert((this.negative | num.negative) === 0);
- return this.iuand(num);
- };
- // And `num` with `this`
- BN.prototype.and = function and (num) {
- if (this.length > num.length) return this.clone().iand(num);
- return num.clone().iand(this);
- };
- BN.prototype.uand = function uand (num) {
- if (this.length > num.length) return this.clone().iuand(num);
- return num.clone().iuand(this);
- };
- // Xor `num` with `this` in-place
- BN.prototype.iuxor = function iuxor (num) {
- // a.length > b.length
- var a;
- var b;
- if (this.length > num.length) {
- a = this;
- b = num;
- } else {
- a = num;
- b = this;
- }
- for (var i = 0; i < b.length; i++) {
- this.words[i] = a.words[i] ^ b.words[i];
- }
- if (this !== a) {
- for (; i < a.length; i++) {
- this.words[i] = a.words[i];
- }
- }
- this.length = a.length;
- return this.strip();
- };
- BN.prototype.ixor = function ixor (num) {
- assert((this.negative | num.negative) === 0);
- return this.iuxor(num);
- };
- // Xor `num` with `this`
- BN.prototype.xor = function xor (num) {
- if (this.length > num.length) return this.clone().ixor(num);
- return num.clone().ixor(this);
- };
- BN.prototype.uxor = function uxor (num) {
- if (this.length > num.length) return this.clone().iuxor(num);
- return num.clone().iuxor(this);
- };
- // Not ``this`` with ``width`` bitwidth
- BN.prototype.inotn = function inotn (width) {
- assert(typeof width === 'number' && width >= 0);
- var bytesNeeded = Math.ceil(width / 26) | 0;
- var bitsLeft = width % 26;
- // Extend the buffer with leading zeroes
- this._expand(bytesNeeded);
- if (bitsLeft > 0) {
- bytesNeeded--;
- }
- // Handle complete words
- for (var i = 0; i < bytesNeeded; i++) {
- this.words[i] = ~this.words[i] & 0x3ffffff;
- }
- // Handle the residue
- if (bitsLeft > 0) {
- this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
- }
- // And remove leading zeroes
- return this.strip();
- };
- BN.prototype.notn = function notn (width) {
- return this.clone().inotn(width);
- };
- // Set `bit` of `this`
- BN.prototype.setn = function setn (bit, val) {
- assert(typeof bit === 'number' && bit >= 0);
- var off = (bit / 26) | 0;
- var wbit = bit % 26;
- this._expand(off + 1);
- if (val) {
- this.words[off] = this.words[off] | (1 << wbit);
- } else {
- this.words[off] = this.words[off] & ~(1 << wbit);
- }
- return this.strip();
- };
- // Add `num` to `this` in-place
- BN.prototype.iadd = function iadd (num) {
- var r;
- // negative + positive
- if (this.negative !== 0 && num.negative === 0) {
- this.negative = 0;
- r = this.isub(num);
- this.negative ^= 1;
- return this._normSign();
- // positive + negative
- } else if (this.negative === 0 && num.negative !== 0) {
- num.negative = 0;
- r = this.isub(num);
- num.negative = 1;
- return r._normSign();
- }
- // a.length > b.length
- var a, b;
- if (this.length > num.length) {
- a = this;
- b = num;
- } else {
- a = num;
- b = this;
- }
- var carry = 0;
- for (var i = 0; i < b.length; i++) {
- r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
- this.words[i] = r & 0x3ffffff;
- carry = r >>> 26;
- }
- for (; carry !== 0 && i < a.length; i++) {
- r = (a.words[i] | 0) + carry;
- this.words[i] = r & 0x3ffffff;
- carry = r >>> 26;
- }
- this.length = a.length;
- if (carry !== 0) {
- this.words[this.length] = carry;
- this.length++;
- // Copy the rest of the words
- } else if (a !== this) {
- for (; i < a.length; i++) {
- this.words[i] = a.words[i];
- }
- }
- return this;
- };
- // Add `num` to `this`
- BN.prototype.add = function add (num) {
- var res;
- if (num.negative !== 0 && this.negative === 0) {
- num.negative = 0;
- res = this.sub(num);
- num.negative ^= 1;
- return res;
- } else if (num.negative === 0 && this.negative !== 0) {
- this.negative = 0;
- res = num.sub(this);
- this.negative = 1;
- return res;
- }
- if (this.length > num.length) return this.clone().iadd(num);
- return num.clone().iadd(this);
- };
- // Subtract `num` from `this` in-place
- BN.prototype.isub = function isub (num) {
- // this - (-num) = this + num
- if (num.negative !== 0) {
- num.negative = 0;
- var r = this.iadd(num);
- num.negative = 1;
- return r._normSign();
- // -this - num = -(this + num)
- } else if (this.negative !== 0) {
- this.negative = 0;
- this.iadd(num);
- this.negative = 1;
- return this._normSign();
- }
- // At this point both numbers are positive
- var cmp = this.cmp(num);
- // Optimization - zeroify
- if (cmp === 0) {
- this.negative = 0;
- this.length = 1;
- this.words[0] = 0;
- return this;
- }
- // a > b
- var a, b;
- if (cmp > 0) {
- a = this;
- b = num;
- } else {
- a = num;
- b = this;
- }
- var carry = 0;
- for (var i = 0; i < b.length; i++) {
- r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
- carry = r >> 26;
- this.words[i] = r & 0x3ffffff;
- }
- for (; carry !== 0 && i < a.length; i++) {
- r = (a.words[i] | 0) + carry;
- carry = r >> 26;
- this.words[i] = r & 0x3ffffff;
- }
- // Copy rest of the words
- if (carry === 0 && i < a.length && a !== this) {
- for (; i < a.length; i++) {
- this.words[i] = a.words[i];
- }
- }
- this.length = Math.max(this.length, i);
- if (a !== this) {
- this.negative = 1;
- }
- return this.strip();
- };
- // Subtract `num` from `this`
- BN.prototype.sub = function sub (num) {
- return this.clone().isub(num);
- };
- function smallMulTo (self, num, out) {
- out.negative = num.negative ^ self.negative;
- var len = (self.length + num.length) | 0;
- out.length = len;
- len = (len - 1) | 0;
- // Peel one iteration (compiler can't do it, because of code complexity)
- var a = self.words[0] | 0;
- var b = num.words[0] | 0;
- var r = a * b;
- var lo = r & 0x3ffffff;
- var carry = (r / 0x4000000) | 0;
- out.words[0] = lo;
- for (var k = 1; k < len; k++) {
- // Sum all words with the same `i + j = k` and accumulate `ncarry`,
- // note that ncarry could be >= 0x3ffffff
- var ncarry = carry >>> 26;
- var rword = carry & 0x3ffffff;
- var maxJ = Math.min(k, num.length - 1);
- for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
- var i = (k - j) | 0;
- a = self.words[i] | 0;
- b = num.words[j] | 0;
- r = a * b + rword;
- ncarry += (r / 0x4000000) | 0;
- rword = r & 0x3ffffff;
- }
- out.words[k] = rword | 0;
- carry = ncarry | 0;
- }
- if (carry !== 0) {
- out.words[k] = carry | 0;
- } else {
- out.length--;
- }
- return out.strip();
- }
- // TODO(indutny): it may be reasonable to omit it for users who don't need
- // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
- // multiplication (like elliptic secp256k1).
- var comb10MulTo = function comb10MulTo (self, num, out) {
- var a = self.words;
- var b = num.words;
- var o = out.words;
- var c = 0;
- var lo;
- var mid;
- var hi;
- var a0 = a[0] | 0;
- var al0 = a0 & 0x1fff;
- var ah0 = a0 >>> 13;
- var a1 = a[1] | 0;
- var al1 = a1 & 0x1fff;
- var ah1 = a1 >>> 13;
- var a2 = a[2] | 0;
- var al2 = a2 & 0x1fff;
- var ah2 = a2 >>> 13;
- var a3 = a[3] | 0;
- var al3 = a3 & 0x1fff;
- var ah3 = a3 >>> 13;
- var a4 = a[4] | 0;
- var al4 = a4 & 0x1fff;
- var ah4 = a4 >>> 13;
- var a5 = a[5] | 0;
- var al5 = a5 & 0x1fff;
- var ah5 = a5 >>> 13;
- var a6 = a[6] | 0;
- var al6 = a6 & 0x1fff;
- var ah6 = a6 >>> 13;
- var a7 = a[7] | 0;
- var al7 = a7 & 0x1fff;
- var ah7 = a7 >>> 13;
- var a8 = a[8] | 0;
- var al8 = a8 & 0x1fff;
- var ah8 = a8 >>> 13;
- var a9 = a[9] | 0;
- var al9 = a9 & 0x1fff;
- var ah9 = a9 >>> 13;
- var b0 = b[0] | 0;
- var bl0 = b0 & 0x1fff;
- var bh0 = b0 >>> 13;
- var b1 = b[1] | 0;
- var bl1 = b1 & 0x1fff;
- var bh1 = b1 >>> 13;
- var b2 = b[2] | 0;
- var bl2 = b2 & 0x1fff;
- var bh2 = b2 >>> 13;
- var b3 = b[3] | 0;
- var bl3 = b3 & 0x1fff;
- var bh3 = b3 >>> 13;
- var b4 = b[4] | 0;
- var bl4 = b4 & 0x1fff;
- var bh4 = b4 >>> 13;
- var b5 = b[5] | 0;
- var bl5 = b5 & 0x1fff;
- var bh5 = b5 >>> 13;
- var b6 = b[6] | 0;
- var bl6 = b6 & 0x1fff;
- var bh6 = b6 >>> 13;
- var b7 = b[7] | 0;
- var bl7 = b7 & 0x1fff;
- var bh7 = b7 >>> 13;
- var b8 = b[8] | 0;
- var bl8 = b8 & 0x1fff;
- var bh8 = b8 >>> 13;
- var b9 = b[9] | 0;
- var bl9 = b9 & 0x1fff;
- var bh9 = b9 >>> 13;
- out.negative = self.negative ^ num.negative;
- out.length = 19;
- /* k = 0 */
- lo = Math.imul(al0, bl0);
- mid = Math.imul(al0, bh0);
- mid = (mid + Math.imul(ah0, bl0)) | 0;
- hi = Math.imul(ah0, bh0);
- var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
- w0 &= 0x3ffffff;
- /* k = 1 */
- lo = Math.imul(al1, bl0);
- mid = Math.imul(al1, bh0);
- mid = (mid + Math.imul(ah1, bl0)) | 0;
- hi = Math.imul(ah1, bh0);
- lo = (lo + Math.imul(al0, bl1)) | 0;
- mid = (mid + Math.imul(al0, bh1)) | 0;
- mid = (mid + Math.imul(ah0, bl1)) | 0;
- hi = (hi + Math.imul(ah0, bh1)) | 0;
- var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
- w1 &= 0x3ffffff;
- /* k = 2 */
- lo = Math.imul(al2, bl0);
- mid = Math.imul(al2, bh0);
- mid = (mid + Math.imul(ah2, bl0)) | 0;
- hi = Math.imul(ah2, bh0);
- lo = (lo + Math.imul(al1, bl1)) | 0;
- mid = (mid + Math.imul(al1, bh1)) | 0;
- mid = (mid + Math.imul(ah1, bl1)) | 0;
- hi = (hi + Math.imul(ah1, bh1)) | 0;
- lo = (lo + Math.imul(al0, bl2)) | 0;
- mid = (mid + Math.imul(al0, bh2)) | 0;
- mid = (mid + Math.imul(ah0, bl2)) | 0;
- hi = (hi + Math.imul(ah0, bh2)) | 0;
- var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
- w2 &= 0x3ffffff;
- /* k = 3 */
- lo = Math.imul(al3, bl0);
- mid = Math.imul(al3, bh0);
- mid = (mid + Math.imul(ah3, bl0)) | 0;
- hi = Math.imul(ah3, bh0);
- lo = (lo + Math.imul(al2, bl1)) | 0;
- mid = (mid + Math.imul(al2, bh1)) | 0;
- mid = (mid + Math.imul(ah2, bl1)) | 0;
- hi = (hi + Math.imul(ah2, bh1)) | 0;
- lo = (lo + Math.imul(al1, bl2)) | 0;
- mid = (mid + Math.imul(al1, bh2)) | 0;
- mid = (mid + Math.imul(ah1, bl2)) | 0;
- hi = (hi + Math.imul(ah1, bh2)) | 0;
- lo = (lo + Math.imul(al0, bl3)) | 0;
- mid = (mid + Math.imul(al0, bh3)) | 0;
- mid = (mid + Math.imul(ah0, bl3)) | 0;
- hi = (hi + Math.imul(ah0, bh3)) | 0;
- var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
- w3 &= 0x3ffffff;
- /* k = 4 */
- lo = Math.imul(al4, bl0);
- mid = Math.imul(al4, bh0);
- mid = (mid + Math.imul(ah4, bl0)) | 0;
- hi = Math.imul(ah4, bh0);
- lo = (lo + Math.imul(al3, bl1)) | 0;
- mid = (mid + Math.imul(al3, bh1)) | 0;
- mid = (mid + Math.imul(ah3, bl1)) | 0;
- hi = (hi + Math.imul(ah3, bh1)) | 0;
- lo = (lo + Math.imul(al2, bl2)) | 0;
- mid = (mid + Math.imul(al2, bh2)) | 0;
- mid = (mid + Math.imul(ah2, bl2)) | 0;
- hi = (hi + Math.imul(ah2, bh2)) | 0;
- lo = (lo + Math.imul(al1, bl3)) | 0;
- mid = (mid + Math.imul(al1, bh3)) | 0;
- mid = (mid + Math.imul(ah1, bl3)) | 0;
- hi = (hi + Math.imul(ah1, bh3)) | 0;
- lo = (lo + Math.imul(al0, bl4)) | 0;
- mid = (mid + Math.imul(al0, bh4)) | 0;
- mid = (mid + Math.imul(ah0, bl4)) | 0;
- hi = (hi + Math.imul(ah0, bh4)) | 0;
- var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
- w4 &= 0x3ffffff;
- /* k = 5 */
- lo = Math.imul(al5, bl0);
- mid = Math.imul(al5, bh0);
- mid = (mid + Math.imul(ah5, bl0)) | 0;
- hi = Math.imul(ah5, bh0);
- lo = (lo + Math.imul(al4, bl1)) | 0;
- mid = (mid + Math.imul(al4, bh1)) | 0;
- mid = (mid + Math.imul(ah4, bl1)) | 0;
- hi = (hi + Math.imul(ah4, bh1)) | 0;
- lo = (lo + Math.imul(al3, bl2)) | 0;
- mid = (mid + Math.imul(al3, bh2)) | 0;
- mid = (mid + Math.imul(ah3, bl2)) | 0;
- hi = (hi + Math.imul(ah3, bh2)) | 0;
- lo = (lo + Math.imul(al2, bl3)) | 0;
- mid = (mid + Math.imul(al2, bh3)) | 0;
- mid = (mid + Math.imul(ah2, bl3)) | 0;
- hi = (hi + Math.imul(ah2, bh3)) | 0;
- lo = (lo + Math.imul(al1, bl4)) | 0;
- mid = (mid + Math.imul(al1, bh4)) | 0;
- mid = (mid + Math.imul(ah1, bl4)) | 0;
- hi = (hi + Math.imul(ah1, bh4)) | 0;
- lo = (lo + Math.imul(al0, bl5)) | 0;
- mid = (mid + Math.imul(al0, bh5)) | 0;
- mid = (mid + Math.imul(ah0, bl5)) | 0;
- hi = (hi + Math.imul(ah0, bh5)) | 0;
- var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
- w5 &= 0x3ffffff;
- /* k = 6 */
- lo = Math.imul(al6, bl0);
- mid = Math.imul(al6, bh0);
- mid = (mid + Math.imul(ah6, bl0)) | 0;
- hi = Math.imul(ah6, bh0);
- lo = (lo + Math.imul(al5, bl1)) | 0;
- mid = (mid + Math.imul(al5, bh1)) | 0;
- mid = (mid + Math.imul(ah5, bl1)) | 0;
- hi = (hi + Math.imul(ah5, bh1)) | 0;
- lo = (lo + Math.imul(al4, bl2)) | 0;
- mid = (mid + Math.imul(al4, bh2)) | 0;
- mid = (mid + Math.imul(ah4, bl2)) | 0;
- hi = (hi + Math.imul(ah4, bh2)) | 0;
- lo = (lo + Math.imul(al3, bl3)) | 0;
- mid = (mid + Math.imul(al3, bh3)) | 0;
- mid = (mid + Math.imul(ah3, bl3)) | 0;
- hi = (hi + Math.imul(ah3, bh3)) | 0;
- lo = (lo + Math.imul(al2, bl4)) | 0;
- mid = (mid + Math.imul(al2, bh4)) | 0;
- mid = (mid + Math.imul(ah2, bl4)) | 0;
- hi = (hi + Math.imul(ah2, bh4)) | 0;
- lo = (lo + Math.imul(al1, bl5)) | 0;
- mid = (mid + Math.imul(al1, bh5)) | 0;
- mid = (mid + Math.imul(ah1, bl5)) | 0;
- hi = (hi + Math.imul(ah1, bh5)) | 0;
- lo = (lo + Math.imul(al0, bl6)) | 0;
- mid = (mid + Math.imul(al0, bh6)) | 0;
- mid = (mid + Math.imul(ah0, bl6)) | 0;
- hi = (hi + Math.imul(ah0, bh6)) | 0;
- var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
- w6 &= 0x3ffffff;
- /* k = 7 */
- lo = Math.imul(al7, bl0);
- mid = Math.imul(al7, bh0);
- mid = (mid + Math.imul(ah7, bl0)) | 0;
- hi = Math.imul(ah7, bh0);
- lo = (lo + Math.imul(al6, bl1)) | 0;
- mid = (mid + Math.imul(al6, bh1)) | 0;
- mid = (mid + Math.imul(ah6, bl1)) | 0;
- hi = (hi + Math.imul(ah6, bh1)) | 0;
- lo = (lo + Math.imul(al5, bl2)) | 0;
- mid = (mid + Math.imul(al5, bh2)) | 0;
- mid = (mid + Math.imul(ah5, bl2)) | 0;
- hi = (hi + Math.imul(ah5, bh2)) | 0;
- lo = (lo + Math.imul(al4, bl3)) | 0;
- mid = (mid + Math.imul(al4, bh3)) | 0;
- mid = (mid + Math.imul(ah4, bl3)) | 0;
- hi = (hi + Math.imul(ah4, bh3)) | 0;
- lo = (lo + Math.imul(al3, bl4)) | 0;
- mid = (mid + Math.imul(al3, bh4)) | 0;
- mid = (mid + Math.imul(ah3, bl4)) | 0;
- hi = (hi + Math.imul(ah3, bh4)) | 0;
- lo = (lo + Math.imul(al2, bl5)) | 0;
- mid = (mid + Math.imul(al2, bh5)) | 0;
- mid = (mid + Math.imul(ah2, bl5)) | 0;
- hi = (hi + Math.imul(ah2, bh5)) | 0;
- lo = (lo + Math.imul(al1, bl6)) | 0;
- mid = (mid + Math.imul(al1, bh6)) | 0;
- mid = (mid + Math.imul(ah1, bl6)) | 0;
- hi = (hi + Math.imul(ah1, bh6)) | 0;
- lo = (lo + Math.imul(al0, bl7)) | 0;
- mid = (mid + Math.imul(al0, bh7)) | 0;
- mid = (mid + Math.imul(ah0, bl7)) | 0;
- hi = (hi + Math.imul(ah0, bh7)) | 0;
- var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
- w7 &= 0x3ffffff;
- /* k = 8 */
- lo = Math.imul(al8, bl0);
- mid = Math.imul(al8, bh0);
- mid = (mid + Math.imul(ah8, bl0)) | 0;
- hi = Math.imul(ah8, bh0);
- lo = (lo + Math.imul(al7, bl1)) | 0;
- mid = (mid + Math.imul(al7, bh1)) | 0;
- mid = (mid + Math.imul(ah7, bl1)) | 0;
- hi = (hi + Math.imul(ah7, bh1)) | 0;
- lo = (lo + Math.imul(al6, bl2)) | 0;
- mid = (mid + Math.imul(al6, bh2)) | 0;
- mid = (mid + Math.imul(ah6, bl2)) | 0;
- hi = (hi + Math.imul(ah6, bh2)) | 0;
- lo = (lo + Math.imul(al5, bl3)) | 0;
- mid = (mid + Math.imul(al5, bh3)) | 0;
- mid = (mid + Math.imul(ah5, bl3)) | 0;
- hi = (hi + Math.imul(ah5, bh3)) | 0;
- lo = (lo + Math.imul(al4, bl4)) | 0;
- mid = (mid + Math.imul(al4, bh4)) | 0;
- mid = (mid + Math.imul(ah4, bl4)) | 0;
- hi = (hi + Math.imul(ah4, bh4)) | 0;
- lo = (lo + Math.imul(al3, bl5)) | 0;
- mid = (mid + Math.imul(al3, bh5)) | 0;
- mid = (mid + Math.imul(ah3, bl5)) | 0;
- hi = (hi + Math.imul(ah3, bh5)) | 0;
- lo = (lo + Math.imul(al2, bl6)) | 0;
- mid = (mid + Math.imul(al2, bh6)) | 0;
- mid = (mid + Math.imul(ah2, bl6)) | 0;
- hi = (hi + Math.imul(ah2, bh6)) | 0;
- lo = (lo + Math.imul(al1, bl7)) | 0;
- mid = (mid + Math.imul(al1, bh7)) | 0;
- mid = (mid + Math.imul(ah1, bl7)) | 0;
- hi = (hi + Math.imul(ah1, bh7)) | 0;
- lo = (lo + Math.imul(al0, bl8)) | 0;
- mid = (mid + Math.imul(al0, bh8)) | 0;
- mid = (mid + Math.imul(ah0, bl8)) | 0;
- hi = (hi + Math.imul(ah0, bh8)) | 0;
- var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
- w8 &= 0x3ffffff;
- /* k = 9 */
- lo = Math.imul(al9, bl0);
- mid = Math.imul(al9, bh0);
- mid = (mid + Math.imul(ah9, bl0)) | 0;
- hi = Math.imul(ah9, bh0);
- lo = (lo + Math.imul(al8, bl1)) | 0;
- mid = (mid + Math.imul(al8, bh1)) | 0;
- mid = (mid + Math.imul(ah8, bl1)) | 0;
- hi = (hi + Math.imul(ah8, bh1)) | 0;
- lo = (lo + Math.imul(al7, bl2)) | 0;
- mid = (mid + Math.imul(al7, bh2)) | 0;
- mid = (mid + Math.imul(ah7, bl2)) | 0;
- hi = (hi + Math.imul(ah7, bh2)) | 0;
- lo = (lo + Math.imul(al6, bl3)) | 0;
- mid = (mid + Math.imul(al6, bh3)) | 0;
- mid = (mid + Math.imul(ah6, bl3)) | 0;
- hi = (hi + Math.imul(ah6, bh3)) | 0;
- lo = (lo + Math.imul(al5, bl4)) | 0;
- mid = (mid + Math.imul(al5, bh4)) | 0;
- mid = (mid + Math.imul(ah5, bl4)) | 0;
- hi = (hi + Math.imul(ah5, bh4)) | 0;
- lo = (lo + Math.imul(al4, bl5)) | 0;
- mid = (mid + Math.imul(al4, bh5)) | 0;
- mid = (mid + Math.imul(ah4, bl5)) | 0;
- hi = (hi + Math.imul(ah4, bh5)) | 0;
- lo = (lo + Math.imul(al3, bl6)) | 0;
- mid = (mid + Math.imul(al3, bh6)) | 0;
- mid = (mid + Math.imul(ah3, bl6)) | 0;
- hi = (hi + Math.imul(ah3, bh6)) | 0;
- lo = (lo + Math.imul(al2, bl7)) | 0;
- mid = (mid + Math.imul(al2, bh7)) | 0;
- mid = (mid + Math.imul(ah2, bl7)) | 0;
- hi = (hi + Math.imul(ah2, bh7)) | 0;
- lo = (lo + Math.imul(al1, bl8)) | 0;
- mid = (mid + Math.imul(al1, bh8)) | 0;
- mid = (mid + Math.imul(ah1, bl8)) | 0;
- hi = (hi + Math.imul(ah1, bh8)) | 0;
- lo = (lo + Math.imul(al0, bl9)) | 0;
- mid = (mid + Math.imul(al0, bh9)) | 0;
- mid = (mid + Math.imul(ah0, bl9)) | 0;
- hi = (hi + Math.imul(ah0, bh9)) | 0;
- var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
- w9 &= 0x3ffffff;
- /* k = 10 */
- lo = Math.imul(al9, bl1);
- mid = Math.imul(al9, bh1);
- mid = (mid + Math.imul(ah9, bl1)) | 0;
- hi = Math.imul(ah9, bh1);
- lo = (lo + Math.imul(al8, bl2)) | 0;
- mid = (mid + Math.imul(al8, bh2)) | 0;
- mid = (mid + Math.imul(ah8, bl2)) | 0;
- hi = (hi + Math.imul(ah8, bh2)) | 0;
- lo = (lo + Math.imul(al7, bl3)) | 0;
- mid = (mid + Math.imul(al7, bh3)) | 0;
- mid = (mid + Math.imul(ah7, bl3)) | 0;
- hi = (hi + Math.imul(ah7, bh3)) | 0;
- lo = (lo + Math.imul(al6, bl4)) | 0;
- mid = (mid + Math.imul(al6, bh4)) | 0;
- mid = (mid + Math.imul(ah6, bl4)) | 0;
- hi = (hi + Math.imul(ah6, bh4)) | 0;
- lo = (lo + Math.imul(al5, bl5)) | 0;
- mid = (mid + Math.imul(al5, bh5)) | 0;
- mid = (mid + Math.imul(ah5, bl5)) | 0;
- hi = (hi + Math.imul(ah5, bh5)) | 0;
- lo = (lo + Math.imul(al4, bl6)) | 0;
- mid = (mid + Math.imul(al4, bh6)) | 0;
- mid = (mid + Math.imul(ah4, bl6)) | 0;
- hi = (hi + Math.imul(ah4, bh6)) | 0;
- lo = (lo + Math.imul(al3, bl7)) | 0;
- mid = (mid + Math.imul(al3, bh7)) | 0;
- mid = (mid + Math.imul(ah3, bl7)) | 0;
- hi = (hi + Math.imul(ah3, bh7)) | 0;
- lo = (lo + Math.imul(al2, bl8)) | 0;
- mid = (mid + Math.imul(al2, bh8)) | 0;
- mid = (mid + Math.imul(ah2, bl8)) | 0;
- hi = (hi + Math.imul(ah2, bh8)) | 0;
- lo = (lo + Math.imul(al1, bl9)) | 0;
- mid = (mid + Math.imul(al1, bh9)) | 0;
- mid = (mid + Math.imul(ah1, bl9)) | 0;
- hi = (hi + Math.imul(ah1, bh9)) | 0;
- var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
- w10 &= 0x3ffffff;
- /* k = 11 */
- lo = Math.imul(al9, bl2);
- mid = Math.imul(al9, bh2);
- mid = (mid + Math.imul(ah9, bl2)) | 0;
- hi = Math.imul(ah9, bh2);
- lo = (lo + Math.imul(al8, bl3)) | 0;
- mid = (mid + Math.imul(al8, bh3)) | 0;
- mid = (mid + Math.imul(ah8, bl3)) | 0;
- hi = (hi + Math.imul(ah8, bh3)) | 0;
- lo = (lo + Math.imul(al7, bl4)) | 0;
- mid = (mid + Math.imul(al7, bh4)) | 0;
- mid = (mid + Math.imul(ah7, bl4)) | 0;
- hi = (hi + Math.imul(ah7, bh4)) | 0;
- lo = (lo + Math.imul(al6, bl5)) | 0;
- mid = (mid + Math.imul(al6, bh5)) | 0;
- mid = (mid + Math.imul(ah6, bl5)) | 0;
- hi = (hi + Math.imul(ah6, bh5)) | 0;
- lo = (lo + Math.imul(al5, bl6)) | 0;
- mid = (mid + Math.imul(al5, bh6)) | 0;
- mid = (mid + Math.imul(ah5, bl6)) | 0;
- hi = (hi + Math.imul(ah5, bh6)) | 0;
- lo = (lo + Math.imul(al4, bl7)) | 0;
- mid = (mid + Math.imul(al4, bh7)) | 0;
- mid = (mid + Math.imul(ah4, bl7)) | 0;
- hi = (hi + Math.imul(ah4, bh7)) | 0;
- lo = (lo + Math.imul(al3, bl8)) | 0;
- mid = (mid + Math.imul(al3, bh8)) | 0;
- mid = (mid + Math.imul(ah3, bl8)) | 0;
- hi = (hi + Math.imul(ah3, bh8)) | 0;
- lo = (lo + Math.imul(al2, bl9)) | 0;
- mid = (mid + Math.imul(al2, bh9)) | 0;
- mid = (mid + Math.imul(ah2, bl9)) | 0;
- hi = (hi + Math.imul(ah2, bh9)) | 0;
- var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
- w11 &= 0x3ffffff;
- /* k = 12 */
- lo = Math.imul(al9, bl3);
- mid = Math.imul(al9, bh3);
- mid = (mid + Math.imul(ah9, bl3)) | 0;
- hi = Math.imul(ah9, bh3);
- lo = (lo + Math.imul(al8, bl4)) | 0;
- mid = (mid + Math.imul(al8, bh4)) | 0;
- mid = (mid + Math.imul(ah8, bl4)) | 0;
- hi = (hi + Math.imul(ah8, bh4)) | 0;
- lo = (lo + Math.imul(al7, bl5)) | 0;
- mid = (mid + Math.imul(al7, bh5)) | 0;
- mid = (mid + Math.imul(ah7, bl5)) | 0;
- hi = (hi + Math.imul(ah7, bh5)) | 0;
- lo = (lo + Math.imul(al6, bl6)) | 0;
- mid = (mid + Math.imul(al6, bh6)) | 0;
- mid = (mid + Math.imul(ah6, bl6)) | 0;
- hi = (hi + Math.imul(ah6, bh6)) | 0;
- lo = (lo + Math.imul(al5, bl7)) | 0;
- mid = (mid + Math.imul(al5, bh7)) | 0;
- mid = (mid + Math.imul(ah5, bl7)) | 0;
- hi = (hi + Math.imul(ah5, bh7)) | 0;
- lo = (lo + Math.imul(al4, bl8)) | 0;
- mid = (mid + Math.imul(al4, bh8)) | 0;
- mid = (mid + Math.imul(ah4, bl8)) | 0;
- hi = (hi + Math.imul(ah4, bh8)) | 0;
- lo = (lo + Math.imul(al3, bl9)) | 0;
- mid = (mid + Math.imul(al3, bh9)) | 0;
- mid = (mid + Math.imul(ah3, bl9)) | 0;
- hi = (hi + Math.imul(ah3, bh9)) | 0;
- var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
- w12 &= 0x3ffffff;
- /* k = 13 */
- lo = Math.imul(al9, bl4);
- mid = Math.imul(al9, bh4);
- mid = (mid + Math.imul(ah9, bl4)) | 0;
- hi = Math.imul(ah9, bh4);
- lo = (lo + Math.imul(al8, bl5)) | 0;
- mid = (mid + Math.imul(al8, bh5)) | 0;
- mid = (mid + Math.imul(ah8, bl5)) | 0;
- hi = (hi + Math.imul(ah8, bh5)) | 0;
- lo = (lo + Math.imul(al7, bl6)) | 0;
- mid = (mid + Math.imul(al7, bh6)) | 0;
- mid = (mid + Math.imul(ah7, bl6)) | 0;
- hi = (hi + Math.imul(ah7, bh6)) | 0;
- lo = (lo + Math.imul(al6, bl7)) | 0;
- mid = (mid + Math.imul(al6, bh7)) | 0;
- mid = (mid + Math.imul(ah6, bl7)) | 0;
- hi = (hi + Math.imul(ah6, bh7)) | 0;
- lo = (lo + Math.imul(al5, bl8)) | 0;
- mid = (mid + Math.imul(al5, bh8)) | 0;
- mid = (mid + Math.imul(ah5, bl8)) | 0;
- hi = (hi + Math.imul(ah5, bh8)) | 0;
- lo = (lo + Math.imul(al4, bl9)) | 0;
- mid = (mid + Math.imul(al4, bh9)) | 0;
- mid = (mid + Math.imul(ah4, bl9)) | 0;
- hi = (hi + Math.imul(ah4, bh9)) | 0;
- var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
- w13 &= 0x3ffffff;
- /* k = 14 */
- lo = Math.imul(al9, bl5);
- mid = Math.imul(al9, bh5);
- mid = (mid + Math.imul(ah9, bl5)) | 0;
- hi = Math.imul(ah9, bh5);
- lo = (lo + Math.imul(al8, bl6)) | 0;
- mid = (mid + Math.imul(al8, bh6)) | 0;
- mid = (mid + Math.imul(ah8, bl6)) | 0;
- hi = (hi + Math.imul(ah8, bh6)) | 0;
- lo = (lo + Math.imul(al7, bl7)) | 0;
- mid = (mid + Math.imul(al7, bh7)) | 0;
- mid = (mid + Math.imul(ah7, bl7)) | 0;
- hi = (hi + Math.imul(ah7, bh7)) | 0;
- lo = (lo + Math.imul(al6, bl8)) | 0;
- mid = (mid + Math.imul(al6, bh8)) | 0;
- mid = (mid + Math.imul(ah6, bl8)) | 0;
- hi = (hi + Math.imul(ah6, bh8)) | 0;
- lo = (lo + Math.imul(al5, bl9)) | 0;
- mid = (mid + Math.imul(al5, bh9)) | 0;
- mid = (mid + Math.imul(ah5, bl9)) | 0;
- hi = (hi + Math.imul(ah5, bh9)) | 0;
- var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
- w14 &= 0x3ffffff;
- /* k = 15 */
- lo = Math.imul(al9, bl6);
- mid = Math.imul(al9, bh6);
- mid = (mid + Math.imul(ah9, bl6)) | 0;
- hi = Math.imul(ah9, bh6);
- lo = (lo + Math.imul(al8, bl7)) | 0;
- mid = (mid + Math.imul(al8, bh7)) | 0;
- mid = (mid + Math.imul(ah8, bl7)) | 0;
- hi = (hi + Math.imul(ah8, bh7)) | 0;
- lo = (lo + Math.imul(al7, bl8)) | 0;
- mid = (mid + Math.imul(al7, bh8)) | 0;
- mid = (mid + Math.imul(ah7, bl8)) | 0;
- hi = (hi + Math.imul(ah7, bh8)) | 0;
- lo = (lo + Math.imul(al6, bl9)) | 0;
- mid = (mid + Math.imul(al6, bh9)) | 0;
- mid = (mid + Math.imul(ah6, bl9)) | 0;
- hi = (hi + Math.imul(ah6, bh9)) | 0;
- var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
- w15 &= 0x3ffffff;
- /* k = 16 */
- lo = Math.imul(al9, bl7);
- mid = Math.imul(al9, bh7);
- mid = (mid + Math.imul(ah9, bl7)) | 0;
- hi = Math.imul(ah9, bh7);
- lo = (lo + Math.imul(al8, bl8)) | 0;
- mid = (mid + Math.imul(al8, bh8)) | 0;
- mid = (mid + Math.imul(ah8, bl8)) | 0;
- hi = (hi + Math.imul(ah8, bh8)) | 0;
- lo = (lo + Math.imul(al7, bl9)) | 0;
- mid = (mid + Math.imul(al7, bh9)) | 0;
- mid = (mid + Math.imul(ah7, bl9)) | 0;
- hi = (hi + Math.imul(ah7, bh9)) | 0;
- var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
- w16 &= 0x3ffffff;
- /* k = 17 */
- lo = Math.imul(al9, bl8);
- mid = Math.imul(al9, bh8);
- mid = (mid + Math.imul(ah9, bl8)) | 0;
- hi = Math.imul(ah9, bh8);
- lo = (lo + Math.imul(al8, bl9)) | 0;
- mid = (mid + Math.imul(al8, bh9)) | 0;
- mid = (mid + Math.imul(ah8, bl9)) | 0;
- hi = (hi + Math.imul(ah8, bh9)) | 0;
- var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
- w17 &= 0x3ffffff;
- /* k = 18 */
- lo = Math.imul(al9, bl9);
- mid = Math.imul(al9, bh9);
- mid = (mid + Math.imul(ah9, bl9)) | 0;
- hi = Math.imul(ah9, bh9);
- var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
- w18 &= 0x3ffffff;
- o[0] = w0;
- o[1] = w1;
- o[2] = w2;
- o[3] = w3;
- o[4] = w4;
- o[5] = w5;
- o[6] = w6;
- o[7] = w7;
- o[8] = w8;
- o[9] = w9;
- o[10] = w10;
- o[11] = w11;
- o[12] = w12;
- o[13] = w13;
- o[14] = w14;
- o[15] = w15;
- o[16] = w16;
- o[17] = w17;
- o[18] = w18;
- if (c !== 0) {
- o[19] = c;
- out.length++;
- }
- return out;
- };
- // Polyfill comb
- if (!Math.imul) {
- comb10MulTo = smallMulTo;
- }
- function bigMulTo (self, num, out) {
- out.negative = num.negative ^ self.negative;
- out.length = self.length + num.length;
- var carry = 0;
- var hncarry = 0;
- for (var k = 0; k < out.length - 1; k++) {
- // Sum all words with the same `i + j = k` and accumulate `ncarry`,
- // note that ncarry could be >= 0x3ffffff
- var ncarry = hncarry;
- hncarry = 0;
- var rword = carry & 0x3ffffff;
- var maxJ = Math.min(k, num.length - 1);
- for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
- var i = k - j;
- var a = self.words[i] | 0;
- var b = num.words[j] | 0;
- var r = a * b;
- var lo = r & 0x3ffffff;
- ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
- lo = (lo + rword) | 0;
- rword = lo & 0x3ffffff;
- ncarry = (ncarry + (lo >>> 26)) | 0;
- hncarry += ncarry >>> 26;
- ncarry &= 0x3ffffff;
- }
- out.words[k] = rword;
- carry = ncarry;
- ncarry = hncarry;
- }
- if (carry !== 0) {
- out.words[k] = carry;
- } else {
- out.length--;
- }
- return out.strip();
- }
- function jumboMulTo (self, num, out) {
- var fftm = new FFTM();
- return fftm.mulp(self, num, out);
- }
- BN.prototype.mulTo = function mulTo (num, out) {
- var res;
- var len = this.length + num.length;
- if (this.length === 10 && num.length === 10) {
- res = comb10MulTo(this, num, out);
- } else if (len < 63) {
- res = smallMulTo(this, num, out);
- } else if (len < 1024) {
- res = bigMulTo(this, num, out);
- } else {
- res = jumboMulTo(this, num, out);
- }
- return res;
- };
- // Cooley-Tukey algorithm for FFT
- // slightly revisited to rely on looping instead of recursion
- function FFTM (x, y) {
- this.x = x;
- this.y = y;
- }
- FFTM.prototype.makeRBT = function makeRBT (N) {
- var t = new Array(N);
- var l = BN.prototype._countBits(N) - 1;
- for (var i = 0; i < N; i++) {
- t[i] = this.revBin(i, l, N);
- }
- return t;
- };
- // Returns binary-reversed representation of `x`
- FFTM.prototype.revBin = function revBin (x, l, N) {
- if (x === 0 || x === N - 1) return x;
- var rb = 0;
- for (var i = 0; i < l; i++) {
- rb |= (x & 1) << (l - i - 1);
- x >>= 1;
- }
- return rb;
- };
- // Performs "tweedling" phase, therefore 'emulating'
- // behaviour of the recursive algorithm
- FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
- for (var i = 0; i < N; i++) {
- rtws[i] = rws[rbt[i]];
- itws[i] = iws[rbt[i]];
- }
- };
- FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
- this.permute(rbt, rws, iws, rtws, itws, N);
- for (var s = 1; s < N; s <<= 1) {
- var l = s << 1;
- var rtwdf = Math.cos(2 * Math.PI / l);
- var itwdf = Math.sin(2 * Math.PI / l);
- for (var p = 0; p < N; p += l) {
- var rtwdf_ = rtwdf;
- var itwdf_ = itwdf;
- for (var j = 0; j < s; j++) {
- var re = rtws[p + j];
- var ie = itws[p + j];
- var ro = rtws[p + j + s];
- var io = itws[p + j + s];
- var rx = rtwdf_ * ro - itwdf_ * io;
- io = rtwdf_ * io + itwdf_ * ro;
- ro = rx;
- rtws[p + j] = re + ro;
- itws[p + j] = ie + io;
- rtws[p + j + s] = re - ro;
- itws[p + j + s] = ie - io;
- /* jshint maxdepth : false */
- if (j !== l) {
- rx = rtwdf * rtwdf_ - itwdf * itwdf_;
- itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
- rtwdf_ = rx;
- }
- }
- }
- }
- };
- FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
- var N = Math.max(m, n) | 1;
- var odd = N & 1;
- var i = 0;
- for (N = N / 2 | 0; N; N = N >>> 1) {
- i++;
- }
- return 1 << i + 1 + odd;
- };
- FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
- if (N <= 1) return;
- for (var i = 0; i < N / 2; i++) {
- var t = rws[i];
- rws[i] = rws[N - i - 1];
- rws[N - i - 1] = t;
- t = iws[i];
- iws[i] = -iws[N - i - 1];
- iws[N - i - 1] = -t;
- }
- };
- FFTM.prototype.normalize13b = function normalize13b (ws, N) {
- var carry = 0;
- for (var i = 0; i < N / 2; i++) {
- var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
- Math.round(ws[2 * i] / N) +
- carry;
- ws[i] = w & 0x3ffffff;
- if (w < 0x4000000) {
- carry = 0;
- } else {
- carry = w / 0x4000000 | 0;
- }
- }
- return ws;
- };
- FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
- var carry = 0;
- for (var i = 0; i < len; i++) {
- carry = carry + (ws[i] | 0);
- rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
- rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
- }
- // Pad with zeroes
- for (i = 2 * len; i < N; ++i) {
- rws[i] = 0;
- }
- assert(carry === 0);
- assert((carry & ~0x1fff) === 0);
- };
- FFTM.prototype.stub = function stub (N) {
- var ph = new Array(N);
- for (var i = 0; i < N; i++) {
- ph[i] = 0;
- }
- return ph;
- };
- FFTM.prototype.mulp = function mulp (x, y, out) {
- var N = 2 * this.guessLen13b(x.length, y.length);
- var rbt = this.makeRBT(N);
- var _ = this.stub(N);
- var rws = new Array(N);
- var rwst = new Array(N);
- var iwst = new Array(N);
- var nrws = new Array(N);
- var nrwst = new Array(N);
- var niwst = new Array(N);
- var rmws = out.words;
- rmws.length = N;
- this.convert13b(x.words, x.length, rws, N);
- this.convert13b(y.words, y.length, nrws, N);
- this.transform(rws, _, rwst, iwst, N, rbt);
- this.transform(nrws, _, nrwst, niwst, N, rbt);
- for (var i = 0; i < N; i++) {
- var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
- iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
- rwst[i] = rx;
- }
- this.conjugate(rwst, iwst, N);
- this.transform(rwst, iwst, rmws, _, N, rbt);
- this.conjugate(rmws, _, N);
- this.normalize13b(rmws, N);
- out.negative = x.negative ^ y.negative;
- out.length = x.length + y.length;
- return out.strip();
- };
- // Multiply `this` by `num`
- BN.prototype.mul = function mul (num) {
- var out = new BN(null);
- out.words = new Array(this.length + num.length);
- return this.mulTo(num, out);
- };
- // Multiply employing FFT
- BN.prototype.mulf = function mulf (num) {
- var out = new BN(null);
- out.words = new Array(this.length + num.length);
- return jumboMulTo(this, num, out);
- };
- // In-place Multiplication
- BN.prototype.imul = function imul (num) {
- return this.clone().mulTo(num, this);
- };
- BN.prototype.imuln = function imuln (num) {
- assert(typeof num === 'number');
- assert(num < 0x4000000);
- // Carry
- var carry = 0;
- for (var i = 0; i < this.length; i++) {
- var w = (this.words[i] | 0) * num;
- var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
- carry >>= 26;
- carry += (w / 0x4000000) | 0;
- // NOTE: lo is 27bit maximum
- carry += lo >>> 26;
- this.words[i] = lo & 0x3ffffff;
- }
- if (carry !== 0) {
- this.words[i] = carry;
- this.length++;
- }
- return this;
- };
- BN.prototype.muln = function muln (num) {
- return this.clone().imuln(num);
- };
- // `this` * `this`
- BN.prototype.sqr = function sqr () {
- return this.mul(this);
- };
- // `this` * `this` in-place
- BN.prototype.isqr = function isqr () {
- return this.imul(this.clone());
- };
- // Math.pow(`this`, `num`)
- BN.prototype.pow = function pow (num) {
- var w = toBitArray(num);
- if (w.length === 0) return new BN(1);
- // Skip leading zeroes
- var res = this;
- for (var i = 0; i < w.length; i++, res = res.sqr()) {
- if (w[i] !== 0) break;
- }
- if (++i < w.length) {
- for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
- if (w[i] === 0) continue;
- res = res.mul(q);
- }
- }
- return res;
- };
- // Shift-left in-place
- BN.prototype.iushln = function iushln (bits) {
- assert(typeof bits === 'number' && bits >= 0);
- var r = bits % 26;
- var s = (bits - r) / 26;
- var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
- var i;
- if (r !== 0) {
- var carry = 0;
- for (i = 0; i < this.length; i++) {
- var newCarry = this.words[i] & carryMask;
- var c = ((this.words[i] | 0) - newCarry) << r;
- this.words[i] = c | carry;
- carry = newCarry >>> (26 - r);
- }
- if (carry) {
- this.words[i] = carry;
- this.length++;
- }
- }
- if (s !== 0) {
- for (i = this.length - 1; i >= 0; i--) {
- this.words[i + s] = this.words[i];
- }
- for (i = 0; i < s; i++) {
- this.words[i] = 0;
- }
- this.length += s;
- }
- return this.strip();
- };
- BN.prototype.ishln = function ishln (bits) {
- // TODO(indutny): implement me
- assert(this.negative === 0);
- return this.iushln(bits);
- };
- // Shift-right in-place
- // NOTE: `hint` is a lowest bit before trailing zeroes
- // NOTE: if `extended` is present - it will be filled with destroyed bits
- BN.prototype.iushrn = function iushrn (bits, hint, extended) {
- assert(typeof bits === 'number' && bits >= 0);
- var h;
- if (hint) {
- h = (hint - (hint % 26)) / 26;
- } else {
- h = 0;
- }
- var r = bits % 26;
- var s = Math.min((bits - r) / 26, this.length);
- var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
- var maskedWords = extended;
- h -= s;
- h = Math.max(0, h);
- // Extended mode, copy masked part
- if (maskedWords) {
- for (var i = 0; i < s; i++) {
- maskedWords.words[i] = this.words[i];
- }
- maskedWords.length = s;
- }
- if (s === 0) {
- // No-op, we should not move anything at all
- } else if (this.length > s) {
- this.length -= s;
- for (i = 0; i < this.length; i++) {
- this.words[i] = this.words[i + s];
- }
- } else {
- this.words[0] = 0;
- this.length = 1;
- }
- var carry = 0;
- for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
- var word = this.words[i] | 0;
- this.words[i] = (carry << (26 - r)) | (word >>> r);
- carry = word & mask;
- }
- // Push carried bits as a mask
- if (maskedWords && carry !== 0) {
- maskedWords.words[maskedWords.length++] = carry;
- }
- if (this.length === 0) {
- this.words[0] = 0;
- this.length = 1;
- }
- return this.strip();
- };
- BN.prototype.ishrn = function ishrn (bits, hint, extended) {
- // TODO(indutny): implement me
- assert(this.negative === 0);
- return this.iushrn(bits, hint, extended);
- };
- // Shift-left
- BN.prototype.shln = function shln (bits) {
- return this.clone().ishln(bits);
- };
- BN.prototype.ushln = function ushln (bits) {
- return this.clone().iushln(bits);
- };
- // Shift-right
- BN.prototype.shrn = function shrn (bits) {
- return this.clone().ishrn(bits);
- };
- BN.prototype.ushrn = function ushrn (bits) {
- return this.clone().iushrn(bits);
- };
- // Test if n bit is set
- BN.prototype.testn = function testn (bit) {
- assert(typeof bit === 'number' && bit >= 0);
- var r = bit % 26;
- var s = (bit - r) / 26;
- var q = 1 << r;
- // Fast case: bit is much higher than all existing words
- if (this.length <= s) return false;
- // Check bit and return
- var w = this.words[s];
- return !!(w & q);
- };
- // Return only lowers bits of number (in-place)
- BN.prototype.imaskn = function imaskn (bits) {
- assert(typeof bits === 'number' && bits >= 0);
- var r = bits % 26;
- var s = (bits - r) / 26;
- assert(this.negative === 0, 'imaskn works only with positive numbers');
- if (this.length <= s) {
- return this;
- }
- if (r !== 0) {
- s++;
- }
- this.length = Math.min(s, this.length);
- if (r !== 0) {
- var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
- this.words[this.length - 1] &= mask;
- }
- return this.strip();
- };
- // Return only lowers bits of number
- BN.prototype.maskn = function maskn (bits) {
- return this.clone().imaskn(bits);
- };
- // Add plain number `num` to `this`
- BN.prototype.iaddn = function iaddn (num) {
- assert(typeof num === 'number');
- assert(num < 0x4000000);
- if (num < 0) return this.isubn(-num);
- // Possible sign change
- if (this.negative !== 0) {
- if (this.length === 1 && (this.words[0] | 0) < num) {
- this.words[0] = num - (this.words[0] | 0);
- this.negative = 0;
- return this;
- }
- this.negative = 0;
- this.isubn(num);
- this.negative = 1;
- return this;
- }
- // Add without checks
- return this._iaddn(num);
- };
- BN.prototype._iaddn = function _iaddn (num) {
- this.words[0] += num;
- // Carry
- for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
- this.words[i] -= 0x4000000;
- if (i === this.length - 1) {
- this.words[i + 1] = 1;
- } else {
- this.words[i + 1]++;
- }
- }
- this.length = Math.max(this.length, i + 1);
- return this;
- };
- // Subtract plain number `num` from `this`
- BN.prototype.isubn = function isubn (num) {
- assert(typeof num === 'number');
- assert(num < 0x4000000);
- if (num < 0) return this.iaddn(-num);
- if (this.negative !== 0) {
- this.negative = 0;
- this.iaddn(num);
- this.negative = 1;
- return this;
- }
- this.words[0] -= num;
- if (this.length === 1 && this.words[0] < 0) {
- this.words[0] = -this.words[0];
- this.negative = 1;
- } else {
- // Carry
- for (var i = 0; i < this.length && this.words[i] < 0; i++) {
- this.words[i] += 0x4000000;
- this.words[i + 1] -= 1;
- }
- }
- return this.strip();
- };
- BN.prototype.addn = function addn (num) {
- return this.clone().iaddn(num);
- };
- BN.prototype.subn = function subn (num) {
- return this.clone().isubn(num);
- };
- BN.prototype.iabs = function iabs () {
- this.negative = 0;
- return this;
- };
- BN.prototype.abs = function abs () {
- return this.clone().iabs();
- };
- BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
- var len = num.length + shift;
- var i;
- this._expand(len);
- var w;
- var carry = 0;
- for (i = 0; i < num.length; i++) {
- w = (this.words[i + shift] | 0) + carry;
- var right = (num.words[i] | 0) * mul;
- w -= right & 0x3ffffff;
- carry = (w >> 26) - ((right / 0x4000000) | 0);
- this.words[i + shift] = w & 0x3ffffff;
- }
- for (; i < this.length - shift; i++) {
- w = (this.words[i + shift] | 0) + carry;
- carry = w >> 26;
- this.words[i + shift] = w & 0x3ffffff;
- }
- if (carry === 0) return this.strip();
- // Subtraction overflow
- assert(carry === -1);
- carry = 0;
- for (i = 0; i < this.length; i++) {
- w = -(this.words[i] | 0) + carry;
- carry = w >> 26;
- this.words[i] = w & 0x3ffffff;
- }
- this.negative = 1;
- return this.strip();
- };
- BN.prototype._wordDiv = function _wordDiv (num, mode) {
- var shift = this.length - num.length;
- var a = this.clone();
- var b = num;
- // Normalize
- var bhi = b.words[b.length - 1] | 0;
- var bhiBits = this._countBits(bhi);
- shift = 26 - bhiBits;
- if (shift !== 0) {
- b = b.ushln(shift);
- a.iushln(shift);
- bhi = b.words[b.length - 1] | 0;
- }
- // Initialize quotient
- var m = a.length - b.length;
- var q;
- if (mode !== 'mod') {
- q = new BN(null);
- q.length = m + 1;
- q.words = new Array(q.length);
- for (var i = 0; i < q.length; i++) {
- q.words[i] = 0;
- }
- }
- var diff = a.clone()._ishlnsubmul(b, 1, m);
- if (diff.negative === 0) {
- a = diff;
- if (q) {
- q.words[m] = 1;
- }
- }
- for (var j = m - 1; j >= 0; j--) {
- var qj = (a.words[b.length + j] | 0) * 0x4000000 +
- (a.words[b.length + j - 1] | 0);
- // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
- // (0x7ffffff)
- qj = Math.min((qj / bhi) | 0, 0x3ffffff);
- a._ishlnsubmul(b, qj, j);
- while (a.negative !== 0) {
- qj--;
- a.negative = 0;
- a._ishlnsubmul(b, 1, j);
- if (!a.isZero()) {
- a.negative ^= 1;
- }
- }
- if (q) {
- q.words[j] = qj;
- }
- }
- if (q) {
- q.strip();
- }
- a.strip();
- // Denormalize
- if (mode !== 'div' && shift !== 0) {
- a.iushrn(shift);
- }
- return {
- div: q || null,
- mod: a
- };
- };
- // NOTE: 1) `mode` can be set to `mod` to request mod only,
- // to `div` to request div only, or be absent to
- // request both div & mod
- // 2) `positive` is true if unsigned mod is requested
- BN.prototype.divmod = function divmod (num, mode, positive) {
- assert(!num.isZero());
- if (this.isZero()) {
- return {
- div: new BN(0),
- mod: new BN(0)
- };
- }
- var div, mod, res;
- if (this.negative !== 0 && num.negative === 0) {
- res = this.neg().divmod(num, mode);
- if (mode !== 'mod') {
- div = res.div.neg();
- }
- if (mode !== 'div') {
- mod = res.mod.neg();
- if (positive && mod.negative !== 0) {
- mod.iadd(num);
- }
- }
- return {
- div: div,
- mod: mod
- };
- }
- if (this.negative === 0 && num.negative !== 0) {
- res = this.divmod(num.neg(), mode);
- if (mode !== 'mod') {
- div = res.div.neg();
- }
- return {
- div: div,
- mod: res.mod
- };
- }
- if ((this.negative & num.negative) !== 0) {
- res = this.neg().divmod(num.neg(), mode);
- if (mode !== 'div') {
- mod = res.mod.neg();
- if (positive && mod.negative !== 0) {
- mod.isub(num);
- }
- }
- return {
- div: res.div,
- mod: mod
- };
- }
- // Both numbers are positive at this point
- // Strip both numbers to approximate shift value
- if (num.length > this.length || this.cmp(num) < 0) {
- return {
- div: new BN(0),
- mod: this
- };
- }
- // Very short reduction
- if (num.length === 1) {
- if (mode === 'div') {
- return {
- div: this.divn(num.words[0]),
- mod: null
- };
- }
- if (mode === 'mod') {
- return {
- div: null,
- mod: new BN(this.modn(num.words[0]))
- };
- }
- return {
- div: this.divn(num.words[0]),
- mod: new BN(this.modn(num.words[0]))
- };
- }
- return this._wordDiv(num, mode);
- };
- // Find `this` / `num`
- BN.prototype.div = function div (num) {
- return this.divmod(num, 'div', false).div;
- };
- // Find `this` % `num`
- BN.prototype.mod = function mod (num) {
- return this.divmod(num, 'mod', false).mod;
- };
- BN.prototype.umod = function umod (num) {
- return this.divmod(num, 'mod', true).mod;
- };
- // Find Round(`this` / `num`)
- BN.prototype.divRound = function divRound (num) {
- var dm = this.divmod(num);
- // Fast case - exact division
- if (dm.mod.isZero()) return dm.div;
- var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
- var half = num.ushrn(1);
- var r2 = num.andln(1);
- var cmp = mod.cmp(half);
- // Round down
- if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
- // Round up
- return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
- };
- BN.prototype.modn = function modn (num) {
- assert(num <= 0x3ffffff);
- var p = (1 << 26) % num;
- var acc = 0;
- for (var i = this.length - 1; i >= 0; i--) {
- acc = (p * acc + (this.words[i] | 0)) % num;
- }
- return acc;
- };
- // In-place division by number
- BN.prototype.idivn = function idivn (num) {
- assert(num <= 0x3ffffff);
- var carry = 0;
- for (var i = this.length - 1; i >= 0; i--) {
- var w = (this.words[i] | 0) + carry * 0x4000000;
- this.words[i] = (w / num) | 0;
- carry = w % num;
- }
- return this.strip();
- };
- BN.prototype.divn = function divn (num) {
- return this.clone().idivn(num);
- };
- BN.prototype.egcd = function egcd (p) {
- assert(p.negative === 0);
- assert(!p.isZero());
- var x = this;
- var y = p.clone();
- if (x.negative !== 0) {
- x = x.umod(p);
- } else {
- x = x.clone();
- }
- // A * x + B * y = x
- var A = new BN(1);
- var B = new BN(0);
- // C * x + D * y = y
- var C = new BN(0);
- var D = new BN(1);
- var g = 0;
- while (x.isEven() && y.isEven()) {
- x.iushrn(1);
- y.iushrn(1);
- ++g;
- }
- var yp = y.clone();
- var xp = x.clone();
- while (!x.isZero()) {
- for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
- if (i > 0) {
- x.iushrn(i);
- while (i-- > 0) {
- if (A.isOdd() || B.isOdd()) {
- A.iadd(yp);
- B.isub(xp);
- }
- A.iushrn(1);
- B.iushrn(1);
- }
- }
- for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
- if (j > 0) {
- y.iushrn(j);
- while (j-- > 0) {
- if (C.isOdd() || D.isOdd()) {
- C.iadd(yp);
- D.isub(xp);
- }
- C.iushrn(1);
- D.iushrn(1);
- }
- }
- if (x.cmp(y) >= 0) {
- x.isub(y);
- A.isub(C);
- B.isub(D);
- } else {
- y.isub(x);
- C.isub(A);
- D.isub(B);
- }
- }
- return {
- a: C,
- b: D,
- gcd: y.iushln(g)
- };
- };
- // This is reduced incarnation of the binary EEA
- // above, designated to invert members of the
- // _prime_ fields F(p) at a maximal speed
- BN.prototype._invmp = function _invmp (p) {
- assert(p.negative === 0);
- assert(!p.isZero());
- var a = this;
- var b = p.clone();
- if (a.negative !== 0) {
- a = a.umod(p);
- } else {
- a = a.clone();
- }
- var x1 = new BN(1);
- var x2 = new BN(0);
- var delta = b.clone();
- while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
- for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
- if (i > 0) {
- a.iushrn(i);
- while (i-- > 0) {
- if (x1.isOdd()) {
- x1.iadd(delta);
- }
- x1.iushrn(1);
- }
- }
- for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
- if (j > 0) {
- b.iushrn(j);
- while (j-- > 0) {
- if (x2.isOdd()) {
- x2.iadd(delta);
- }
- x2.iushrn(1);
- }
- }
- if (a.cmp(b) >= 0) {
- a.isub(b);
- x1.isub(x2);
- } else {
- b.isub(a);
- x2.isub(x1);
- }
- }
- var res;
- if (a.cmpn(1) === 0) {
- res = x1;
- } else {
- res = x2;
- }
- if (res.cmpn(0) < 0) {
- res.iadd(p);
- }
- return res;
- };
- BN.prototype.gcd = function gcd (num) {
- if (this.isZero()) return num.abs();
- if (num.isZero()) return this.abs();
- var a = this.clone();
- var b = num.clone();
- a.negative = 0;
- b.negative = 0;
- // Remove common factor of two
- for (var shift = 0; a.isEven() && b.isEven(); shift++) {
- a.iushrn(1);
- b.iushrn(1);
- }
- do {
- while (a.isEven()) {
- a.iushrn(1);
- }
- while (b.isEven()) {
- b.iushrn(1);
- }
- var r = a.cmp(b);
- if (r < 0) {
- // Swap `a` and `b` to make `a` always bigger than `b`
- var t = a;
- a = b;
- b = t;
- } else if (r === 0 || b.cmpn(1) === 0) {
- break;
- }
- a.isub(b);
- } while (true);
- return b.iushln(shift);
- };
- // Invert number in the field F(num)
- BN.prototype.invm = function invm (num) {
- return this.egcd(num).a.umod(num);
- };
- BN.prototype.isEven = function isEven () {
- return (this.words[0] & 1) === 0;
- };
- BN.prototype.isOdd = function isOdd () {
- return (this.words[0] & 1) === 1;
- };
- // And first word and num
- BN.prototype.andln = function andln (num) {
- return this.words[0] & num;
- };
- // Increment at the bit position in-line
- BN.prototype.bincn = function bincn (bit) {
- assert(typeof bit === 'number');
- var r = bit % 26;
- var s = (bit - r) / 26;
- var q = 1 << r;
- // Fast case: bit is much higher than all existing words
- if (this.length <= s) {
- this._expand(s + 1);
- this.words[s] |= q;
- return this;
- }
- // Add bit and propagate, if needed
- var carry = q;
- for (var i = s; carry !== 0 && i < this.length; i++) {
- var w = this.words[i] | 0;
- w += carry;
- carry = w >>> 26;
- w &= 0x3ffffff;
- this.words[i] = w;
- }
- if (carry !== 0) {
- this.words[i] = carry;
- this.length++;
- }
- return this;
- };
- BN.prototype.isZero = function isZero () {
- return this.length === 1 && this.words[0] === 0;
- };
- BN.prototype.cmpn = function cmpn (num) {
- var negative = num < 0;
- if (this.negative !== 0 && !negative) return -1;
- if (this.negative === 0 && negative) return 1;
- this.strip();
- var res;
- if (this.length > 1) {
- res = 1;
- } else {
- if (negative) {
- num = -num;
- }
- assert(num <= 0x3ffffff, 'Number is too big');
- var w = this.words[0] | 0;
- res = w === num ? 0 : w < num ? -1 : 1;
- }
- if (this.negative !== 0) return -res | 0;
- return res;
- };
- // Compare two numbers and return:
- // 1 - if `this` > `num`
- // 0 - if `this` == `num`
- // -1 - if `this` < `num`
- BN.prototype.cmp = function cmp (num) {
- if (this.negative !== 0 && num.negative === 0) return -1;
- if (this.negative === 0 && num.negative !== 0) return 1;
- var res = this.ucmp(num);
- if (this.negative !== 0) return -res | 0;
- return res;
- };
- // Unsigned comparison
- BN.prototype.ucmp = function ucmp (num) {
- // At this point both numbers have the same sign
- if (this.length > num.length) return 1;
- if (this.length < num.length) return -1;
- var res = 0;
- for (var i = this.length - 1; i >= 0; i--) {
- var a = this.words[i] | 0;
- var b = num.words[i] | 0;
- if (a === b) continue;
- if (a < b) {
- res = -1;
- } else if (a > b) {
- res = 1;
- }
- break;
- }
- return res;
- };
- BN.prototype.gtn = function gtn (num) {
- return this.cmpn(num) === 1;
- };
- BN.prototype.gt = function gt (num) {
- return this.cmp(num) === 1;
- };
- BN.prototype.gten = function gten (num) {
- return this.cmpn(num) >= 0;
- };
- BN.prototype.gte = function gte (num) {
- return this.cmp(num) >= 0;
- };
- BN.prototype.ltn = function ltn (num) {
- return this.cmpn(num) === -1;
- };
- BN.prototype.lt = function lt (num) {
- return this.cmp(num) === -1;
- };
- BN.prototype.lten = function lten (num) {
- return this.cmpn(num) <= 0;
- };
- BN.prototype.lte = function lte (num) {
- return this.cmp(num) <= 0;
- };
- BN.prototype.eqn = function eqn (num) {
- return this.cmpn(num) === 0;
- };
- BN.prototype.eq = function eq (num) {
- return this.cmp(num) === 0;
- };
- //
- // A reduce context, could be using montgomery or something better, depending
- // on the `m` itself.
- //
- BN.red = function red (num) {
- return new Red(num);
- };
- BN.prototype.toRed = function toRed (ctx) {
- assert(!this.red, 'Already a number in reduction context');
- assert(this.negative === 0, 'red works only with positives');
- return ctx.convertTo(this)._forceRed(ctx);
- };
- BN.prototype.fromRed = function fromRed () {
- assert(this.red, 'fromRed works only with numbers in reduction context');
- return this.red.convertFrom(this);
- };
- BN.prototype._forceRed = function _forceRed (ctx) {
- this.red = ctx;
- return this;
- };
- BN.prototype.forceRed = function forceRed (ctx) {
- assert(!this.red, 'Already a number in reduction context');
- return this._forceRed(ctx);
- };
- BN.prototype.redAdd = function redAdd (num) {
- assert(this.red, 'redAdd works only with red numbers');
- return this.red.add(this, num);
- };
- BN.prototype.redIAdd = function redIAdd (num) {
- assert(this.red, 'redIAdd works only with red numbers');
- return this.red.iadd(this, num);
- };
- BN.prototype.redSub = function redSub (num) {
- assert(this.red, 'redSub works only with red numbers');
- return this.red.sub(this, num);
- };
- BN.prototype.redISub = function redISub (num) {
- assert(this.red, 'redISub works only with red numbers');
- return this.red.isub(this, num);
- };
- BN.prototype.redShl = function redShl (num) {
- assert(this.red, 'redShl works only with red numbers');
- return this.red.shl(this, num);
- };
- BN.prototype.redMul = function redMul (num) {
- assert(this.red, 'redMul works only with red numbers');
- this.red._verify2(this, num);
- return this.red.mul(this, num);
- };
- BN.prototype.redIMul = function redIMul (num) {
- assert(this.red, 'redMul works only with red numbers');
- this.red._verify2(this, num);
- return this.red.imul(this, num);
- };
- BN.prototype.redSqr = function redSqr () {
- assert(this.red, 'redSqr works only with red numbers');
- this.red._verify1(this);
- return this.red.sqr(this);
- };
- BN.prototype.redISqr = function redISqr () {
- assert(this.red, 'redISqr works only with red numbers');
- this.red._verify1(this);
- return this.red.isqr(this);
- };
- // Square root over p
- BN.prototype.redSqrt = function redSqrt () {
- assert(this.red, 'redSqrt works only with red numbers');
- this.red._verify1(this);
- return this.red.sqrt(this);
- };
- BN.prototype.redInvm = function redInvm () {
- assert(this.red, 'redInvm works only with red numbers');
- this.red._verify1(this);
- return this.red.invm(this);
- };
- // Return negative clone of `this` % `red modulo`
- BN.prototype.redNeg = function redNeg () {
- assert(this.red, 'redNeg works only with red numbers');
- this.red._verify1(this);
- return this.red.neg(this);
- };
- BN.prototype.redPow = function redPow (num) {
- assert(this.red && !num.red, 'redPow(normalNum)');
- this.red._verify1(this);
- return this.red.pow(this, num);
- };
- // Prime numbers with efficient reduction
- var primes = {
- k256: null,
- p224: null,
- p192: null,
- p25519: null
- };
- // Pseudo-Mersenne prime
- function MPrime (name, p) {
- // P = 2 ^ N - K
- this.name = name;
- this.p = new BN(p, 16);
- this.n = this.p.bitLength();
- this.k = new BN(1).iushln(this.n).isub(this.p);
- this.tmp = this._tmp();
- }
- MPrime.prototype._tmp = function _tmp () {
- var tmp = new BN(null);
- tmp.words = new Array(Math.ceil(this.n / 13));
- return tmp;
- };
- MPrime.prototype.ireduce = function ireduce (num) {
- // Assumes that `num` is less than `P^2`
- // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
- var r = num;
- var rlen;
- do {
- this.split(r, this.tmp);
- r = this.imulK(r);
- r = r.iadd(this.tmp);
- rlen = r.bitLength();
- } while (rlen > this.n);
- var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
- if (cmp === 0) {
- r.words[0] = 0;
- r.length = 1;
- } else if (cmp > 0) {
- r.isub(this.p);
- } else {
- if (r.strip !== undefined) {
- // r is BN v4 instance
- r.strip();
- } else {
- // r is BN v5 instance
- r._strip();
- }
- }
- return r;
- };
- MPrime.prototype.split = function split (input, out) {
- input.iushrn(this.n, 0, out);
- };
- MPrime.prototype.imulK = function imulK (num) {
- return num.imul(this.k);
- };
- function K256 () {
- MPrime.call(
- this,
- 'k256',
- 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
- }
- inherits(K256, MPrime);
- K256.prototype.split = function split (input, output) {
- // 256 = 9 * 26 + 22
- var mask = 0x3fffff;
- var outLen = Math.min(input.length, 9);
- for (var i = 0; i < outLen; i++) {
- output.words[i] = input.words[i];
- }
- output.length = outLen;
- if (input.length <= 9) {
- input.words[0] = 0;
- input.length = 1;
- return;
- }
- // Shift by 9 limbs
- var prev = input.words[9];
- output.words[output.length++] = prev & mask;
- for (i = 10; i < input.length; i++) {
- var next = input.words[i] | 0;
- input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
- prev = next;
- }
- prev >>>= 22;
- input.words[i - 10] = prev;
- if (prev === 0 && input.length > 10) {
- input.length -= 10;
- } else {
- input.length -= 9;
- }
- };
- K256.prototype.imulK = function imulK (num) {
- // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
- num.words[num.length] = 0;
- num.words[num.length + 1] = 0;
- num.length += 2;
- // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
- var lo = 0;
- for (var i = 0; i < num.length; i++) {
- var w = num.words[i] | 0;
- lo += w * 0x3d1;
- num.words[i] = lo & 0x3ffffff;
- lo = w * 0x40 + ((lo / 0x4000000) | 0);
- }
- // Fast length reduction
- if (num.words[num.length - 1] === 0) {
- num.length--;
- if (num.words[num.length - 1] === 0) {
- num.length--;
- }
- }
- return num;
- };
- function P224 () {
- MPrime.call(
- this,
- 'p224',
- 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
- }
- inherits(P224, MPrime);
- function P192 () {
- MPrime.call(
- this,
- 'p192',
- 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
- }
- inherits(P192, MPrime);
- function P25519 () {
- // 2 ^ 255 - 19
- MPrime.call(
- this,
- '25519',
- '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
- }
- inherits(P25519, MPrime);
- P25519.prototype.imulK = function imulK (num) {
- // K = 0x13
- var carry = 0;
- for (var i = 0; i < num.length; i++) {
- var hi = (num.words[i] | 0) * 0x13 + carry;
- var lo = hi & 0x3ffffff;
- hi >>>= 26;
- num.words[i] = lo;
- carry = hi;
- }
- if (carry !== 0) {
- num.words[num.length++] = carry;
- }
- return num;
- };
- // Exported mostly for testing purposes, use plain name instead
- BN._prime = function prime (name) {
- // Cached version of prime
- if (primes[name]) return primes[name];
- var prime;
- if (name === 'k256') {
- prime = new K256();
- } else if (name === 'p224') {
- prime = new P224();
- } else if (name === 'p192') {
- prime = new P192();
- } else if (name === 'p25519') {
- prime = new P25519();
- } else {
- throw new Error('Unknown prime ' + name);
- }
- primes[name] = prime;
- return prime;
- };
- //
- // Base reduction engine
- //
- function Red (m) {
- if (typeof m === 'string') {
- var prime = BN._prime(m);
- this.m = prime.p;
- this.prime = prime;
- } else {
- assert(m.gtn(1), 'modulus must be greater than 1');
- this.m = m;
- this.prime = null;
- }
- }
- Red.prototype._verify1 = function _verify1 (a) {
- assert(a.negative === 0, 'red works only with positives');
- assert(a.red, 'red works only with red numbers');
- };
- Red.prototype._verify2 = function _verify2 (a, b) {
- assert((a.negative | b.negative) === 0, 'red works only with positives');
- assert(a.red && a.red === b.red,
- 'red works only with red numbers');
- };
- Red.prototype.imod = function imod (a) {
- if (this.prime) return this.prime.ireduce(a)._forceRed(this);
- return a.umod(this.m)._forceRed(this);
- };
- Red.prototype.neg = function neg (a) {
- if (a.isZero()) {
- return a.clone();
- }
- return this.m.sub(a)._forceRed(this);
- };
- Red.prototype.add = function add (a, b) {
- this._verify2(a, b);
- var res = a.add(b);
- if (res.cmp(this.m) >= 0) {
- res.isub(this.m);
- }
- return res._forceRed(this);
- };
- Red.prototype.iadd = function iadd (a, b) {
- this._verify2(a, b);
- var res = a.iadd(b);
- if (res.cmp(this.m) >= 0) {
- res.isub(this.m);
- }
- return res;
- };
- Red.prototype.sub = function sub (a, b) {
- this._verify2(a, b);
- var res = a.sub(b);
- if (res.cmpn(0) < 0) {
- res.iadd(this.m);
- }
- return res._forceRed(this);
- };
- Red.prototype.isub = function isub (a, b) {
- this._verify2(a, b);
- var res = a.isub(b);
- if (res.cmpn(0) < 0) {
- res.iadd(this.m);
- }
- return res;
- };
- Red.prototype.shl = function shl (a, num) {
- this._verify1(a);
- return this.imod(a.ushln(num));
- };
- Red.prototype.imul = function imul (a, b) {
- this._verify2(a, b);
- return this.imod(a.imul(b));
- };
- Red.prototype.mul = function mul (a, b) {
- this._verify2(a, b);
- return this.imod(a.mul(b));
- };
- Red.prototype.isqr = function isqr (a) {
- return this.imul(a, a.clone());
- };
- Red.prototype.sqr = function sqr (a) {
- return this.mul(a, a);
- };
- Red.prototype.sqrt = function sqrt (a) {
- if (a.isZero()) return a.clone();
- var mod3 = this.m.andln(3);
- assert(mod3 % 2 === 1);
- // Fast case
- if (mod3 === 3) {
- var pow = this.m.add(new BN(1)).iushrn(2);
- return this.pow(a, pow);
- }
- // Tonelli-Shanks algorithm (Totally unoptimized and slow)
- //
- // Find Q and S, that Q * 2 ^ S = (P - 1)
- var q = this.m.subn(1);
- var s = 0;
- while (!q.isZero() && q.andln(1) === 0) {
- s++;
- q.iushrn(1);
- }
- assert(!q.isZero());
- var one = new BN(1).toRed(this);
- var nOne = one.redNeg();
- // Find quadratic non-residue
- // NOTE: Max is such because of generalized Riemann hypothesis.
- var lpow = this.m.subn(1).iushrn(1);
- var z = this.m.bitLength();
- z = new BN(2 * z * z).toRed(this);
- while (this.pow(z, lpow).cmp(nOne) !== 0) {
- z.redIAdd(nOne);
- }
- var c = this.pow(z, q);
- var r = this.pow(a, q.addn(1).iushrn(1));
- var t = this.pow(a, q);
- var m = s;
- while (t.cmp(one) !== 0) {
- var tmp = t;
- for (var i = 0; tmp.cmp(one) !== 0; i++) {
- tmp = tmp.redSqr();
- }
- assert(i < m);
- var b = this.pow(c, new BN(1).iushln(m - i - 1));
- r = r.redMul(b);
- c = b.redSqr();
- t = t.redMul(c);
- m = i;
- }
- return r;
- };
- Red.prototype.invm = function invm (a) {
- var inv = a._invmp(this.m);
- if (inv.negative !== 0) {
- inv.negative = 0;
- return this.imod(inv).redNeg();
- } else {
- return this.imod(inv);
- }
- };
- Red.prototype.pow = function pow (a, num) {
- if (num.isZero()) return new BN(1).toRed(this);
- if (num.cmpn(1) === 0) return a.clone();
- var windowSize = 4;
- var wnd = new Array(1 << windowSize);
- wnd[0] = new BN(1).toRed(this);
- wnd[1] = a;
- for (var i = 2; i < wnd.length; i++) {
- wnd[i] = this.mul(wnd[i - 1], a);
- }
- var res = wnd[0];
- var current = 0;
- var currentLen = 0;
- var start = num.bitLength() % 26;
- if (start === 0) {
- start = 26;
- }
- for (i = num.length - 1; i >= 0; i--) {
- var word = num.words[i];
- for (var j = start - 1; j >= 0; j--) {
- var bit = (word >> j) & 1;
- if (res !== wnd[0]) {
- res = this.sqr(res);
- }
- if (bit === 0 && current === 0) {
- currentLen = 0;
- continue;
- }
- current <<= 1;
- current |= bit;
- currentLen++;
- if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
- res = this.mul(res, wnd[current]);
- currentLen = 0;
- current = 0;
- }
- start = 26;
- }
- return res;
- };
- Red.prototype.convertTo = function convertTo (num) {
- var r = num.umod(this.m);
- return r === num ? r.clone() : r;
- };
- Red.prototype.convertFrom = function convertFrom (num) {
- var res = num.clone();
- res.red = null;
- return res;
- };
- //
- // Montgomery method engine
- //
- BN.mont = function mont (num) {
- return new Mont(num);
- };
- function Mont (m) {
- Red.call(this, m);
- this.shift = this.m.bitLength();
- if (this.shift % 26 !== 0) {
- this.shift += 26 - (this.shift % 26);
- }
- this.r = new BN(1).iushln(this.shift);
- this.r2 = this.imod(this.r.sqr());
- this.rinv = this.r._invmp(this.m);
- this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
- this.minv = this.minv.umod(this.r);
- this.minv = this.r.sub(this.minv);
- }
- inherits(Mont, Red);
- Mont.prototype.convertTo = function convertTo (num) {
- return this.imod(num.ushln(this.shift));
- };
- Mont.prototype.convertFrom = function convertFrom (num) {
- var r = this.imod(num.mul(this.rinv));
- r.red = null;
- return r;
- };
- Mont.prototype.imul = function imul (a, b) {
- if (a.isZero() || b.isZero()) {
- a.words[0] = 0;
- a.length = 1;
- return a;
- }
- var t = a.imul(b);
- var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
- var u = t.isub(c).iushrn(this.shift);
- var res = u;
- if (u.cmp(this.m) >= 0) {
- res = u.isub(this.m);
- } else if (u.cmpn(0) < 0) {
- res = u.iadd(this.m);
- }
- return res._forceRed(this);
- };
- Mont.prototype.mul = function mul (a, b) {
- if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
- var t = a.mul(b);
- var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
- var u = t.isub(c).iushrn(this.shift);
- var res = u;
- if (u.cmp(this.m) >= 0) {
- res = u.isub(this.m);
- } else if (u.cmpn(0) < 0) {
- res = u.iadd(this.m);
- }
- return res._forceRed(this);
- };
- Mont.prototype.invm = function invm (a) {
- // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
- var res = this.imod(a._invmp(this.m).mul(this.r2));
- return res._forceRed(this);
- };
- })('object' === 'undefined' || module, commonjsGlobal);
- });
- var _version = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "logger/5.6.0";
- });
- var _version$1 = /*@__PURE__*/getDefaultExportFromCjs(_version);
- var lib = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Logger = exports.ErrorCode = exports.LogLevel = void 0;
- var _permanentCensorErrors = false;
- var _censorErrors = false;
- var LogLevels = { debug: 1, "default": 2, info: 2, warning: 3, error: 4, off: 5 };
- var _logLevel = LogLevels["default"];
- var _globalLogger = null;
- function _checkNormalize() {
- try {
- var missing_1 = [];
- // Make sure all forms of normalization are supported
- ["NFD", "NFC", "NFKD", "NFKC"].forEach(function (form) {
- try {
- if ("test".normalize(form) !== "test") {
- throw new Error("bad normalize");
- }
- ;
- }
- catch (error) {
- missing_1.push(form);
- }
- });
- if (missing_1.length) {
- throw new Error("missing " + missing_1.join(", "));
- }
- if (String.fromCharCode(0xe9).normalize("NFD") !== String.fromCharCode(0x65, 0x0301)) {
- throw new Error("broken implementation");
- }
- }
- catch (error) {
- return error.message;
- }
- return null;
- }
- var _normalizeError = _checkNormalize();
- var LogLevel;
- (function (LogLevel) {
- LogLevel["DEBUG"] = "DEBUG";
- LogLevel["INFO"] = "INFO";
- LogLevel["WARNING"] = "WARNING";
- LogLevel["ERROR"] = "ERROR";
- LogLevel["OFF"] = "OFF";
- })(LogLevel = exports.LogLevel || (exports.LogLevel = {}));
- var ErrorCode;
- (function (ErrorCode) {
- ///////////////////
- // Generic Errors
- // Unknown Error
- ErrorCode["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
- // Not Implemented
- ErrorCode["NOT_IMPLEMENTED"] = "NOT_IMPLEMENTED";
- // Unsupported Operation
- // - operation
- ErrorCode["UNSUPPORTED_OPERATION"] = "UNSUPPORTED_OPERATION";
- // Network Error (i.e. Ethereum Network, such as an invalid chain ID)
- // - event ("noNetwork" is not re-thrown in provider.ready; otherwise thrown)
- ErrorCode["NETWORK_ERROR"] = "NETWORK_ERROR";
- // Some sort of bad response from the server
- ErrorCode["SERVER_ERROR"] = "SERVER_ERROR";
- // Timeout
- ErrorCode["TIMEOUT"] = "TIMEOUT";
- ///////////////////
- // Operational Errors
- // Buffer Overrun
- ErrorCode["BUFFER_OVERRUN"] = "BUFFER_OVERRUN";
- // Numeric Fault
- // - operation: the operation being executed
- // - fault: the reason this faulted
- ErrorCode["NUMERIC_FAULT"] = "NUMERIC_FAULT";
- ///////////////////
- // Argument Errors
- // Missing new operator to an object
- // - name: The name of the class
- ErrorCode["MISSING_NEW"] = "MISSING_NEW";
- // Invalid argument (e.g. value is incompatible with type) to a function:
- // - argument: The argument name that was invalid
- // - value: The value of the argument
- ErrorCode["INVALID_ARGUMENT"] = "INVALID_ARGUMENT";
- // Missing argument to a function:
- // - count: The number of arguments received
- // - expectedCount: The number of arguments expected
- ErrorCode["MISSING_ARGUMENT"] = "MISSING_ARGUMENT";
- // Too many arguments
- // - count: The number of arguments received
- // - expectedCount: The number of arguments expected
- ErrorCode["UNEXPECTED_ARGUMENT"] = "UNEXPECTED_ARGUMENT";
- ///////////////////
- // Blockchain Errors
- // Call exception
- // - transaction: the transaction
- // - address?: the contract address
- // - args?: The arguments passed into the function
- // - method?: The Solidity method signature
- // - errorSignature?: The EIP848 error signature
- // - errorArgs?: The EIP848 error parameters
- // - reason: The reason (only for EIP848 "Error(string)")
- ErrorCode["CALL_EXCEPTION"] = "CALL_EXCEPTION";
- // Insufficient funds (< value + gasLimit * gasPrice)
- // - transaction: the transaction attempted
- ErrorCode["INSUFFICIENT_FUNDS"] = "INSUFFICIENT_FUNDS";
- // Nonce has already been used
- // - transaction: the transaction attempted
- ErrorCode["NONCE_EXPIRED"] = "NONCE_EXPIRED";
- // The replacement fee for the transaction is too low
- // - transaction: the transaction attempted
- ErrorCode["REPLACEMENT_UNDERPRICED"] = "REPLACEMENT_UNDERPRICED";
- // The gas limit could not be estimated
- // - transaction: the transaction passed to estimateGas
- ErrorCode["UNPREDICTABLE_GAS_LIMIT"] = "UNPREDICTABLE_GAS_LIMIT";
- // The transaction was replaced by one with a higher gas price
- // - reason: "cancelled", "replaced" or "repriced"
- // - cancelled: true if reason == "cancelled" or reason == "replaced")
- // - hash: original transaction hash
- // - replacement: the full TransactionsResponse for the replacement
- // - receipt: the receipt of the replacement
- ErrorCode["TRANSACTION_REPLACED"] = "TRANSACTION_REPLACED";
- })(ErrorCode = exports.ErrorCode || (exports.ErrorCode = {}));
- ;
- var HEX = "0123456789abcdef";
- var Logger = /** @class */ (function () {
- function Logger(version) {
- Object.defineProperty(this, "version", {
- enumerable: true,
- value: version,
- writable: false
- });
- }
- Logger.prototype._log = function (logLevel, args) {
- var level = logLevel.toLowerCase();
- if (LogLevels[level] == null) {
- this.throwArgumentError("invalid log level name", "logLevel", logLevel);
- }
- if (_logLevel > LogLevels[level]) {
- return;
- }
- console.log.apply(console, args);
- };
- Logger.prototype.debug = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- this._log(Logger.levels.DEBUG, args);
- };
- Logger.prototype.info = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- this._log(Logger.levels.INFO, args);
- };
- Logger.prototype.warn = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- this._log(Logger.levels.WARNING, args);
- };
- Logger.prototype.makeError = function (message, code, params) {
- // Errors are being censored
- if (_censorErrors) {
- return this.makeError("censored error", code, {});
- }
- if (!code) {
- code = Logger.errors.UNKNOWN_ERROR;
- }
- if (!params) {
- params = {};
- }
- var messageDetails = [];
- Object.keys(params).forEach(function (key) {
- var value = params[key];
- try {
- if (value instanceof Uint8Array) {
- var hex = "";
- for (var i = 0; i < value.length; i++) {
- hex += HEX[value[i] >> 4];
- hex += HEX[value[i] & 0x0f];
- }
- messageDetails.push(key + "=Uint8Array(0x" + hex + ")");
- }
- else {
- messageDetails.push(key + "=" + JSON.stringify(value));
- }
- }
- catch (error) {
- messageDetails.push(key + "=" + JSON.stringify(params[key].toString()));
- }
- });
- messageDetails.push("code=" + code);
- messageDetails.push("version=" + this.version);
- var reason = message;
- var url = "";
- switch (code) {
- case ErrorCode.NUMERIC_FAULT: {
- url = "NUMERIC_FAULT";
- var fault = message;
- switch (fault) {
- case "overflow":
- case "underflow":
- case "division-by-zero":
- url += "-" + fault;
- break;
- case "negative-power":
- case "negative-width":
- url += "-unsupported";
- break;
- case "unbound-bitwise-result":
- url += "-unbound-result";
- break;
- }
- break;
- }
- case ErrorCode.CALL_EXCEPTION:
- case ErrorCode.INSUFFICIENT_FUNDS:
- case ErrorCode.MISSING_NEW:
- case ErrorCode.NONCE_EXPIRED:
- case ErrorCode.REPLACEMENT_UNDERPRICED:
- case ErrorCode.TRANSACTION_REPLACED:
- case ErrorCode.UNPREDICTABLE_GAS_LIMIT:
- url = code;
- break;
- }
- if (url) {
- message += " [ See: https:/\/links.ethers.org/v5-errors-" + url + " ]";
- }
- if (messageDetails.length) {
- message += " (" + messageDetails.join(", ") + ")";
- }
- // @TODO: Any??
- var error = new Error(message);
- error.reason = reason;
- error.code = code;
- Object.keys(params).forEach(function (key) {
- error[key] = params[key];
- });
- return error;
- };
- Logger.prototype.throwError = function (message, code, params) {
- throw this.makeError(message, code, params);
- };
- Logger.prototype.throwArgumentError = function (message, name, value) {
- return this.throwError(message, Logger.errors.INVALID_ARGUMENT, {
- argument: name,
- value: value
- });
- };
- Logger.prototype.assert = function (condition, message, code, params) {
- if (!!condition) {
- return;
- }
- this.throwError(message, code, params);
- };
- Logger.prototype.assertArgument = function (condition, message, name, value) {
- if (!!condition) {
- return;
- }
- this.throwArgumentError(message, name, value);
- };
- Logger.prototype.checkNormalize = function (message) {
- if (message == null) {
- message = "platform missing String.prototype.normalize";
- }
- if (_normalizeError) {
- this.throwError("platform missing String.prototype.normalize", Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "String.prototype.normalize", form: _normalizeError
- });
- }
- };
- Logger.prototype.checkSafeUint53 = function (value, message) {
- if (typeof (value) !== "number") {
- return;
- }
- if (message == null) {
- message = "value not safe";
- }
- if (value < 0 || value >= 0x1fffffffffffff) {
- this.throwError(message, Logger.errors.NUMERIC_FAULT, {
- operation: "checkSafeInteger",
- fault: "out-of-safe-range",
- value: value
- });
- }
- if (value % 1) {
- this.throwError(message, Logger.errors.NUMERIC_FAULT, {
- operation: "checkSafeInteger",
- fault: "non-integer",
- value: value
- });
- }
- };
- Logger.prototype.checkArgumentCount = function (count, expectedCount, message) {
- if (message) {
- message = ": " + message;
- }
- else {
- message = "";
- }
- if (count < expectedCount) {
- this.throwError("missing argument" + message, Logger.errors.MISSING_ARGUMENT, {
- count: count,
- expectedCount: expectedCount
- });
- }
- if (count > expectedCount) {
- this.throwError("too many arguments" + message, Logger.errors.UNEXPECTED_ARGUMENT, {
- count: count,
- expectedCount: expectedCount
- });
- }
- };
- Logger.prototype.checkNew = function (target, kind) {
- if (target === Object || target == null) {
- this.throwError("missing new", Logger.errors.MISSING_NEW, { name: kind.name });
- }
- };
- Logger.prototype.checkAbstract = function (target, kind) {
- if (target === kind) {
- this.throwError("cannot instantiate abstract class " + JSON.stringify(kind.name) + " directly; use a sub-class", Logger.errors.UNSUPPORTED_OPERATION, { name: target.name, operation: "new" });
- }
- else if (target === Object || target == null) {
- this.throwError("missing new", Logger.errors.MISSING_NEW, { name: kind.name });
- }
- };
- Logger.globalLogger = function () {
- if (!_globalLogger) {
- _globalLogger = new Logger(_version.version);
- }
- return _globalLogger;
- };
- Logger.setCensorship = function (censorship, permanent) {
- if (!censorship && permanent) {
- this.globalLogger().throwError("cannot permanently disable censorship", Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "setCensorship"
- });
- }
- if (_permanentCensorErrors) {
- if (!censorship) {
- return;
- }
- this.globalLogger().throwError("error censorship permanent", Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "setCensorship"
- });
- }
- _censorErrors = !!censorship;
- _permanentCensorErrors = !!permanent;
- };
- Logger.setLogLevel = function (logLevel) {
- var level = LogLevels[logLevel.toLowerCase()];
- if (level == null) {
- Logger.globalLogger().warn("invalid log level - " + logLevel);
- return;
- }
- _logLevel = level;
- };
- Logger.from = function (version) {
- return new Logger(version);
- };
- Logger.errors = ErrorCode;
- Logger.levels = LogLevel;
- return Logger;
- }());
- exports.Logger = Logger;
- });
- var index = /*@__PURE__*/getDefaultExportFromCjs(lib);
- var _version$2 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "bytes/5.6.0";
- });
- var _version$3 = /*@__PURE__*/getDefaultExportFromCjs(_version$2);
- var lib$1 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.joinSignature = exports.splitSignature = exports.hexZeroPad = exports.hexStripZeros = exports.hexValue = exports.hexConcat = exports.hexDataSlice = exports.hexDataLength = exports.hexlify = exports.isHexString = exports.zeroPad = exports.stripZeros = exports.concat = exports.arrayify = exports.isBytes = exports.isBytesLike = void 0;
- var logger = new lib.Logger(_version$2.version);
- ///////////////////////////////
- function isHexable(value) {
- return !!(value.toHexString);
- }
- function addSlice(array) {
- if (array.slice) {
- return array;
- }
- array.slice = function () {
- var args = Array.prototype.slice.call(arguments);
- return addSlice(new Uint8Array(Array.prototype.slice.apply(array, args)));
- };
- return array;
- }
- function isBytesLike(value) {
- return ((isHexString(value) && !(value.length % 2)) || isBytes(value));
- }
- exports.isBytesLike = isBytesLike;
- function isInteger(value) {
- return (typeof (value) === "number" && value == value && (value % 1) === 0);
- }
- function isBytes(value) {
- if (value == null) {
- return false;
- }
- if (value.constructor === Uint8Array) {
- return true;
- }
- if (typeof (value) === "string") {
- return false;
- }
- if (!isInteger(value.length) || value.length < 0) {
- return false;
- }
- for (var i = 0; i < value.length; i++) {
- var v = value[i];
- if (!isInteger(v) || v < 0 || v >= 256) {
- return false;
- }
- }
- return true;
- }
- exports.isBytes = isBytes;
- function arrayify(value, options) {
- if (!options) {
- options = {};
- }
- if (typeof (value) === "number") {
- logger.checkSafeUint53(value, "invalid arrayify value");
- var result = [];
- while (value) {
- result.unshift(value & 0xff);
- value = parseInt(String(value / 256));
- }
- if (result.length === 0) {
- result.push(0);
- }
- return addSlice(new Uint8Array(result));
- }
- if (options.allowMissingPrefix && typeof (value) === "string" && value.substring(0, 2) !== "0x") {
- value = "0x" + value;
- }
- if (isHexable(value)) {
- value = value.toHexString();
- }
- if (isHexString(value)) {
- var hex = value.substring(2);
- if (hex.length % 2) {
- if (options.hexPad === "left") {
- hex = "0x0" + hex.substring(2);
- }
- else if (options.hexPad === "right") {
- hex += "0";
- }
- else {
- logger.throwArgumentError("hex data is odd-length", "value", value);
- }
- }
- var result = [];
- for (var i = 0; i < hex.length; i += 2) {
- result.push(parseInt(hex.substring(i, i + 2), 16));
- }
- return addSlice(new Uint8Array(result));
- }
- if (isBytes(value)) {
- return addSlice(new Uint8Array(value));
- }
- return logger.throwArgumentError("invalid arrayify value", "value", value);
- }
- exports.arrayify = arrayify;
- function concat(items) {
- var objects = items.map(function (item) { return arrayify(item); });
- var length = objects.reduce(function (accum, item) { return (accum + item.length); }, 0);
- var result = new Uint8Array(length);
- objects.reduce(function (offset, object) {
- result.set(object, offset);
- return offset + object.length;
- }, 0);
- return addSlice(result);
- }
- exports.concat = concat;
- function stripZeros(value) {
- var result = arrayify(value);
- if (result.length === 0) {
- return result;
- }
- // Find the first non-zero entry
- var start = 0;
- while (start < result.length && result[start] === 0) {
- start++;
- }
- // If we started with zeros, strip them
- if (start) {
- result = result.slice(start);
- }
- return result;
- }
- exports.stripZeros = stripZeros;
- function zeroPad(value, length) {
- value = arrayify(value);
- if (value.length > length) {
- logger.throwArgumentError("value out of range", "value", arguments[0]);
- }
- var result = new Uint8Array(length);
- result.set(value, length - value.length);
- return addSlice(result);
- }
- exports.zeroPad = zeroPad;
- function isHexString(value, length) {
- if (typeof (value) !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) {
- return false;
- }
- if (length && value.length !== 2 + 2 * length) {
- return false;
- }
- return true;
- }
- exports.isHexString = isHexString;
- var HexCharacters = "0123456789abcdef";
- function hexlify(value, options) {
- if (!options) {
- options = {};
- }
- if (typeof (value) === "number") {
- logger.checkSafeUint53(value, "invalid hexlify value");
- var hex = "";
- while (value) {
- hex = HexCharacters[value & 0xf] + hex;
- value = Math.floor(value / 16);
- }
- if (hex.length) {
- if (hex.length % 2) {
- hex = "0" + hex;
- }
- return "0x" + hex;
- }
- return "0x00";
- }
- if (typeof (value) === "bigint") {
- value = value.toString(16);
- if (value.length % 2) {
- return ("0x0" + value);
- }
- return "0x" + value;
- }
- if (options.allowMissingPrefix && typeof (value) === "string" && value.substring(0, 2) !== "0x") {
- value = "0x" + value;
- }
- if (isHexable(value)) {
- return value.toHexString();
- }
- if (isHexString(value)) {
- if (value.length % 2) {
- if (options.hexPad === "left") {
- value = "0x0" + value.substring(2);
- }
- else if (options.hexPad === "right") {
- value += "0";
- }
- else {
- logger.throwArgumentError("hex data is odd-length", "value", value);
- }
- }
- return value.toLowerCase();
- }
- if (isBytes(value)) {
- var result = "0x";
- for (var i = 0; i < value.length; i++) {
- var v = value[i];
- result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f];
- }
- return result;
- }
- return logger.throwArgumentError("invalid hexlify value", "value", value);
- }
- exports.hexlify = hexlify;
- /*
- function unoddify(value: BytesLike | Hexable | number): BytesLike | Hexable | number {
- if (typeof(value) === "string" && value.length % 2 && value.substring(0, 2) === "0x") {
- return "0x0" + value.substring(2);
- }
- return value;
- }
- */
- function hexDataLength(data) {
- if (typeof (data) !== "string") {
- data = hexlify(data);
- }
- else if (!isHexString(data) || (data.length % 2)) {
- return null;
- }
- return (data.length - 2) / 2;
- }
- exports.hexDataLength = hexDataLength;
- function hexDataSlice(data, offset, endOffset) {
- if (typeof (data) !== "string") {
- data = hexlify(data);
- }
- else if (!isHexString(data) || (data.length % 2)) {
- logger.throwArgumentError("invalid hexData", "value", data);
- }
- offset = 2 + 2 * offset;
- if (endOffset != null) {
- return "0x" + data.substring(offset, 2 + 2 * endOffset);
- }
- return "0x" + data.substring(offset);
- }
- exports.hexDataSlice = hexDataSlice;
- function hexConcat(items) {
- var result = "0x";
- items.forEach(function (item) {
- result += hexlify(item).substring(2);
- });
- return result;
- }
- exports.hexConcat = hexConcat;
- function hexValue(value) {
- var trimmed = hexStripZeros(hexlify(value, { hexPad: "left" }));
- if (trimmed === "0x") {
- return "0x0";
- }
- return trimmed;
- }
- exports.hexValue = hexValue;
- function hexStripZeros(value) {
- if (typeof (value) !== "string") {
- value = hexlify(value);
- }
- if (!isHexString(value)) {
- logger.throwArgumentError("invalid hex string", "value", value);
- }
- value = value.substring(2);
- var offset = 0;
- while (offset < value.length && value[offset] === "0") {
- offset++;
- }
- return "0x" + value.substring(offset);
- }
- exports.hexStripZeros = hexStripZeros;
- function hexZeroPad(value, length) {
- if (typeof (value) !== "string") {
- value = hexlify(value);
- }
- else if (!isHexString(value)) {
- logger.throwArgumentError("invalid hex string", "value", value);
- }
- if (value.length > 2 * length + 2) {
- logger.throwArgumentError("value out of range", "value", arguments[1]);
- }
- while (value.length < 2 * length + 2) {
- value = "0x0" + value.substring(2);
- }
- return value;
- }
- exports.hexZeroPad = hexZeroPad;
- function splitSignature(signature) {
- var result = {
- r: "0x",
- s: "0x",
- _vs: "0x",
- recoveryParam: 0,
- v: 0,
- yParityAndS: "0x",
- compact: "0x"
- };
- if (isBytesLike(signature)) {
- var bytes = arrayify(signature);
- // Get the r, s and v
- if (bytes.length === 64) {
- // EIP-2098; pull the v from the top bit of s and clear it
- result.v = 27 + (bytes[32] >> 7);
- bytes[32] &= 0x7f;
- result.r = hexlify(bytes.slice(0, 32));
- result.s = hexlify(bytes.slice(32, 64));
- }
- else if (bytes.length === 65) {
- result.r = hexlify(bytes.slice(0, 32));
- result.s = hexlify(bytes.slice(32, 64));
- result.v = bytes[64];
- }
- else {
- logger.throwArgumentError("invalid signature string", "signature", signature);
- }
- // Allow a recid to be used as the v
- if (result.v < 27) {
- if (result.v === 0 || result.v === 1) {
- result.v += 27;
- }
- else {
- logger.throwArgumentError("signature invalid v byte", "signature", signature);
- }
- }
- // Compute recoveryParam from v
- result.recoveryParam = 1 - (result.v % 2);
- // Compute _vs from recoveryParam and s
- if (result.recoveryParam) {
- bytes[32] |= 0x80;
- }
- result._vs = hexlify(bytes.slice(32, 64));
- }
- else {
- result.r = signature.r;
- result.s = signature.s;
- result.v = signature.v;
- result.recoveryParam = signature.recoveryParam;
- result._vs = signature._vs;
- // If the _vs is available, use it to populate missing s, v and recoveryParam
- // and verify non-missing s, v and recoveryParam
- if (result._vs != null) {
- var vs_1 = zeroPad(arrayify(result._vs), 32);
- result._vs = hexlify(vs_1);
- // Set or check the recid
- var recoveryParam = ((vs_1[0] >= 128) ? 1 : 0);
- if (result.recoveryParam == null) {
- result.recoveryParam = recoveryParam;
- }
- else if (result.recoveryParam !== recoveryParam) {
- logger.throwArgumentError("signature recoveryParam mismatch _vs", "signature", signature);
- }
- // Set or check the s
- vs_1[0] &= 0x7f;
- var s = hexlify(vs_1);
- if (result.s == null) {
- result.s = s;
- }
- else if (result.s !== s) {
- logger.throwArgumentError("signature v mismatch _vs", "signature", signature);
- }
- }
- // Use recid and v to populate each other
- if (result.recoveryParam == null) {
- if (result.v == null) {
- logger.throwArgumentError("signature missing v and recoveryParam", "signature", signature);
- }
- else if (result.v === 0 || result.v === 1) {
- result.recoveryParam = result.v;
- }
- else {
- result.recoveryParam = 1 - (result.v % 2);
- }
- }
- else {
- if (result.v == null) {
- result.v = 27 + result.recoveryParam;
- }
- else {
- var recId = (result.v === 0 || result.v === 1) ? result.v : (1 - (result.v % 2));
- if (result.recoveryParam !== recId) {
- logger.throwArgumentError("signature recoveryParam mismatch v", "signature", signature);
- }
- }
- }
- if (result.r == null || !isHexString(result.r)) {
- logger.throwArgumentError("signature missing or invalid r", "signature", signature);
- }
- else {
- result.r = hexZeroPad(result.r, 32);
- }
- if (result.s == null || !isHexString(result.s)) {
- logger.throwArgumentError("signature missing or invalid s", "signature", signature);
- }
- else {
- result.s = hexZeroPad(result.s, 32);
- }
- var vs = arrayify(result.s);
- if (vs[0] >= 128) {
- logger.throwArgumentError("signature s out of range", "signature", signature);
- }
- if (result.recoveryParam) {
- vs[0] |= 0x80;
- }
- var _vs = hexlify(vs);
- if (result._vs) {
- if (!isHexString(result._vs)) {
- logger.throwArgumentError("signature invalid _vs", "signature", signature);
- }
- result._vs = hexZeroPad(result._vs, 32);
- }
- // Set or check the _vs
- if (result._vs == null) {
- result._vs = _vs;
- }
- else if (result._vs !== _vs) {
- logger.throwArgumentError("signature _vs mismatch v and s", "signature", signature);
- }
- }
- result.yParityAndS = result._vs;
- result.compact = result.r + result.yParityAndS.substring(2);
- return result;
- }
- exports.splitSignature = splitSignature;
- function joinSignature(signature) {
- signature = splitSignature(signature);
- return hexlify(concat([
- signature.r,
- signature.s,
- (signature.recoveryParam ? "0x1c" : "0x1b")
- ]));
- }
- exports.joinSignature = joinSignature;
- });
- var index$1 = /*@__PURE__*/getDefaultExportFromCjs(lib$1);
- var _version$4 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "bignumber/5.6.0";
- });
- var _version$5 = /*@__PURE__*/getDefaultExportFromCjs(_version$4);
- var bignumber = createCommonjsModule(function (module, exports) {
- "use strict";
- var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports._base16To36 = exports._base36To16 = exports.BigNumber = exports.isBigNumberish = void 0;
- /**
- * BigNumber
- *
- * A wrapper around the BN.js object. We use the BN.js library
- * because it is used by elliptic, so it is required regardless.
- *
- */
- var bn_js_1 = __importDefault(bn);
- var BN = bn_js_1.default.BN;
- var logger = new lib.Logger(_version$4.version);
- var _constructorGuard = {};
- var MAX_SAFE = 0x1fffffffffffff;
- function isBigNumberish(value) {
- return (value != null) && (BigNumber.isBigNumber(value) ||
- (typeof (value) === "number" && (value % 1) === 0) ||
- (typeof (value) === "string" && !!value.match(/^-?[0-9]+$/)) ||
- (0, lib$1.isHexString)(value) ||
- (typeof (value) === "bigint") ||
- (0, lib$1.isBytes)(value));
- }
- exports.isBigNumberish = isBigNumberish;
- // Only warn about passing 10 into radix once
- var _warnedToStringRadix = false;
- var BigNumber = /** @class */ (function () {
- function BigNumber(constructorGuard, hex) {
- var _newTarget = this.constructor;
- logger.checkNew(_newTarget, BigNumber);
- if (constructorGuard !== _constructorGuard) {
- logger.throwError("cannot call constructor directly; use BigNumber.from", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "new (BigNumber)"
- });
- }
- this._hex = hex;
- this._isBigNumber = true;
- Object.freeze(this);
- }
- BigNumber.prototype.fromTwos = function (value) {
- return toBigNumber(toBN(this).fromTwos(value));
- };
- BigNumber.prototype.toTwos = function (value) {
- return toBigNumber(toBN(this).toTwos(value));
- };
- BigNumber.prototype.abs = function () {
- if (this._hex[0] === "-") {
- return BigNumber.from(this._hex.substring(1));
- }
- return this;
- };
- BigNumber.prototype.add = function (other) {
- return toBigNumber(toBN(this).add(toBN(other)));
- };
- BigNumber.prototype.sub = function (other) {
- return toBigNumber(toBN(this).sub(toBN(other)));
- };
- BigNumber.prototype.div = function (other) {
- var o = BigNumber.from(other);
- if (o.isZero()) {
- throwFault("division-by-zero", "div");
- }
- return toBigNumber(toBN(this).div(toBN(other)));
- };
- BigNumber.prototype.mul = function (other) {
- return toBigNumber(toBN(this).mul(toBN(other)));
- };
- BigNumber.prototype.mod = function (other) {
- var value = toBN(other);
- if (value.isNeg()) {
- throwFault("division-by-zero", "mod");
- }
- return toBigNumber(toBN(this).umod(value));
- };
- BigNumber.prototype.pow = function (other) {
- var value = toBN(other);
- if (value.isNeg()) {
- throwFault("negative-power", "pow");
- }
- return toBigNumber(toBN(this).pow(value));
- };
- BigNumber.prototype.and = function (other) {
- var value = toBN(other);
- if (this.isNegative() || value.isNeg()) {
- throwFault("unbound-bitwise-result", "and");
- }
- return toBigNumber(toBN(this).and(value));
- };
- BigNumber.prototype.or = function (other) {
- var value = toBN(other);
- if (this.isNegative() || value.isNeg()) {
- throwFault("unbound-bitwise-result", "or");
- }
- return toBigNumber(toBN(this).or(value));
- };
- BigNumber.prototype.xor = function (other) {
- var value = toBN(other);
- if (this.isNegative() || value.isNeg()) {
- throwFault("unbound-bitwise-result", "xor");
- }
- return toBigNumber(toBN(this).xor(value));
- };
- BigNumber.prototype.mask = function (value) {
- if (this.isNegative() || value < 0) {
- throwFault("negative-width", "mask");
- }
- return toBigNumber(toBN(this).maskn(value));
- };
- BigNumber.prototype.shl = function (value) {
- if (this.isNegative() || value < 0) {
- throwFault("negative-width", "shl");
- }
- return toBigNumber(toBN(this).shln(value));
- };
- BigNumber.prototype.shr = function (value) {
- if (this.isNegative() || value < 0) {
- throwFault("negative-width", "shr");
- }
- return toBigNumber(toBN(this).shrn(value));
- };
- BigNumber.prototype.eq = function (other) {
- return toBN(this).eq(toBN(other));
- };
- BigNumber.prototype.lt = function (other) {
- return toBN(this).lt(toBN(other));
- };
- BigNumber.prototype.lte = function (other) {
- return toBN(this).lte(toBN(other));
- };
- BigNumber.prototype.gt = function (other) {
- return toBN(this).gt(toBN(other));
- };
- BigNumber.prototype.gte = function (other) {
- return toBN(this).gte(toBN(other));
- };
- BigNumber.prototype.isNegative = function () {
- return (this._hex[0] === "-");
- };
- BigNumber.prototype.isZero = function () {
- return toBN(this).isZero();
- };
- BigNumber.prototype.toNumber = function () {
- try {
- return toBN(this).toNumber();
- }
- catch (error) {
- throwFault("overflow", "toNumber", this.toString());
- }
- return null;
- };
- BigNumber.prototype.toBigInt = function () {
- try {
- return BigInt(this.toString());
- }
- catch (e) { }
- return logger.throwError("this platform does not support BigInt", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- value: this.toString()
- });
- };
- BigNumber.prototype.toString = function () {
- // Lots of people expect this, which we do not support, so check (See: #889)
- if (arguments.length > 0) {
- if (arguments[0] === 10) {
- if (!_warnedToStringRadix) {
- _warnedToStringRadix = true;
- logger.warn("BigNumber.toString does not accept any parameters; base-10 is assumed");
- }
- }
- else if (arguments[0] === 16) {
- logger.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()", lib.Logger.errors.UNEXPECTED_ARGUMENT, {});
- }
- else {
- logger.throwError("BigNumber.toString does not accept parameters", lib.Logger.errors.UNEXPECTED_ARGUMENT, {});
- }
- }
- return toBN(this).toString(10);
- };
- BigNumber.prototype.toHexString = function () {
- return this._hex;
- };
- BigNumber.prototype.toJSON = function (key) {
- return { type: "BigNumber", hex: this.toHexString() };
- };
- BigNumber.from = function (value) {
- if (value instanceof BigNumber) {
- return value;
- }
- if (typeof (value) === "string") {
- if (value.match(/^-?0x[0-9a-f]+$/i)) {
- return new BigNumber(_constructorGuard, toHex(value));
- }
- if (value.match(/^-?[0-9]+$/)) {
- return new BigNumber(_constructorGuard, toHex(new BN(value)));
- }
- return logger.throwArgumentError("invalid BigNumber string", "value", value);
- }
- if (typeof (value) === "number") {
- if (value % 1) {
- throwFault("underflow", "BigNumber.from", value);
- }
- if (value >= MAX_SAFE || value <= -MAX_SAFE) {
- throwFault("overflow", "BigNumber.from", value);
- }
- return BigNumber.from(String(value));
- }
- var anyValue = value;
- if (typeof (anyValue) === "bigint") {
- return BigNumber.from(anyValue.toString());
- }
- if ((0, lib$1.isBytes)(anyValue)) {
- return BigNumber.from((0, lib$1.hexlify)(anyValue));
- }
- if (anyValue) {
- // Hexable interface (takes priority)
- if (anyValue.toHexString) {
- var hex = anyValue.toHexString();
- if (typeof (hex) === "string") {
- return BigNumber.from(hex);
- }
- }
- else {
- // For now, handle legacy JSON-ified values (goes away in v6)
- var hex = anyValue._hex;
- // New-form JSON
- if (hex == null && anyValue.type === "BigNumber") {
- hex = anyValue.hex;
- }
- if (typeof (hex) === "string") {
- if ((0, lib$1.isHexString)(hex) || (hex[0] === "-" && (0, lib$1.isHexString)(hex.substring(1)))) {
- return BigNumber.from(hex);
- }
- }
- }
- }
- return logger.throwArgumentError("invalid BigNumber value", "value", value);
- };
- BigNumber.isBigNumber = function (value) {
- return !!(value && value._isBigNumber);
- };
- return BigNumber;
- }());
- exports.BigNumber = BigNumber;
- // Normalize the hex string
- function toHex(value) {
- // For BN, call on the hex string
- if (typeof (value) !== "string") {
- return toHex(value.toString(16));
- }
- // If negative, prepend the negative sign to the normalized positive value
- if (value[0] === "-") {
- // Strip off the negative sign
- value = value.substring(1);
- // Cannot have multiple negative signs (e.g. "--0x04")
- if (value[0] === "-") {
- logger.throwArgumentError("invalid hex", "value", value);
- }
- // Call toHex on the positive component
- value = toHex(value);
- // Do not allow "-0x00"
- if (value === "0x00") {
- return value;
- }
- // Negate the value
- return "-" + value;
- }
- // Add a "0x" prefix if missing
- if (value.substring(0, 2) !== "0x") {
- value = "0x" + value;
- }
- // Normalize zero
- if (value === "0x") {
- return "0x00";
- }
- // Make the string even length
- if (value.length % 2) {
- value = "0x0" + value.substring(2);
- }
- // Trim to smallest even-length string
- while (value.length > 4 && value.substring(0, 4) === "0x00") {
- value = "0x" + value.substring(4);
- }
- return value;
- }
- function toBigNumber(value) {
- return BigNumber.from(toHex(value));
- }
- function toBN(value) {
- var hex = BigNumber.from(value).toHexString();
- if (hex[0] === "-") {
- return (new BN("-" + hex.substring(3), 16));
- }
- return new BN(hex.substring(2), 16);
- }
- function throwFault(fault, operation, value) {
- var params = { fault: fault, operation: operation };
- if (value != null) {
- params.value = value;
- }
- return logger.throwError(fault, lib.Logger.errors.NUMERIC_FAULT, params);
- }
- // value should have no prefix
- function _base36To16(value) {
- return (new BN(value, 36)).toString(16);
- }
- exports._base36To16 = _base36To16;
- // value should have no prefix
- function _base16To36(value) {
- return (new BN(value, 16)).toString(36);
- }
- exports._base16To36 = _base16To36;
- });
- var bignumber$1 = /*@__PURE__*/getDefaultExportFromCjs(bignumber);
- var fixednumber = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.FixedNumber = exports.FixedFormat = exports.parseFixed = exports.formatFixed = void 0;
- var logger = new lib.Logger(_version$4.version);
- var _constructorGuard = {};
- var Zero = bignumber.BigNumber.from(0);
- var NegativeOne = bignumber.BigNumber.from(-1);
- function throwFault(message, fault, operation, value) {
- var params = { fault: fault, operation: operation };
- if (value !== undefined) {
- params.value = value;
- }
- return logger.throwError(message, lib.Logger.errors.NUMERIC_FAULT, params);
- }
- // Constant to pull zeros from for multipliers
- var zeros = "0";
- while (zeros.length < 256) {
- zeros += zeros;
- }
- // Returns a string "1" followed by decimal "0"s
- function getMultiplier(decimals) {
- if (typeof (decimals) !== "number") {
- try {
- decimals = bignumber.BigNumber.from(decimals).toNumber();
- }
- catch (e) { }
- }
- if (typeof (decimals) === "number" && decimals >= 0 && decimals <= 256 && !(decimals % 1)) {
- return ("1" + zeros.substring(0, decimals));
- }
- return logger.throwArgumentError("invalid decimal size", "decimals", decimals);
- }
- function formatFixed(value, decimals) {
- if (decimals == null) {
- decimals = 0;
- }
- var multiplier = getMultiplier(decimals);
- // Make sure wei is a big number (convert as necessary)
- value = bignumber.BigNumber.from(value);
- var negative = value.lt(Zero);
- if (negative) {
- value = value.mul(NegativeOne);
- }
- var fraction = value.mod(multiplier).toString();
- while (fraction.length < multiplier.length - 1) {
- fraction = "0" + fraction;
- }
- // Strip training 0
- fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1];
- var whole = value.div(multiplier).toString();
- if (multiplier.length === 1) {
- value = whole;
- }
- else {
- value = whole + "." + fraction;
- }
- if (negative) {
- value = "-" + value;
- }
- return value;
- }
- exports.formatFixed = formatFixed;
- function parseFixed(value, decimals) {
- if (decimals == null) {
- decimals = 0;
- }
- var multiplier = getMultiplier(decimals);
- if (typeof (value) !== "string" || !value.match(/^-?[0-9.]+$/)) {
- logger.throwArgumentError("invalid decimal value", "value", value);
- }
- // Is it negative?
- var negative = (value.substring(0, 1) === "-");
- if (negative) {
- value = value.substring(1);
- }
- if (value === ".") {
- logger.throwArgumentError("missing value", "value", value);
- }
- // Split it into a whole and fractional part
- var comps = value.split(".");
- if (comps.length > 2) {
- logger.throwArgumentError("too many decimal points", "value", value);
- }
- var whole = comps[0], fraction = comps[1];
- if (!whole) {
- whole = "0";
- }
- if (!fraction) {
- fraction = "0";
- }
- // Trim trailing zeros
- while (fraction[fraction.length - 1] === "0") {
- fraction = fraction.substring(0, fraction.length - 1);
- }
- // Check the fraction doesn't exceed our decimals size
- if (fraction.length > multiplier.length - 1) {
- throwFault("fractional component exceeds decimals", "underflow", "parseFixed");
- }
- // If decimals is 0, we have an empty string for fraction
- if (fraction === "") {
- fraction = "0";
- }
- // Fully pad the string with zeros to get to wei
- while (fraction.length < multiplier.length - 1) {
- fraction += "0";
- }
- var wholeValue = bignumber.BigNumber.from(whole);
- var fractionValue = bignumber.BigNumber.from(fraction);
- var wei = (wholeValue.mul(multiplier)).add(fractionValue);
- if (negative) {
- wei = wei.mul(NegativeOne);
- }
- return wei;
- }
- exports.parseFixed = parseFixed;
- var FixedFormat = /** @class */ (function () {
- function FixedFormat(constructorGuard, signed, width, decimals) {
- if (constructorGuard !== _constructorGuard) {
- logger.throwError("cannot use FixedFormat constructor; use FixedFormat.from", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "new FixedFormat"
- });
- }
- this.signed = signed;
- this.width = width;
- this.decimals = decimals;
- this.name = (signed ? "" : "u") + "fixed" + String(width) + "x" + String(decimals);
- this._multiplier = getMultiplier(decimals);
- Object.freeze(this);
- }
- FixedFormat.from = function (value) {
- if (value instanceof FixedFormat) {
- return value;
- }
- if (typeof (value) === "number") {
- value = "fixed128x" + value;
- }
- var signed = true;
- var width = 128;
- var decimals = 18;
- if (typeof (value) === "string") {
- if (value === "fixed") {
- // defaults...
- }
- else if (value === "ufixed") {
- signed = false;
- }
- else {
- var match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);
- if (!match) {
- logger.throwArgumentError("invalid fixed format", "format", value);
- }
- signed = (match[1] !== "u");
- width = parseInt(match[2]);
- decimals = parseInt(match[3]);
- }
- }
- else if (value) {
- var check = function (key, type, defaultValue) {
- if (value[key] == null) {
- return defaultValue;
- }
- if (typeof (value[key]) !== type) {
- logger.throwArgumentError("invalid fixed format (" + key + " not " + type + ")", "format." + key, value[key]);
- }
- return value[key];
- };
- signed = check("signed", "boolean", signed);
- width = check("width", "number", width);
- decimals = check("decimals", "number", decimals);
- }
- if (width % 8) {
- logger.throwArgumentError("invalid fixed format width (not byte aligned)", "format.width", width);
- }
- if (decimals > 80) {
- logger.throwArgumentError("invalid fixed format (decimals too large)", "format.decimals", decimals);
- }
- return new FixedFormat(_constructorGuard, signed, width, decimals);
- };
- return FixedFormat;
- }());
- exports.FixedFormat = FixedFormat;
- var FixedNumber = /** @class */ (function () {
- function FixedNumber(constructorGuard, hex, value, format) {
- var _newTarget = this.constructor;
- logger.checkNew(_newTarget, FixedNumber);
- if (constructorGuard !== _constructorGuard) {
- logger.throwError("cannot use FixedNumber constructor; use FixedNumber.from", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "new FixedFormat"
- });
- }
- this.format = format;
- this._hex = hex;
- this._value = value;
- this._isFixedNumber = true;
- Object.freeze(this);
- }
- FixedNumber.prototype._checkFormat = function (other) {
- if (this.format.name !== other.format.name) {
- logger.throwArgumentError("incompatible format; use fixedNumber.toFormat", "other", other);
- }
- };
- FixedNumber.prototype.addUnsafe = function (other) {
- this._checkFormat(other);
- var a = parseFixed(this._value, this.format.decimals);
- var b = parseFixed(other._value, other.format.decimals);
- return FixedNumber.fromValue(a.add(b), this.format.decimals, this.format);
- };
- FixedNumber.prototype.subUnsafe = function (other) {
- this._checkFormat(other);
- var a = parseFixed(this._value, this.format.decimals);
- var b = parseFixed(other._value, other.format.decimals);
- return FixedNumber.fromValue(a.sub(b), this.format.decimals, this.format);
- };
- FixedNumber.prototype.mulUnsafe = function (other) {
- this._checkFormat(other);
- var a = parseFixed(this._value, this.format.decimals);
- var b = parseFixed(other._value, other.format.decimals);
- return FixedNumber.fromValue(a.mul(b).div(this.format._multiplier), this.format.decimals, this.format);
- };
- FixedNumber.prototype.divUnsafe = function (other) {
- this._checkFormat(other);
- var a = parseFixed(this._value, this.format.decimals);
- var b = parseFixed(other._value, other.format.decimals);
- return FixedNumber.fromValue(a.mul(this.format._multiplier).div(b), this.format.decimals, this.format);
- };
- FixedNumber.prototype.floor = function () {
- var comps = this.toString().split(".");
- if (comps.length === 1) {
- comps.push("0");
- }
- var result = FixedNumber.from(comps[0], this.format);
- var hasFraction = !comps[1].match(/^(0*)$/);
- if (this.isNegative() && hasFraction) {
- result = result.subUnsafe(ONE.toFormat(result.format));
- }
- return result;
- };
- FixedNumber.prototype.ceiling = function () {
- var comps = this.toString().split(".");
- if (comps.length === 1) {
- comps.push("0");
- }
- var result = FixedNumber.from(comps[0], this.format);
- var hasFraction = !comps[1].match(/^(0*)$/);
- if (!this.isNegative() && hasFraction) {
- result = result.addUnsafe(ONE.toFormat(result.format));
- }
- return result;
- };
- // @TODO: Support other rounding algorithms
- FixedNumber.prototype.round = function (decimals) {
- if (decimals == null) {
- decimals = 0;
- }
- // If we are already in range, we're done
- var comps = this.toString().split(".");
- if (comps.length === 1) {
- comps.push("0");
- }
- if (decimals < 0 || decimals > 80 || (decimals % 1)) {
- logger.throwArgumentError("invalid decimal count", "decimals", decimals);
- }
- if (comps[1].length <= decimals) {
- return this;
- }
- var factor = FixedNumber.from("1" + zeros.substring(0, decimals), this.format);
- var bump = BUMP.toFormat(this.format);
- return this.mulUnsafe(factor).addUnsafe(bump).floor().divUnsafe(factor);
- };
- FixedNumber.prototype.isZero = function () {
- return (this._value === "0.0" || this._value === "0");
- };
- FixedNumber.prototype.isNegative = function () {
- return (this._value[0] === "-");
- };
- FixedNumber.prototype.toString = function () { return this._value; };
- FixedNumber.prototype.toHexString = function (width) {
- if (width == null) {
- return this._hex;
- }
- if (width % 8) {
- logger.throwArgumentError("invalid byte width", "width", width);
- }
- var hex = bignumber.BigNumber.from(this._hex).fromTwos(this.format.width).toTwos(width).toHexString();
- return (0, lib$1.hexZeroPad)(hex, width / 8);
- };
- FixedNumber.prototype.toUnsafeFloat = function () { return parseFloat(this.toString()); };
- FixedNumber.prototype.toFormat = function (format) {
- return FixedNumber.fromString(this._value, format);
- };
- FixedNumber.fromValue = function (value, decimals, format) {
- // If decimals looks more like a format, and there is no format, shift the parameters
- if (format == null && decimals != null && !(0, bignumber.isBigNumberish)(decimals)) {
- format = decimals;
- decimals = null;
- }
- if (decimals == null) {
- decimals = 0;
- }
- if (format == null) {
- format = "fixed";
- }
- return FixedNumber.fromString(formatFixed(value, decimals), FixedFormat.from(format));
- };
- FixedNumber.fromString = function (value, format) {
- if (format == null) {
- format = "fixed";
- }
- var fixedFormat = FixedFormat.from(format);
- var numeric = parseFixed(value, fixedFormat.decimals);
- if (!fixedFormat.signed && numeric.lt(Zero)) {
- throwFault("unsigned value cannot be negative", "overflow", "value", value);
- }
- var hex = null;
- if (fixedFormat.signed) {
- hex = numeric.toTwos(fixedFormat.width).toHexString();
- }
- else {
- hex = numeric.toHexString();
- hex = (0, lib$1.hexZeroPad)(hex, fixedFormat.width / 8);
- }
- var decimal = formatFixed(numeric, fixedFormat.decimals);
- return new FixedNumber(_constructorGuard, hex, decimal, fixedFormat);
- };
- FixedNumber.fromBytes = function (value, format) {
- if (format == null) {
- format = "fixed";
- }
- var fixedFormat = FixedFormat.from(format);
- if ((0, lib$1.arrayify)(value).length > fixedFormat.width / 8) {
- throw new Error("overflow");
- }
- var numeric = bignumber.BigNumber.from(value);
- if (fixedFormat.signed) {
- numeric = numeric.fromTwos(fixedFormat.width);
- }
- var hex = numeric.toTwos((fixedFormat.signed ? 0 : 1) + fixedFormat.width).toHexString();
- var decimal = formatFixed(numeric, fixedFormat.decimals);
- return new FixedNumber(_constructorGuard, hex, decimal, fixedFormat);
- };
- FixedNumber.from = function (value, format) {
- if (typeof (value) === "string") {
- return FixedNumber.fromString(value, format);
- }
- if ((0, lib$1.isBytes)(value)) {
- return FixedNumber.fromBytes(value, format);
- }
- try {
- return FixedNumber.fromValue(value, 0, format);
- }
- catch (error) {
- // Allow NUMERIC_FAULT to bubble up
- if (error.code !== lib.Logger.errors.INVALID_ARGUMENT) {
- throw error;
- }
- }
- return logger.throwArgumentError("invalid FixedNumber value", "value", value);
- };
- FixedNumber.isFixedNumber = function (value) {
- return !!(value && value._isFixedNumber);
- };
- return FixedNumber;
- }());
- exports.FixedNumber = FixedNumber;
- var ONE = FixedNumber.from(1);
- var BUMP = FixedNumber.from("0.5");
- });
- var fixednumber$1 = /*@__PURE__*/getDefaultExportFromCjs(fixednumber);
- var lib$2 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports._base36To16 = exports._base16To36 = exports.parseFixed = exports.FixedNumber = exports.FixedFormat = exports.formatFixed = exports.BigNumber = void 0;
- Object.defineProperty(exports, "BigNumber", { enumerable: true, get: function () { return bignumber.BigNumber; } });
- Object.defineProperty(exports, "formatFixed", { enumerable: true, get: function () { return fixednumber.formatFixed; } });
- Object.defineProperty(exports, "FixedFormat", { enumerable: true, get: function () { return fixednumber.FixedFormat; } });
- Object.defineProperty(exports, "FixedNumber", { enumerable: true, get: function () { return fixednumber.FixedNumber; } });
- Object.defineProperty(exports, "parseFixed", { enumerable: true, get: function () { return fixednumber.parseFixed; } });
- // Internal methods used by address
- var bignumber_2 = bignumber;
- Object.defineProperty(exports, "_base16To36", { enumerable: true, get: function () { return bignumber_2._base16To36; } });
- Object.defineProperty(exports, "_base36To16", { enumerable: true, get: function () { return bignumber_2._base36To16; } });
- });
- var index$2 = /*@__PURE__*/getDefaultExportFromCjs(lib$2);
- var _version$6 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "properties/5.6.0";
- });
- var _version$7 = /*@__PURE__*/getDefaultExportFromCjs(_version$6);
- var lib$3 = createCommonjsModule(function (module, exports) {
- "use strict";
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Description = exports.deepCopy = exports.shallowCopy = exports.checkProperties = exports.resolveProperties = exports.getStatic = exports.defineReadOnly = void 0;
- var logger = new lib.Logger(_version$6.version);
- function defineReadOnly(object, name, value) {
- Object.defineProperty(object, name, {
- enumerable: true,
- value: value,
- writable: false,
- });
- }
- exports.defineReadOnly = defineReadOnly;
- // Crawl up the constructor chain to find a static method
- function getStatic(ctor, key) {
- for (var i = 0; i < 32; i++) {
- if (ctor[key]) {
- return ctor[key];
- }
- if (!ctor.prototype || typeof (ctor.prototype) !== "object") {
- break;
- }
- ctor = Object.getPrototypeOf(ctor.prototype).constructor;
- }
- return null;
- }
- exports.getStatic = getStatic;
- function resolveProperties(object) {
- return __awaiter(this, void 0, void 0, function () {
- var promises, results;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- promises = Object.keys(object).map(function (key) {
- var value = object[key];
- return Promise.resolve(value).then(function (v) { return ({ key: key, value: v }); });
- });
- return [4 /*yield*/, Promise.all(promises)];
- case 1:
- results = _a.sent();
- return [2 /*return*/, results.reduce(function (accum, result) {
- accum[(result.key)] = result.value;
- return accum;
- }, {})];
- }
- });
- });
- }
- exports.resolveProperties = resolveProperties;
- function checkProperties(object, properties) {
- if (!object || typeof (object) !== "object") {
- logger.throwArgumentError("invalid object", "object", object);
- }
- Object.keys(object).forEach(function (key) {
- if (!properties[key]) {
- logger.throwArgumentError("invalid object key - " + key, "transaction:" + key, object);
- }
- });
- }
- exports.checkProperties = checkProperties;
- function shallowCopy(object) {
- var result = {};
- for (var key in object) {
- result[key] = object[key];
- }
- return result;
- }
- exports.shallowCopy = shallowCopy;
- var opaque = { bigint: true, boolean: true, "function": true, number: true, string: true };
- function _isFrozen(object) {
- // Opaque objects are not mutable, so safe to copy by assignment
- if (object === undefined || object === null || opaque[typeof (object)]) {
- return true;
- }
- if (Array.isArray(object) || typeof (object) === "object") {
- if (!Object.isFrozen(object)) {
- return false;
- }
- var keys = Object.keys(object);
- for (var i = 0; i < keys.length; i++) {
- var value = null;
- try {
- value = object[keys[i]];
- }
- catch (error) {
- // If accessing a value triggers an error, it is a getter
- // designed to do so (e.g. Result) and is therefore "frozen"
- continue;
- }
- if (!_isFrozen(value)) {
- return false;
- }
- }
- return true;
- }
- return logger.throwArgumentError("Cannot deepCopy " + typeof (object), "object", object);
- }
- // Returns a new copy of object, such that no properties may be replaced.
- // New properties may be added only to objects.
- function _deepCopy(object) {
- if (_isFrozen(object)) {
- return object;
- }
- // Arrays are mutable, so we need to create a copy
- if (Array.isArray(object)) {
- return Object.freeze(object.map(function (item) { return deepCopy(item); }));
- }
- if (typeof (object) === "object") {
- var result = {};
- for (var key in object) {
- var value = object[key];
- if (value === undefined) {
- continue;
- }
- defineReadOnly(result, key, deepCopy(value));
- }
- return result;
- }
- return logger.throwArgumentError("Cannot deepCopy " + typeof (object), "object", object);
- }
- function deepCopy(object) {
- return _deepCopy(object);
- }
- exports.deepCopy = deepCopy;
- var Description = /** @class */ (function () {
- function Description(info) {
- for (var key in info) {
- this[key] = deepCopy(info[key]);
- }
- }
- return Description;
- }());
- exports.Description = Description;
- });
- var index$3 = /*@__PURE__*/getDefaultExportFromCjs(lib$3);
- var _version$8 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "abi/5.6.0";
- });
- var _version$9 = /*@__PURE__*/getDefaultExportFromCjs(_version$8);
- var fragments = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ErrorFragment = exports.FunctionFragment = exports.ConstructorFragment = exports.EventFragment = exports.Fragment = exports.ParamType = exports.FormatTypes = void 0;
- var logger = new lib.Logger(_version$8.version);
- ;
- var _constructorGuard = {};
- var ModifiersBytes = { calldata: true, memory: true, storage: true };
- var ModifiersNest = { calldata: true, memory: true };
- function checkModifier(type, name) {
- if (type === "bytes" || type === "string") {
- if (ModifiersBytes[name]) {
- return true;
- }
- }
- else if (type === "address") {
- if (name === "payable") {
- return true;
- }
- }
- else if (type.indexOf("[") >= 0 || type === "tuple") {
- if (ModifiersNest[name]) {
- return true;
- }
- }
- if (ModifiersBytes[name] || name === "payable") {
- logger.throwArgumentError("invalid modifier", "name", name);
- }
- return false;
- }
- // @TODO: Make sure that children of an indexed tuple are marked with a null indexed
- function parseParamType(param, allowIndexed) {
- var originalParam = param;
- function throwError(i) {
- logger.throwArgumentError("unexpected character at position " + i, "param", param);
- }
- param = param.replace(/\s/g, " ");
- function newNode(parent) {
- var node = { type: "", name: "", parent: parent, state: { allowType: true } };
- if (allowIndexed) {
- node.indexed = false;
- }
- return node;
- }
- var parent = { type: "", name: "", state: { allowType: true } };
- var node = parent;
- for (var i = 0; i < param.length; i++) {
- var c = param[i];
- switch (c) {
- case "(":
- if (node.state.allowType && node.type === "") {
- node.type = "tuple";
- }
- else if (!node.state.allowParams) {
- throwError(i);
- }
- node.state.allowType = false;
- node.type = verifyType(node.type);
- node.components = [newNode(node)];
- node = node.components[0];
- break;
- case ")":
- delete node.state;
- if (node.name === "indexed") {
- if (!allowIndexed) {
- throwError(i);
- }
- node.indexed = true;
- node.name = "";
- }
- if (checkModifier(node.type, node.name)) {
- node.name = "";
- }
- node.type = verifyType(node.type);
- var child = node;
- node = node.parent;
- if (!node) {
- throwError(i);
- }
- delete child.parent;
- node.state.allowParams = false;
- node.state.allowName = true;
- node.state.allowArray = true;
- break;
- case ",":
- delete node.state;
- if (node.name === "indexed") {
- if (!allowIndexed) {
- throwError(i);
- }
- node.indexed = true;
- node.name = "";
- }
- if (checkModifier(node.type, node.name)) {
- node.name = "";
- }
- node.type = verifyType(node.type);
- var sibling = newNode(node.parent);
- //{ type: "", name: "", parent: node.parent, state: { allowType: true } };
- node.parent.components.push(sibling);
- delete node.parent;
- node = sibling;
- break;
- // Hit a space...
- case " ":
- // If reading type, the type is done and may read a param or name
- if (node.state.allowType) {
- if (node.type !== "") {
- node.type = verifyType(node.type);
- delete node.state.allowType;
- node.state.allowName = true;
- node.state.allowParams = true;
- }
- }
- // If reading name, the name is done
- if (node.state.allowName) {
- if (node.name !== "") {
- if (node.name === "indexed") {
- if (!allowIndexed) {
- throwError(i);
- }
- if (node.indexed) {
- throwError(i);
- }
- node.indexed = true;
- node.name = "";
- }
- else if (checkModifier(node.type, node.name)) {
- node.name = "";
- }
- else {
- node.state.allowName = false;
- }
- }
- }
- break;
- case "[":
- if (!node.state.allowArray) {
- throwError(i);
- }
- node.type += c;
- node.state.allowArray = false;
- node.state.allowName = false;
- node.state.readArray = true;
- break;
- case "]":
- if (!node.state.readArray) {
- throwError(i);
- }
- node.type += c;
- node.state.readArray = false;
- node.state.allowArray = true;
- node.state.allowName = true;
- break;
- default:
- if (node.state.allowType) {
- node.type += c;
- node.state.allowParams = true;
- node.state.allowArray = true;
- }
- else if (node.state.allowName) {
- node.name += c;
- delete node.state.allowArray;
- }
- else if (node.state.readArray) {
- node.type += c;
- }
- else {
- throwError(i);
- }
- }
- }
- if (node.parent) {
- logger.throwArgumentError("unexpected eof", "param", param);
- }
- delete parent.state;
- if (node.name === "indexed") {
- if (!allowIndexed) {
- throwError(originalParam.length - 7);
- }
- if (node.indexed) {
- throwError(originalParam.length - 7);
- }
- node.indexed = true;
- node.name = "";
- }
- else if (checkModifier(node.type, node.name)) {
- node.name = "";
- }
- parent.type = verifyType(parent.type);
- return parent;
- }
- function populate(object, params) {
- for (var key in params) {
- (0, lib$3.defineReadOnly)(object, key, params[key]);
- }
- }
- exports.FormatTypes = Object.freeze({
- // Bare formatting, as is needed for computing a sighash of an event or function
- sighash: "sighash",
- // Human-Readable with Minimal spacing and without names (compact human-readable)
- minimal: "minimal",
- // Human-Readable with nice spacing, including all names
- full: "full",
- // JSON-format a la Solidity
- json: "json"
- });
- var paramTypeArray = new RegExp(/^(.*)\[([0-9]*)\]$/);
- var ParamType = /** @class */ (function () {
- function ParamType(constructorGuard, params) {
- if (constructorGuard !== _constructorGuard) {
- logger.throwError("use fromString", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "new ParamType()"
- });
- }
- populate(this, params);
- var match = this.type.match(paramTypeArray);
- if (match) {
- populate(this, {
- arrayLength: parseInt(match[2] || "-1"),
- arrayChildren: ParamType.fromObject({
- type: match[1],
- components: this.components
- }),
- baseType: "array"
- });
- }
- else {
- populate(this, {
- arrayLength: null,
- arrayChildren: null,
- baseType: ((this.components != null) ? "tuple" : this.type)
- });
- }
- this._isParamType = true;
- Object.freeze(this);
- }
- // Format the parameter fragment
- // - sighash: "(uint256,address)"
- // - minimal: "tuple(uint256,address) indexed"
- // - full: "tuple(uint256 foo, address bar) indexed baz"
- ParamType.prototype.format = function (format) {
- if (!format) {
- format = exports.FormatTypes.sighash;
- }
- if (!exports.FormatTypes[format]) {
- logger.throwArgumentError("invalid format type", "format", format);
- }
- if (format === exports.FormatTypes.json) {
- var result_1 = {
- type: ((this.baseType === "tuple") ? "tuple" : this.type),
- name: (this.name || undefined)
- };
- if (typeof (this.indexed) === "boolean") {
- result_1.indexed = this.indexed;
- }
- if (this.components) {
- result_1.components = this.components.map(function (comp) { return JSON.parse(comp.format(format)); });
- }
- return JSON.stringify(result_1);
- }
- var result = "";
- // Array
- if (this.baseType === "array") {
- result += this.arrayChildren.format(format);
- result += "[" + (this.arrayLength < 0 ? "" : String(this.arrayLength)) + "]";
- }
- else {
- if (this.baseType === "tuple") {
- if (format !== exports.FormatTypes.sighash) {
- result += this.type;
- }
- result += "(" + this.components.map(function (comp) { return comp.format(format); }).join((format === exports.FormatTypes.full) ? ", " : ",") + ")";
- }
- else {
- result += this.type;
- }
- }
- if (format !== exports.FormatTypes.sighash) {
- if (this.indexed === true) {
- result += " indexed";
- }
- if (format === exports.FormatTypes.full && this.name) {
- result += " " + this.name;
- }
- }
- return result;
- };
- ParamType.from = function (value, allowIndexed) {
- if (typeof (value) === "string") {
- return ParamType.fromString(value, allowIndexed);
- }
- return ParamType.fromObject(value);
- };
- ParamType.fromObject = function (value) {
- if (ParamType.isParamType(value)) {
- return value;
- }
- return new ParamType(_constructorGuard, {
- name: (value.name || null),
- type: verifyType(value.type),
- indexed: ((value.indexed == null) ? null : !!value.indexed),
- components: (value.components ? value.components.map(ParamType.fromObject) : null)
- });
- };
- ParamType.fromString = function (value, allowIndexed) {
- function ParamTypify(node) {
- return ParamType.fromObject({
- name: node.name,
- type: node.type,
- indexed: node.indexed,
- components: node.components
- });
- }
- return ParamTypify(parseParamType(value, !!allowIndexed));
- };
- ParamType.isParamType = function (value) {
- return !!(value != null && value._isParamType);
- };
- return ParamType;
- }());
- exports.ParamType = ParamType;
- ;
- function parseParams(value, allowIndex) {
- return splitNesting(value).map(function (param) { return ParamType.fromString(param, allowIndex); });
- }
- var Fragment = /** @class */ (function () {
- function Fragment(constructorGuard, params) {
- if (constructorGuard !== _constructorGuard) {
- logger.throwError("use a static from method", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "new Fragment()"
- });
- }
- populate(this, params);
- this._isFragment = true;
- Object.freeze(this);
- }
- Fragment.from = function (value) {
- if (Fragment.isFragment(value)) {
- return value;
- }
- if (typeof (value) === "string") {
- return Fragment.fromString(value);
- }
- return Fragment.fromObject(value);
- };
- Fragment.fromObject = function (value) {
- if (Fragment.isFragment(value)) {
- return value;
- }
- switch (value.type) {
- case "function":
- return FunctionFragment.fromObject(value);
- case "event":
- return EventFragment.fromObject(value);
- case "constructor":
- return ConstructorFragment.fromObject(value);
- case "error":
- return ErrorFragment.fromObject(value);
- case "fallback":
- case "receive":
- // @TODO: Something? Maybe return a FunctionFragment? A custom DefaultFunctionFragment?
- return null;
- }
- return logger.throwArgumentError("invalid fragment object", "value", value);
- };
- Fragment.fromString = function (value) {
- // Make sure the "returns" is surrounded by a space and all whitespace is exactly one space
- value = value.replace(/\s/g, " ");
- value = value.replace(/\(/g, " (").replace(/\)/g, ") ").replace(/\s+/g, " ");
- value = value.trim();
- if (value.split(" ")[0] === "event") {
- return EventFragment.fromString(value.substring(5).trim());
- }
- else if (value.split(" ")[0] === "function") {
- return FunctionFragment.fromString(value.substring(8).trim());
- }
- else if (value.split("(")[0].trim() === "constructor") {
- return ConstructorFragment.fromString(value.trim());
- }
- else if (value.split(" ")[0] === "error") {
- return ErrorFragment.fromString(value.substring(5).trim());
- }
- return logger.throwArgumentError("unsupported fragment", "value", value);
- };
- Fragment.isFragment = function (value) {
- return !!(value && value._isFragment);
- };
- return Fragment;
- }());
- exports.Fragment = Fragment;
- var EventFragment = /** @class */ (function (_super) {
- __extends(EventFragment, _super);
- function EventFragment() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- EventFragment.prototype.format = function (format) {
- if (!format) {
- format = exports.FormatTypes.sighash;
- }
- if (!exports.FormatTypes[format]) {
- logger.throwArgumentError("invalid format type", "format", format);
- }
- if (format === exports.FormatTypes.json) {
- return JSON.stringify({
- type: "event",
- anonymous: this.anonymous,
- name: this.name,
- inputs: this.inputs.map(function (input) { return JSON.parse(input.format(format)); })
- });
- }
- var result = "";
- if (format !== exports.FormatTypes.sighash) {
- result += "event ";
- }
- result += this.name + "(" + this.inputs.map(function (input) { return input.format(format); }).join((format === exports.FormatTypes.full) ? ", " : ",") + ") ";
- if (format !== exports.FormatTypes.sighash) {
- if (this.anonymous) {
- result += "anonymous ";
- }
- }
- return result.trim();
- };
- EventFragment.from = function (value) {
- if (typeof (value) === "string") {
- return EventFragment.fromString(value);
- }
- return EventFragment.fromObject(value);
- };
- EventFragment.fromObject = function (value) {
- if (EventFragment.isEventFragment(value)) {
- return value;
- }
- if (value.type !== "event") {
- logger.throwArgumentError("invalid event object", "value", value);
- }
- var params = {
- name: verifyIdentifier(value.name),
- anonymous: value.anonymous,
- inputs: (value.inputs ? value.inputs.map(ParamType.fromObject) : []),
- type: "event"
- };
- return new EventFragment(_constructorGuard, params);
- };
- EventFragment.fromString = function (value) {
- var match = value.match(regexParen);
- if (!match) {
- logger.throwArgumentError("invalid event string", "value", value);
- }
- var anonymous = false;
- match[3].split(" ").forEach(function (modifier) {
- switch (modifier.trim()) {
- case "anonymous":
- anonymous = true;
- break;
- case "":
- break;
- default:
- logger.warn("unknown modifier: " + modifier);
- }
- });
- return EventFragment.fromObject({
- name: match[1].trim(),
- anonymous: anonymous,
- inputs: parseParams(match[2], true),
- type: "event"
- });
- };
- EventFragment.isEventFragment = function (value) {
- return (value && value._isFragment && value.type === "event");
- };
- return EventFragment;
- }(Fragment));
- exports.EventFragment = EventFragment;
- function parseGas(value, params) {
- params.gas = null;
- var comps = value.split("@");
- if (comps.length !== 1) {
- if (comps.length > 2) {
- logger.throwArgumentError("invalid human-readable ABI signature", "value", value);
- }
- if (!comps[1].match(/^[0-9]+$/)) {
- logger.throwArgumentError("invalid human-readable ABI signature gas", "value", value);
- }
- params.gas = lib$2.BigNumber.from(comps[1]);
- return comps[0];
- }
- return value;
- }
- function parseModifiers(value, params) {
- params.constant = false;
- params.payable = false;
- params.stateMutability = "nonpayable";
- value.split(" ").forEach(function (modifier) {
- switch (modifier.trim()) {
- case "constant":
- params.constant = true;
- break;
- case "payable":
- params.payable = true;
- params.stateMutability = "payable";
- break;
- case "nonpayable":
- params.payable = false;
- params.stateMutability = "nonpayable";
- break;
- case "pure":
- params.constant = true;
- params.stateMutability = "pure";
- break;
- case "view":
- params.constant = true;
- params.stateMutability = "view";
- break;
- case "external":
- case "public":
- case "":
- break;
- default:
- console.log("unknown modifier: " + modifier);
- }
- });
- }
- function verifyState(value) {
- var result = {
- constant: false,
- payable: true,
- stateMutability: "payable"
- };
- if (value.stateMutability != null) {
- result.stateMutability = value.stateMutability;
- // Set (and check things are consistent) the constant property
- result.constant = (result.stateMutability === "view" || result.stateMutability === "pure");
- if (value.constant != null) {
- if ((!!value.constant) !== result.constant) {
- logger.throwArgumentError("cannot have constant function with mutability " + result.stateMutability, "value", value);
- }
- }
- // Set (and check things are consistent) the payable property
- result.payable = (result.stateMutability === "payable");
- if (value.payable != null) {
- if ((!!value.payable) !== result.payable) {
- logger.throwArgumentError("cannot have payable function with mutability " + result.stateMutability, "value", value);
- }
- }
- }
- else if (value.payable != null) {
- result.payable = !!value.payable;
- // If payable we can assume non-constant; otherwise we can't assume
- if (value.constant == null && !result.payable && value.type !== "constructor") {
- logger.throwArgumentError("unable to determine stateMutability", "value", value);
- }
- result.constant = !!value.constant;
- if (result.constant) {
- result.stateMutability = "view";
- }
- else {
- result.stateMutability = (result.payable ? "payable" : "nonpayable");
- }
- if (result.payable && result.constant) {
- logger.throwArgumentError("cannot have constant payable function", "value", value);
- }
- }
- else if (value.constant != null) {
- result.constant = !!value.constant;
- result.payable = !result.constant;
- result.stateMutability = (result.constant ? "view" : "payable");
- }
- else if (value.type !== "constructor") {
- logger.throwArgumentError("unable to determine stateMutability", "value", value);
- }
- return result;
- }
- var ConstructorFragment = /** @class */ (function (_super) {
- __extends(ConstructorFragment, _super);
- function ConstructorFragment() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- ConstructorFragment.prototype.format = function (format) {
- if (!format) {
- format = exports.FormatTypes.sighash;
- }
- if (!exports.FormatTypes[format]) {
- logger.throwArgumentError("invalid format type", "format", format);
- }
- if (format === exports.FormatTypes.json) {
- return JSON.stringify({
- type: "constructor",
- stateMutability: ((this.stateMutability !== "nonpayable") ? this.stateMutability : undefined),
- payable: this.payable,
- gas: (this.gas ? this.gas.toNumber() : undefined),
- inputs: this.inputs.map(function (input) { return JSON.parse(input.format(format)); })
- });
- }
- if (format === exports.FormatTypes.sighash) {
- logger.throwError("cannot format a constructor for sighash", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "format(sighash)"
- });
- }
- var result = "constructor(" + this.inputs.map(function (input) { return input.format(format); }).join((format === exports.FormatTypes.full) ? ", " : ",") + ") ";
- if (this.stateMutability && this.stateMutability !== "nonpayable") {
- result += this.stateMutability + " ";
- }
- return result.trim();
- };
- ConstructorFragment.from = function (value) {
- if (typeof (value) === "string") {
- return ConstructorFragment.fromString(value);
- }
- return ConstructorFragment.fromObject(value);
- };
- ConstructorFragment.fromObject = function (value) {
- if (ConstructorFragment.isConstructorFragment(value)) {
- return value;
- }
- if (value.type !== "constructor") {
- logger.throwArgumentError("invalid constructor object", "value", value);
- }
- var state = verifyState(value);
- if (state.constant) {
- logger.throwArgumentError("constructor cannot be constant", "value", value);
- }
- var params = {
- name: null,
- type: value.type,
- inputs: (value.inputs ? value.inputs.map(ParamType.fromObject) : []),
- payable: state.payable,
- stateMutability: state.stateMutability,
- gas: (value.gas ? lib$2.BigNumber.from(value.gas) : null)
- };
- return new ConstructorFragment(_constructorGuard, params);
- };
- ConstructorFragment.fromString = function (value) {
- var params = { type: "constructor" };
- value = parseGas(value, params);
- var parens = value.match(regexParen);
- if (!parens || parens[1].trim() !== "constructor") {
- logger.throwArgumentError("invalid constructor string", "value", value);
- }
- params.inputs = parseParams(parens[2].trim(), false);
- parseModifiers(parens[3].trim(), params);
- return ConstructorFragment.fromObject(params);
- };
- ConstructorFragment.isConstructorFragment = function (value) {
- return (value && value._isFragment && value.type === "constructor");
- };
- return ConstructorFragment;
- }(Fragment));
- exports.ConstructorFragment = ConstructorFragment;
- var FunctionFragment = /** @class */ (function (_super) {
- __extends(FunctionFragment, _super);
- function FunctionFragment() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- FunctionFragment.prototype.format = function (format) {
- if (!format) {
- format = exports.FormatTypes.sighash;
- }
- if (!exports.FormatTypes[format]) {
- logger.throwArgumentError("invalid format type", "format", format);
- }
- if (format === exports.FormatTypes.json) {
- return JSON.stringify({
- type: "function",
- name: this.name,
- constant: this.constant,
- stateMutability: ((this.stateMutability !== "nonpayable") ? this.stateMutability : undefined),
- payable: this.payable,
- gas: (this.gas ? this.gas.toNumber() : undefined),
- inputs: this.inputs.map(function (input) { return JSON.parse(input.format(format)); }),
- outputs: this.outputs.map(function (output) { return JSON.parse(output.format(format)); }),
- });
- }
- var result = "";
- if (format !== exports.FormatTypes.sighash) {
- result += "function ";
- }
- result += this.name + "(" + this.inputs.map(function (input) { return input.format(format); }).join((format === exports.FormatTypes.full) ? ", " : ",") + ") ";
- if (format !== exports.FormatTypes.sighash) {
- if (this.stateMutability) {
- if (this.stateMutability !== "nonpayable") {
- result += (this.stateMutability + " ");
- }
- }
- else if (this.constant) {
- result += "view ";
- }
- if (this.outputs && this.outputs.length) {
- result += "returns (" + this.outputs.map(function (output) { return output.format(format); }).join(", ") + ") ";
- }
- if (this.gas != null) {
- result += "@" + this.gas.toString() + " ";
- }
- }
- return result.trim();
- };
- FunctionFragment.from = function (value) {
- if (typeof (value) === "string") {
- return FunctionFragment.fromString(value);
- }
- return FunctionFragment.fromObject(value);
- };
- FunctionFragment.fromObject = function (value) {
- if (FunctionFragment.isFunctionFragment(value)) {
- return value;
- }
- if (value.type !== "function") {
- logger.throwArgumentError("invalid function object", "value", value);
- }
- var state = verifyState(value);
- var params = {
- type: value.type,
- name: verifyIdentifier(value.name),
- constant: state.constant,
- inputs: (value.inputs ? value.inputs.map(ParamType.fromObject) : []),
- outputs: (value.outputs ? value.outputs.map(ParamType.fromObject) : []),
- payable: state.payable,
- stateMutability: state.stateMutability,
- gas: (value.gas ? lib$2.BigNumber.from(value.gas) : null)
- };
- return new FunctionFragment(_constructorGuard, params);
- };
- FunctionFragment.fromString = function (value) {
- var params = { type: "function" };
- value = parseGas(value, params);
- var comps = value.split(" returns ");
- if (comps.length > 2) {
- logger.throwArgumentError("invalid function string", "value", value);
- }
- var parens = comps[0].match(regexParen);
- if (!parens) {
- logger.throwArgumentError("invalid function signature", "value", value);
- }
- params.name = parens[1].trim();
- if (params.name) {
- verifyIdentifier(params.name);
- }
- params.inputs = parseParams(parens[2], false);
- parseModifiers(parens[3].trim(), params);
- // We have outputs
- if (comps.length > 1) {
- var returns = comps[1].match(regexParen);
- if (returns[1].trim() != "" || returns[3].trim() != "") {
- logger.throwArgumentError("unexpected tokens", "value", value);
- }
- params.outputs = parseParams(returns[2], false);
- }
- else {
- params.outputs = [];
- }
- return FunctionFragment.fromObject(params);
- };
- FunctionFragment.isFunctionFragment = function (value) {
- return (value && value._isFragment && value.type === "function");
- };
- return FunctionFragment;
- }(ConstructorFragment));
- exports.FunctionFragment = FunctionFragment;
- //export class StructFragment extends Fragment {
- //}
- function checkForbidden(fragment) {
- var sig = fragment.format();
- if (sig === "Error(string)" || sig === "Panic(uint256)") {
- logger.throwArgumentError("cannot specify user defined " + sig + " error", "fragment", fragment);
- }
- return fragment;
- }
- var ErrorFragment = /** @class */ (function (_super) {
- __extends(ErrorFragment, _super);
- function ErrorFragment() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- ErrorFragment.prototype.format = function (format) {
- if (!format) {
- format = exports.FormatTypes.sighash;
- }
- if (!exports.FormatTypes[format]) {
- logger.throwArgumentError("invalid format type", "format", format);
- }
- if (format === exports.FormatTypes.json) {
- return JSON.stringify({
- type: "error",
- name: this.name,
- inputs: this.inputs.map(function (input) { return JSON.parse(input.format(format)); }),
- });
- }
- var result = "";
- if (format !== exports.FormatTypes.sighash) {
- result += "error ";
- }
- result += this.name + "(" + this.inputs.map(function (input) { return input.format(format); }).join((format === exports.FormatTypes.full) ? ", " : ",") + ") ";
- return result.trim();
- };
- ErrorFragment.from = function (value) {
- if (typeof (value) === "string") {
- return ErrorFragment.fromString(value);
- }
- return ErrorFragment.fromObject(value);
- };
- ErrorFragment.fromObject = function (value) {
- if (ErrorFragment.isErrorFragment(value)) {
- return value;
- }
- if (value.type !== "error") {
- logger.throwArgumentError("invalid error object", "value", value);
- }
- var params = {
- type: value.type,
- name: verifyIdentifier(value.name),
- inputs: (value.inputs ? value.inputs.map(ParamType.fromObject) : [])
- };
- return checkForbidden(new ErrorFragment(_constructorGuard, params));
- };
- ErrorFragment.fromString = function (value) {
- var params = { type: "error" };
- var parens = value.match(regexParen);
- if (!parens) {
- logger.throwArgumentError("invalid error signature", "value", value);
- }
- params.name = parens[1].trim();
- if (params.name) {
- verifyIdentifier(params.name);
- }
- params.inputs = parseParams(parens[2], false);
- return checkForbidden(ErrorFragment.fromObject(params));
- };
- ErrorFragment.isErrorFragment = function (value) {
- return (value && value._isFragment && value.type === "error");
- };
- return ErrorFragment;
- }(Fragment));
- exports.ErrorFragment = ErrorFragment;
- function verifyType(type) {
- // These need to be transformed to their full description
- if (type.match(/^uint($|[^1-9])/)) {
- type = "uint256" + type.substring(4);
- }
- else if (type.match(/^int($|[^1-9])/)) {
- type = "int256" + type.substring(3);
- }
- // @TODO: more verification
- return type;
- }
- // See: https://github.com/ethereum/solidity/blob/1f8f1a3db93a548d0555e3e14cfc55a10e25b60e/docs/grammar/SolidityLexer.g4#L234
- var regexIdentifier = new RegExp("^[a-zA-Z$_][a-zA-Z0-9$_]*$");
- function verifyIdentifier(value) {
- if (!value || !value.match(regexIdentifier)) {
- logger.throwArgumentError("invalid identifier \"" + value + "\"", "value", value);
- }
- return value;
- }
- var regexParen = new RegExp("^([^)(]*)\\((.*)\\)([^)(]*)$");
- function splitNesting(value) {
- value = value.trim();
- var result = [];
- var accum = "";
- var depth = 0;
- for (var offset = 0; offset < value.length; offset++) {
- var c = value[offset];
- if (c === "," && depth === 0) {
- result.push(accum);
- accum = "";
- }
- else {
- accum += c;
- if (c === "(") {
- depth++;
- }
- else if (c === ")") {
- depth--;
- if (depth === -1) {
- logger.throwArgumentError("unbalanced parenthesis", "value", value);
- }
- }
- }
- }
- if (accum) {
- result.push(accum);
- }
- return result;
- }
- });
- var fragments$1 = /*@__PURE__*/getDefaultExportFromCjs(fragments);
- var abstractCoder = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Reader = exports.Writer = exports.Coder = exports.checkResultErrors = void 0;
- var logger = new lib.Logger(_version$8.version);
- function checkResultErrors(result) {
- // Find the first error (if any)
- var errors = [];
- var checkErrors = function (path, object) {
- if (!Array.isArray(object)) {
- return;
- }
- for (var key in object) {
- var childPath = path.slice();
- childPath.push(key);
- try {
- checkErrors(childPath, object[key]);
- }
- catch (error) {
- errors.push({ path: childPath, error: error });
- }
- }
- };
- checkErrors([], result);
- return errors;
- }
- exports.checkResultErrors = checkResultErrors;
- var Coder = /** @class */ (function () {
- function Coder(name, type, localName, dynamic) {
- // @TODO: defineReadOnly these
- this.name = name;
- this.type = type;
- this.localName = localName;
- this.dynamic = dynamic;
- }
- Coder.prototype._throwError = function (message, value) {
- logger.throwArgumentError(message, this.localName, value);
- };
- return Coder;
- }());
- exports.Coder = Coder;
- var Writer = /** @class */ (function () {
- function Writer(wordSize) {
- (0, lib$3.defineReadOnly)(this, "wordSize", wordSize || 32);
- this._data = [];
- this._dataLength = 0;
- this._padding = new Uint8Array(wordSize);
- }
- Object.defineProperty(Writer.prototype, "data", {
- get: function () {
- return (0, lib$1.hexConcat)(this._data);
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(Writer.prototype, "length", {
- get: function () { return this._dataLength; },
- enumerable: false,
- configurable: true
- });
- Writer.prototype._writeData = function (data) {
- this._data.push(data);
- this._dataLength += data.length;
- return data.length;
- };
- Writer.prototype.appendWriter = function (writer) {
- return this._writeData((0, lib$1.concat)(writer._data));
- };
- // Arrayish items; padded on the right to wordSize
- Writer.prototype.writeBytes = function (value) {
- var bytes = (0, lib$1.arrayify)(value);
- var paddingOffset = bytes.length % this.wordSize;
- if (paddingOffset) {
- bytes = (0, lib$1.concat)([bytes, this._padding.slice(paddingOffset)]);
- }
- return this._writeData(bytes);
- };
- Writer.prototype._getValue = function (value) {
- var bytes = (0, lib$1.arrayify)(lib$2.BigNumber.from(value));
- if (bytes.length > this.wordSize) {
- logger.throwError("value out-of-bounds", lib.Logger.errors.BUFFER_OVERRUN, {
- length: this.wordSize,
- offset: bytes.length
- });
- }
- if (bytes.length % this.wordSize) {
- bytes = (0, lib$1.concat)([this._padding.slice(bytes.length % this.wordSize), bytes]);
- }
- return bytes;
- };
- // BigNumberish items; padded on the left to wordSize
- Writer.prototype.writeValue = function (value) {
- return this._writeData(this._getValue(value));
- };
- Writer.prototype.writeUpdatableValue = function () {
- var _this = this;
- var offset = this._data.length;
- this._data.push(this._padding);
- this._dataLength += this.wordSize;
- return function (value) {
- _this._data[offset] = _this._getValue(value);
- };
- };
- return Writer;
- }());
- exports.Writer = Writer;
- var Reader = /** @class */ (function () {
- function Reader(data, wordSize, coerceFunc, allowLoose) {
- (0, lib$3.defineReadOnly)(this, "_data", (0, lib$1.arrayify)(data));
- (0, lib$3.defineReadOnly)(this, "wordSize", wordSize || 32);
- (0, lib$3.defineReadOnly)(this, "_coerceFunc", coerceFunc);
- (0, lib$3.defineReadOnly)(this, "allowLoose", allowLoose);
- this._offset = 0;
- }
- Object.defineProperty(Reader.prototype, "data", {
- get: function () { return (0, lib$1.hexlify)(this._data); },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(Reader.prototype, "consumed", {
- get: function () { return this._offset; },
- enumerable: false,
- configurable: true
- });
- // The default Coerce function
- Reader.coerce = function (name, value) {
- var match = name.match("^u?int([0-9]+)$");
- if (match && parseInt(match[1]) <= 48) {
- value = value.toNumber();
- }
- return value;
- };
- Reader.prototype.coerce = function (name, value) {
- if (this._coerceFunc) {
- return this._coerceFunc(name, value);
- }
- return Reader.coerce(name, value);
- };
- Reader.prototype._peekBytes = function (offset, length, loose) {
- var alignedLength = Math.ceil(length / this.wordSize) * this.wordSize;
- if (this._offset + alignedLength > this._data.length) {
- if (this.allowLoose && loose && this._offset + length <= this._data.length) {
- alignedLength = length;
- }
- else {
- logger.throwError("data out-of-bounds", lib.Logger.errors.BUFFER_OVERRUN, {
- length: this._data.length,
- offset: this._offset + alignedLength
- });
- }
- }
- return this._data.slice(this._offset, this._offset + alignedLength);
- };
- Reader.prototype.subReader = function (offset) {
- return new Reader(this._data.slice(this._offset + offset), this.wordSize, this._coerceFunc, this.allowLoose);
- };
- Reader.prototype.readBytes = function (length, loose) {
- var bytes = this._peekBytes(0, length, !!loose);
- this._offset += bytes.length;
- // @TODO: Make sure the length..end bytes are all 0?
- return bytes.slice(0, length);
- };
- Reader.prototype.readValue = function () {
- return lib$2.BigNumber.from(this.readBytes(this.wordSize));
- };
- return Reader;
- }());
- exports.Reader = Reader;
- });
- var abstractCoder$1 = /*@__PURE__*/getDefaultExportFromCjs(abstractCoder);
- var sha3 = createCommonjsModule(function (module) {
- /**
- * [js-sha3]{@link https://github.com/emn178/js-sha3}
- *
- * @version 0.8.0
- * @author Chen, Yi-Cyuan [emn178@gmail.com]
- * @copyright Chen, Yi-Cyuan 2015-2018
- * @license MIT
- */
- /*jslint bitwise: true */
- (function () {
- 'use strict';
- var INPUT_ERROR = 'input is invalid type';
- var FINALIZE_ERROR = 'finalize already called';
- var WINDOW = typeof window === 'object';
- var root = WINDOW ? window : {};
- if (root.JS_SHA3_NO_WINDOW) {
- WINDOW = false;
- }
- var WEB_WORKER = !WINDOW && typeof self === 'object';
- var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;
- if (NODE_JS) {
- root = commonjsGlobal;
- } else if (WEB_WORKER) {
- root = self;
- }
- var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && 'object' === 'object' && module.exports;
- var AMD = typeof undefined === 'function' && undefined.amd;
- var ARRAY_BUFFER = !root.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined';
- var HEX_CHARS = '0123456789abcdef'.split('');
- var SHAKE_PADDING = [31, 7936, 2031616, 520093696];
- var CSHAKE_PADDING = [4, 1024, 262144, 67108864];
- var KECCAK_PADDING = [1, 256, 65536, 16777216];
- var PADDING = [6, 1536, 393216, 100663296];
- var SHIFT = [0, 8, 16, 24];
- var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649,
- 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0,
- 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771,
- 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648,
- 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648];
- var BITS = [224, 256, 384, 512];
- var SHAKE_BITS = [128, 256];
- var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array', 'digest'];
- var CSHAKE_BYTEPAD = {
- '128': 168,
- '256': 136
- };
- if (root.JS_SHA3_NO_NODE_JS || !Array.isArray) {
- Array.isArray = function (obj) {
- return Object.prototype.toString.call(obj) === '[object Array]';
- };
- }
- if (ARRAY_BUFFER && (root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) {
- ArrayBuffer.isView = function (obj) {
- return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer;
- };
- }
- var createOutputMethod = function (bits, padding, outputType) {
- return function (message) {
- return new Keccak(bits, padding, bits).update(message)[outputType]();
- };
- };
- var createShakeOutputMethod = function (bits, padding, outputType) {
- return function (message, outputBits) {
- return new Keccak(bits, padding, outputBits).update(message)[outputType]();
- };
- };
- var createCshakeOutputMethod = function (bits, padding, outputType) {
- return function (message, outputBits, n, s) {
- return methods['cshake' + bits].update(message, outputBits, n, s)[outputType]();
- };
- };
- var createKmacOutputMethod = function (bits, padding, outputType) {
- return function (key, message, outputBits, s) {
- return methods['kmac' + bits].update(key, message, outputBits, s)[outputType]();
- };
- };
- var createOutputMethods = function (method, createMethod, bits, padding) {
- for (var i = 0; i < OUTPUT_TYPES.length; ++i) {
- var type = OUTPUT_TYPES[i];
- method[type] = createMethod(bits, padding, type);
- }
- return method;
- };
- var createMethod = function (bits, padding) {
- var method = createOutputMethod(bits, padding, 'hex');
- method.create = function () {
- return new Keccak(bits, padding, bits);
- };
- method.update = function (message) {
- return method.create().update(message);
- };
- return createOutputMethods(method, createOutputMethod, bits, padding);
- };
- var createShakeMethod = function (bits, padding) {
- var method = createShakeOutputMethod(bits, padding, 'hex');
- method.create = function (outputBits) {
- return new Keccak(bits, padding, outputBits);
- };
- method.update = function (message, outputBits) {
- return method.create(outputBits).update(message);
- };
- return createOutputMethods(method, createShakeOutputMethod, bits, padding);
- };
- var createCshakeMethod = function (bits, padding) {
- var w = CSHAKE_BYTEPAD[bits];
- var method = createCshakeOutputMethod(bits, padding, 'hex');
- method.create = function (outputBits, n, s) {
- if (!n && !s) {
- return methods['shake' + bits].create(outputBits);
- } else {
- return new Keccak(bits, padding, outputBits).bytepad([n, s], w);
- }
- };
- method.update = function (message, outputBits, n, s) {
- return method.create(outputBits, n, s).update(message);
- };
- return createOutputMethods(method, createCshakeOutputMethod, bits, padding);
- };
- var createKmacMethod = function (bits, padding) {
- var w = CSHAKE_BYTEPAD[bits];
- var method = createKmacOutputMethod(bits, padding, 'hex');
- method.create = function (key, outputBits, s) {
- return new Kmac(bits, padding, outputBits).bytepad(['KMAC', s], w).bytepad([key], w);
- };
- method.update = function (key, message, outputBits, s) {
- return method.create(key, outputBits, s).update(message);
- };
- return createOutputMethods(method, createKmacOutputMethod, bits, padding);
- };
- var algorithms = [
- { name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod },
- { name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod },
- { name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod },
- { name: 'cshake', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createCshakeMethod },
- { name: 'kmac', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createKmacMethod }
- ];
- var methods = {}, methodNames = [];
- for (var i = 0; i < algorithms.length; ++i) {
- var algorithm = algorithms[i];
- var bits = algorithm.bits;
- for (var j = 0; j < bits.length; ++j) {
- var methodName = algorithm.name + '_' + bits[j];
- methodNames.push(methodName);
- methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding);
- if (algorithm.name !== 'sha3') {
- var newMethodName = algorithm.name + bits[j];
- methodNames.push(newMethodName);
- methods[newMethodName] = methods[methodName];
- }
- }
- }
- function Keccak(bits, padding, outputBits) {
- this.blocks = [];
- this.s = [];
- this.padding = padding;
- this.outputBits = outputBits;
- this.reset = true;
- this.finalized = false;
- this.block = 0;
- this.start = 0;
- this.blockCount = (1600 - (bits << 1)) >> 5;
- this.byteCount = this.blockCount << 2;
- this.outputBlocks = outputBits >> 5;
- this.extraBytes = (outputBits & 31) >> 3;
- for (var i = 0; i < 50; ++i) {
- this.s[i] = 0;
- }
- }
- Keccak.prototype.update = function (message) {
- if (this.finalized) {
- throw new Error(FINALIZE_ERROR);
- }
- var notString, type = typeof message;
- if (type !== 'string') {
- if (type === 'object') {
- if (message === null) {
- throw new Error(INPUT_ERROR);
- } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) {
- message = new Uint8Array(message);
- } else if (!Array.isArray(message)) {
- if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) {
- throw new Error(INPUT_ERROR);
- }
- }
- } else {
- throw new Error(INPUT_ERROR);
- }
- notString = true;
- }
- var blocks = this.blocks, byteCount = this.byteCount, length = message.length,
- blockCount = this.blockCount, index = 0, s = this.s, i, code;
- while (index < length) {
- if (this.reset) {
- this.reset = false;
- blocks[0] = this.block;
- for (i = 1; i < blockCount + 1; ++i) {
- blocks[i] = 0;
- }
- }
- if (notString) {
- for (i = this.start; index < length && i < byteCount; ++index) {
- blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];
- }
- } else {
- for (i = this.start; index < length && i < byteCount; ++index) {
- code = message.charCodeAt(index);
- if (code < 0x80) {
- blocks[i >> 2] |= code << SHIFT[i++ & 3];
- } else if (code < 0x800) {
- blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3];
- blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
- } else if (code < 0xd800 || code >= 0xe000) {
- blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3];
- blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];
- blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
- } else {
- code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff));
- blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3];
- blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3];
- blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];
- blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
- }
- }
- }
- this.lastByteIndex = i;
- if (i >= byteCount) {
- this.start = i - byteCount;
- this.block = blocks[blockCount];
- for (i = 0; i < blockCount; ++i) {
- s[i] ^= blocks[i];
- }
- f(s);
- this.reset = true;
- } else {
- this.start = i;
- }
- }
- return this;
- };
- Keccak.prototype.encode = function (x, right) {
- var o = x & 255, n = 1;
- var bytes = [o];
- x = x >> 8;
- o = x & 255;
- while (o > 0) {
- bytes.unshift(o);
- x = x >> 8;
- o = x & 255;
- ++n;
- }
- if (right) {
- bytes.push(n);
- } else {
- bytes.unshift(n);
- }
- this.update(bytes);
- return bytes.length;
- };
- Keccak.prototype.encodeString = function (str) {
- var notString, type = typeof str;
- if (type !== 'string') {
- if (type === 'object') {
- if (str === null) {
- throw new Error(INPUT_ERROR);
- } else if (ARRAY_BUFFER && str.constructor === ArrayBuffer) {
- str = new Uint8Array(str);
- } else if (!Array.isArray(str)) {
- if (!ARRAY_BUFFER || !ArrayBuffer.isView(str)) {
- throw new Error(INPUT_ERROR);
- }
- }
- } else {
- throw new Error(INPUT_ERROR);
- }
- notString = true;
- }
- var bytes = 0, length = str.length;
- if (notString) {
- bytes = length;
- } else {
- for (var i = 0; i < str.length; ++i) {
- var code = str.charCodeAt(i);
- if (code < 0x80) {
- bytes += 1;
- } else if (code < 0x800) {
- bytes += 2;
- } else if (code < 0xd800 || code >= 0xe000) {
- bytes += 3;
- } else {
- code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++i) & 0x3ff));
- bytes += 4;
- }
- }
- }
- bytes += this.encode(bytes * 8);
- this.update(str);
- return bytes;
- };
- Keccak.prototype.bytepad = function (strs, w) {
- var bytes = this.encode(w);
- for (var i = 0; i < strs.length; ++i) {
- bytes += this.encodeString(strs[i]);
- }
- var paddingBytes = w - bytes % w;
- var zeros = [];
- zeros.length = paddingBytes;
- this.update(zeros);
- return this;
- };
- Keccak.prototype.finalize = function () {
- if (this.finalized) {
- return;
- }
- this.finalized = true;
- var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s;
- blocks[i >> 2] |= this.padding[i & 3];
- if (this.lastByteIndex === this.byteCount) {
- blocks[0] = blocks[blockCount];
- for (i = 1; i < blockCount + 1; ++i) {
- blocks[i] = 0;
- }
- }
- blocks[blockCount - 1] |= 0x80000000;
- for (i = 0; i < blockCount; ++i) {
- s[i] ^= blocks[i];
- }
- f(s);
- };
- Keccak.prototype.toString = Keccak.prototype.hex = function () {
- this.finalize();
- var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,
- extraBytes = this.extraBytes, i = 0, j = 0;
- var hex = '', block;
- while (j < outputBlocks) {
- for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
- block = s[i];
- hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] +
- HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] +
- HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] +
- HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F];
- }
- if (j % blockCount === 0) {
- f(s);
- i = 0;
- }
- }
- if (extraBytes) {
- block = s[i];
- hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F];
- if (extraBytes > 1) {
- hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F];
- }
- if (extraBytes > 2) {
- hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F];
- }
- }
- return hex;
- };
- Keccak.prototype.arrayBuffer = function () {
- this.finalize();
- var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,
- extraBytes = this.extraBytes, i = 0, j = 0;
- var bytes = this.outputBits >> 3;
- var buffer;
- if (extraBytes) {
- buffer = new ArrayBuffer((outputBlocks + 1) << 2);
- } else {
- buffer = new ArrayBuffer(bytes);
- }
- var array = new Uint32Array(buffer);
- while (j < outputBlocks) {
- for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
- array[j] = s[i];
- }
- if (j % blockCount === 0) {
- f(s);
- }
- }
- if (extraBytes) {
- array[i] = s[i];
- buffer = buffer.slice(0, bytes);
- }
- return buffer;
- };
- Keccak.prototype.buffer = Keccak.prototype.arrayBuffer;
- Keccak.prototype.digest = Keccak.prototype.array = function () {
- this.finalize();
- var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,
- extraBytes = this.extraBytes, i = 0, j = 0;
- var array = [], offset, block;
- while (j < outputBlocks) {
- for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
- offset = j << 2;
- block = s[i];
- array[offset] = block & 0xFF;
- array[offset + 1] = (block >> 8) & 0xFF;
- array[offset + 2] = (block >> 16) & 0xFF;
- array[offset + 3] = (block >> 24) & 0xFF;
- }
- if (j % blockCount === 0) {
- f(s);
- }
- }
- if (extraBytes) {
- offset = j << 2;
- block = s[i];
- array[offset] = block & 0xFF;
- if (extraBytes > 1) {
- array[offset + 1] = (block >> 8) & 0xFF;
- }
- if (extraBytes > 2) {
- array[offset + 2] = (block >> 16) & 0xFF;
- }
- }
- return array;
- };
- function Kmac(bits, padding, outputBits) {
- Keccak.call(this, bits, padding, outputBits);
- }
- Kmac.prototype = new Keccak();
- Kmac.prototype.finalize = function () {
- this.encode(this.outputBits, true);
- return Keccak.prototype.finalize.call(this);
- };
- var f = function (s) {
- var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9,
- b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17,
- b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33,
- b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49;
- for (n = 0; n < 48; n += 2) {
- c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40];
- c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41];
- c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42];
- c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43];
- c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44];
- c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45];
- c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46];
- c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47];
- c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48];
- c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49];
- h = c8 ^ ((c2 << 1) | (c3 >>> 31));
- l = c9 ^ ((c3 << 1) | (c2 >>> 31));
- s[0] ^= h;
- s[1] ^= l;
- s[10] ^= h;
- s[11] ^= l;
- s[20] ^= h;
- s[21] ^= l;
- s[30] ^= h;
- s[31] ^= l;
- s[40] ^= h;
- s[41] ^= l;
- h = c0 ^ ((c4 << 1) | (c5 >>> 31));
- l = c1 ^ ((c5 << 1) | (c4 >>> 31));
- s[2] ^= h;
- s[3] ^= l;
- s[12] ^= h;
- s[13] ^= l;
- s[22] ^= h;
- s[23] ^= l;
- s[32] ^= h;
- s[33] ^= l;
- s[42] ^= h;
- s[43] ^= l;
- h = c2 ^ ((c6 << 1) | (c7 >>> 31));
- l = c3 ^ ((c7 << 1) | (c6 >>> 31));
- s[4] ^= h;
- s[5] ^= l;
- s[14] ^= h;
- s[15] ^= l;
- s[24] ^= h;
- s[25] ^= l;
- s[34] ^= h;
- s[35] ^= l;
- s[44] ^= h;
- s[45] ^= l;
- h = c4 ^ ((c8 << 1) | (c9 >>> 31));
- l = c5 ^ ((c9 << 1) | (c8 >>> 31));
- s[6] ^= h;
- s[7] ^= l;
- s[16] ^= h;
- s[17] ^= l;
- s[26] ^= h;
- s[27] ^= l;
- s[36] ^= h;
- s[37] ^= l;
- s[46] ^= h;
- s[47] ^= l;
- h = c6 ^ ((c0 << 1) | (c1 >>> 31));
- l = c7 ^ ((c1 << 1) | (c0 >>> 31));
- s[8] ^= h;
- s[9] ^= l;
- s[18] ^= h;
- s[19] ^= l;
- s[28] ^= h;
- s[29] ^= l;
- s[38] ^= h;
- s[39] ^= l;
- s[48] ^= h;
- s[49] ^= l;
- b0 = s[0];
- b1 = s[1];
- b32 = (s[11] << 4) | (s[10] >>> 28);
- b33 = (s[10] << 4) | (s[11] >>> 28);
- b14 = (s[20] << 3) | (s[21] >>> 29);
- b15 = (s[21] << 3) | (s[20] >>> 29);
- b46 = (s[31] << 9) | (s[30] >>> 23);
- b47 = (s[30] << 9) | (s[31] >>> 23);
- b28 = (s[40] << 18) | (s[41] >>> 14);
- b29 = (s[41] << 18) | (s[40] >>> 14);
- b20 = (s[2] << 1) | (s[3] >>> 31);
- b21 = (s[3] << 1) | (s[2] >>> 31);
- b2 = (s[13] << 12) | (s[12] >>> 20);
- b3 = (s[12] << 12) | (s[13] >>> 20);
- b34 = (s[22] << 10) | (s[23] >>> 22);
- b35 = (s[23] << 10) | (s[22] >>> 22);
- b16 = (s[33] << 13) | (s[32] >>> 19);
- b17 = (s[32] << 13) | (s[33] >>> 19);
- b48 = (s[42] << 2) | (s[43] >>> 30);
- b49 = (s[43] << 2) | (s[42] >>> 30);
- b40 = (s[5] << 30) | (s[4] >>> 2);
- b41 = (s[4] << 30) | (s[5] >>> 2);
- b22 = (s[14] << 6) | (s[15] >>> 26);
- b23 = (s[15] << 6) | (s[14] >>> 26);
- b4 = (s[25] << 11) | (s[24] >>> 21);
- b5 = (s[24] << 11) | (s[25] >>> 21);
- b36 = (s[34] << 15) | (s[35] >>> 17);
- b37 = (s[35] << 15) | (s[34] >>> 17);
- b18 = (s[45] << 29) | (s[44] >>> 3);
- b19 = (s[44] << 29) | (s[45] >>> 3);
- b10 = (s[6] << 28) | (s[7] >>> 4);
- b11 = (s[7] << 28) | (s[6] >>> 4);
- b42 = (s[17] << 23) | (s[16] >>> 9);
- b43 = (s[16] << 23) | (s[17] >>> 9);
- b24 = (s[26] << 25) | (s[27] >>> 7);
- b25 = (s[27] << 25) | (s[26] >>> 7);
- b6 = (s[36] << 21) | (s[37] >>> 11);
- b7 = (s[37] << 21) | (s[36] >>> 11);
- b38 = (s[47] << 24) | (s[46] >>> 8);
- b39 = (s[46] << 24) | (s[47] >>> 8);
- b30 = (s[8] << 27) | (s[9] >>> 5);
- b31 = (s[9] << 27) | (s[8] >>> 5);
- b12 = (s[18] << 20) | (s[19] >>> 12);
- b13 = (s[19] << 20) | (s[18] >>> 12);
- b44 = (s[29] << 7) | (s[28] >>> 25);
- b45 = (s[28] << 7) | (s[29] >>> 25);
- b26 = (s[38] << 8) | (s[39] >>> 24);
- b27 = (s[39] << 8) | (s[38] >>> 24);
- b8 = (s[48] << 14) | (s[49] >>> 18);
- b9 = (s[49] << 14) | (s[48] >>> 18);
- s[0] = b0 ^ (~b2 & b4);
- s[1] = b1 ^ (~b3 & b5);
- s[10] = b10 ^ (~b12 & b14);
- s[11] = b11 ^ (~b13 & b15);
- s[20] = b20 ^ (~b22 & b24);
- s[21] = b21 ^ (~b23 & b25);
- s[30] = b30 ^ (~b32 & b34);
- s[31] = b31 ^ (~b33 & b35);
- s[40] = b40 ^ (~b42 & b44);
- s[41] = b41 ^ (~b43 & b45);
- s[2] = b2 ^ (~b4 & b6);
- s[3] = b3 ^ (~b5 & b7);
- s[12] = b12 ^ (~b14 & b16);
- s[13] = b13 ^ (~b15 & b17);
- s[22] = b22 ^ (~b24 & b26);
- s[23] = b23 ^ (~b25 & b27);
- s[32] = b32 ^ (~b34 & b36);
- s[33] = b33 ^ (~b35 & b37);
- s[42] = b42 ^ (~b44 & b46);
- s[43] = b43 ^ (~b45 & b47);
- s[4] = b4 ^ (~b6 & b8);
- s[5] = b5 ^ (~b7 & b9);
- s[14] = b14 ^ (~b16 & b18);
- s[15] = b15 ^ (~b17 & b19);
- s[24] = b24 ^ (~b26 & b28);
- s[25] = b25 ^ (~b27 & b29);
- s[34] = b34 ^ (~b36 & b38);
- s[35] = b35 ^ (~b37 & b39);
- s[44] = b44 ^ (~b46 & b48);
- s[45] = b45 ^ (~b47 & b49);
- s[6] = b6 ^ (~b8 & b0);
- s[7] = b7 ^ (~b9 & b1);
- s[16] = b16 ^ (~b18 & b10);
- s[17] = b17 ^ (~b19 & b11);
- s[26] = b26 ^ (~b28 & b20);
- s[27] = b27 ^ (~b29 & b21);
- s[36] = b36 ^ (~b38 & b30);
- s[37] = b37 ^ (~b39 & b31);
- s[46] = b46 ^ (~b48 & b40);
- s[47] = b47 ^ (~b49 & b41);
- s[8] = b8 ^ (~b0 & b2);
- s[9] = b9 ^ (~b1 & b3);
- s[18] = b18 ^ (~b10 & b12);
- s[19] = b19 ^ (~b11 & b13);
- s[28] = b28 ^ (~b20 & b22);
- s[29] = b29 ^ (~b21 & b23);
- s[38] = b38 ^ (~b30 & b32);
- s[39] = b39 ^ (~b31 & b33);
- s[48] = b48 ^ (~b40 & b42);
- s[49] = b49 ^ (~b41 & b43);
- s[0] ^= RC[n];
- s[1] ^= RC[n + 1];
- }
- };
- if (COMMON_JS) {
- module.exports = methods;
- } else {
- for (i = 0; i < methodNames.length; ++i) {
- root[methodNames[i]] = methods[methodNames[i]];
- }
- if (AMD) {
- undefined(function () {
- return methods;
- });
- }
- }
- })();
- });
- var lib$4 = createCommonjsModule(function (module, exports) {
- "use strict";
- var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.keccak256 = void 0;
- var js_sha3_1 = __importDefault(sha3);
- function keccak256(data) {
- return '0x' + js_sha3_1.default.keccak_256((0, lib$1.arrayify)(data));
- }
- exports.keccak256 = keccak256;
- });
- var index$4 = /*@__PURE__*/getDefaultExportFromCjs(lib$4);
- var _version$a = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "rlp/5.6.0";
- });
- var _version$b = /*@__PURE__*/getDefaultExportFromCjs(_version$a);
- var lib$5 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.decode = exports.encode = void 0;
- //See: https://github.com/ethereum/wiki/wiki/RLP
- var logger = new lib.Logger(_version$a.version);
- function arrayifyInteger(value) {
- var result = [];
- while (value) {
- result.unshift(value & 0xff);
- value >>= 8;
- }
- return result;
- }
- function unarrayifyInteger(data, offset, length) {
- var result = 0;
- for (var i = 0; i < length; i++) {
- result = (result * 256) + data[offset + i];
- }
- return result;
- }
- function _encode(object) {
- if (Array.isArray(object)) {
- var payload_1 = [];
- object.forEach(function (child) {
- payload_1 = payload_1.concat(_encode(child));
- });
- if (payload_1.length <= 55) {
- payload_1.unshift(0xc0 + payload_1.length);
- return payload_1;
- }
- var length_1 = arrayifyInteger(payload_1.length);
- length_1.unshift(0xf7 + length_1.length);
- return length_1.concat(payload_1);
- }
- if (!(0, lib$1.isBytesLike)(object)) {
- logger.throwArgumentError("RLP object must be BytesLike", "object", object);
- }
- var data = Array.prototype.slice.call((0, lib$1.arrayify)(object));
- if (data.length === 1 && data[0] <= 0x7f) {
- return data;
- }
- else if (data.length <= 55) {
- data.unshift(0x80 + data.length);
- return data;
- }
- var length = arrayifyInteger(data.length);
- length.unshift(0xb7 + length.length);
- return length.concat(data);
- }
- function encode(object) {
- return (0, lib$1.hexlify)(_encode(object));
- }
- exports.encode = encode;
- function _decodeChildren(data, offset, childOffset, length) {
- var result = [];
- while (childOffset < offset + 1 + length) {
- var decoded = _decode(data, childOffset);
- result.push(decoded.result);
- childOffset += decoded.consumed;
- if (childOffset > offset + 1 + length) {
- logger.throwError("child data too short", lib.Logger.errors.BUFFER_OVERRUN, {});
- }
- }
- return { consumed: (1 + length), result: result };
- }
- // returns { consumed: number, result: Object }
- function _decode(data, offset) {
- if (data.length === 0) {
- logger.throwError("data too short", lib.Logger.errors.BUFFER_OVERRUN, {});
- }
- // Array with extra length prefix
- if (data[offset] >= 0xf8) {
- var lengthLength = data[offset] - 0xf7;
- if (offset + 1 + lengthLength > data.length) {
- logger.throwError("data short segment too short", lib.Logger.errors.BUFFER_OVERRUN, {});
- }
- var length_2 = unarrayifyInteger(data, offset + 1, lengthLength);
- if (offset + 1 + lengthLength + length_2 > data.length) {
- logger.throwError("data long segment too short", lib.Logger.errors.BUFFER_OVERRUN, {});
- }
- return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length_2);
- }
- else if (data[offset] >= 0xc0) {
- var length_3 = data[offset] - 0xc0;
- if (offset + 1 + length_3 > data.length) {
- logger.throwError("data array too short", lib.Logger.errors.BUFFER_OVERRUN, {});
- }
- return _decodeChildren(data, offset, offset + 1, length_3);
- }
- else if (data[offset] >= 0xb8) {
- var lengthLength = data[offset] - 0xb7;
- if (offset + 1 + lengthLength > data.length) {
- logger.throwError("data array too short", lib.Logger.errors.BUFFER_OVERRUN, {});
- }
- var length_4 = unarrayifyInteger(data, offset + 1, lengthLength);
- if (offset + 1 + lengthLength + length_4 > data.length) {
- logger.throwError("data array too short", lib.Logger.errors.BUFFER_OVERRUN, {});
- }
- var result = (0, lib$1.hexlify)(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length_4));
- return { consumed: (1 + lengthLength + length_4), result: result };
- }
- else if (data[offset] >= 0x80) {
- var length_5 = data[offset] - 0x80;
- if (offset + 1 + length_5 > data.length) {
- logger.throwError("data too short", lib.Logger.errors.BUFFER_OVERRUN, {});
- }
- var result = (0, lib$1.hexlify)(data.slice(offset + 1, offset + 1 + length_5));
- return { consumed: (1 + length_5), result: result };
- }
- return { consumed: 1, result: (0, lib$1.hexlify)(data[offset]) };
- }
- function decode(data) {
- var bytes = (0, lib$1.arrayify)(data);
- var decoded = _decode(bytes, 0);
- if (decoded.consumed !== bytes.length) {
- logger.throwArgumentError("invalid rlp data", "data", data);
- }
- return decoded.result;
- }
- exports.decode = decode;
- });
- var index$5 = /*@__PURE__*/getDefaultExportFromCjs(lib$5);
- var _version$c = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "address/5.6.0";
- });
- var _version$d = /*@__PURE__*/getDefaultExportFromCjs(_version$c);
- var lib$6 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getCreate2Address = exports.getContractAddress = exports.getIcapAddress = exports.isAddress = exports.getAddress = void 0;
- var logger = new lib.Logger(_version$c.version);
- function getChecksumAddress(address) {
- if (!(0, lib$1.isHexString)(address, 20)) {
- logger.throwArgumentError("invalid address", "address", address);
- }
- address = address.toLowerCase();
- var chars = address.substring(2).split("");
- var expanded = new Uint8Array(40);
- for (var i = 0; i < 40; i++) {
- expanded[i] = chars[i].charCodeAt(0);
- }
- var hashed = (0, lib$1.arrayify)((0, lib$4.keccak256)(expanded));
- for (var i = 0; i < 40; i += 2) {
- if ((hashed[i >> 1] >> 4) >= 8) {
- chars[i] = chars[i].toUpperCase();
- }
- if ((hashed[i >> 1] & 0x0f) >= 8) {
- chars[i + 1] = chars[i + 1].toUpperCase();
- }
- }
- return "0x" + chars.join("");
- }
- // Shims for environments that are missing some required constants and functions
- var MAX_SAFE_INTEGER = 0x1fffffffffffff;
- function log10(x) {
- if (Math.log10) {
- return Math.log10(x);
- }
- return Math.log(x) / Math.LN10;
- }
- // See: https://en.wikipedia.org/wiki/International_Bank_Account_Number
- // Create lookup table
- var ibanLookup = {};
- for (var i = 0; i < 10; i++) {
- ibanLookup[String(i)] = String(i);
- }
- for (var i = 0; i < 26; i++) {
- ibanLookup[String.fromCharCode(65 + i)] = String(10 + i);
- }
- // How many decimal digits can we process? (for 64-bit float, this is 15)
- var safeDigits = Math.floor(log10(MAX_SAFE_INTEGER));
- function ibanChecksum(address) {
- address = address.toUpperCase();
- address = address.substring(4) + address.substring(0, 2) + "00";
- var expanded = address.split("").map(function (c) { return ibanLookup[c]; }).join("");
- // Javascript can handle integers safely up to 15 (decimal) digits
- while (expanded.length >= safeDigits) {
- var block = expanded.substring(0, safeDigits);
- expanded = parseInt(block, 10) % 97 + expanded.substring(block.length);
- }
- var checksum = String(98 - (parseInt(expanded, 10) % 97));
- while (checksum.length < 2) {
- checksum = "0" + checksum;
- }
- return checksum;
- }
- ;
- function getAddress(address) {
- var result = null;
- if (typeof (address) !== "string") {
- logger.throwArgumentError("invalid address", "address", address);
- }
- if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) {
- // Missing the 0x prefix
- if (address.substring(0, 2) !== "0x") {
- address = "0x" + address;
- }
- result = getChecksumAddress(address);
- // It is a checksummed address with a bad checksum
- if (address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) && result !== address) {
- logger.throwArgumentError("bad address checksum", "address", address);
- }
- // Maybe ICAP? (we only support direct mode)
- }
- else if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) {
- // It is an ICAP address with a bad checksum
- if (address.substring(2, 4) !== ibanChecksum(address)) {
- logger.throwArgumentError("bad icap checksum", "address", address);
- }
- result = (0, lib$2._base36To16)(address.substring(4));
- while (result.length < 40) {
- result = "0" + result;
- }
- result = getChecksumAddress("0x" + result);
- }
- else {
- logger.throwArgumentError("invalid address", "address", address);
- }
- return result;
- }
- exports.getAddress = getAddress;
- function isAddress(address) {
- try {
- getAddress(address);
- return true;
- }
- catch (error) { }
- return false;
- }
- exports.isAddress = isAddress;
- function getIcapAddress(address) {
- var base36 = (0, lib$2._base16To36)(getAddress(address).substring(2)).toUpperCase();
- while (base36.length < 30) {
- base36 = "0" + base36;
- }
- return "XE" + ibanChecksum("XE00" + base36) + base36;
- }
- exports.getIcapAddress = getIcapAddress;
- // http://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed
- function getContractAddress(transaction) {
- var from = null;
- try {
- from = getAddress(transaction.from);
- }
- catch (error) {
- logger.throwArgumentError("missing from address", "transaction", transaction);
- }
- var nonce = (0, lib$1.stripZeros)((0, lib$1.arrayify)(lib$2.BigNumber.from(transaction.nonce).toHexString()));
- return getAddress((0, lib$1.hexDataSlice)((0, lib$4.keccak256)((0, lib$5.encode)([from, nonce])), 12));
- }
- exports.getContractAddress = getContractAddress;
- function getCreate2Address(from, salt, initCodeHash) {
- if ((0, lib$1.hexDataLength)(salt) !== 32) {
- logger.throwArgumentError("salt must be 32 bytes", "salt", salt);
- }
- if ((0, lib$1.hexDataLength)(initCodeHash) !== 32) {
- logger.throwArgumentError("initCodeHash must be 32 bytes", "initCodeHash", initCodeHash);
- }
- return getAddress((0, lib$1.hexDataSlice)((0, lib$4.keccak256)((0, lib$1.concat)(["0xff", getAddress(from), salt, initCodeHash])), 12));
- }
- exports.getCreate2Address = getCreate2Address;
- });
- var index$6 = /*@__PURE__*/getDefaultExportFromCjs(lib$6);
- var address = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.AddressCoder = void 0;
- var AddressCoder = /** @class */ (function (_super) {
- __extends(AddressCoder, _super);
- function AddressCoder(localName) {
- return _super.call(this, "address", "address", localName, false) || this;
- }
- AddressCoder.prototype.defaultValue = function () {
- return "0x0000000000000000000000000000000000000000";
- };
- AddressCoder.prototype.encode = function (writer, value) {
- try {
- value = (0, lib$6.getAddress)(value);
- }
- catch (error) {
- this._throwError(error.message, value);
- }
- return writer.writeValue(value);
- };
- AddressCoder.prototype.decode = function (reader) {
- return (0, lib$6.getAddress)((0, lib$1.hexZeroPad)(reader.readValue().toHexString(), 20));
- };
- return AddressCoder;
- }(abstractCoder.Coder));
- exports.AddressCoder = AddressCoder;
- });
- var address$1 = /*@__PURE__*/getDefaultExportFromCjs(address);
- var anonymous = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.AnonymousCoder = void 0;
- // Clones the functionality of an existing Coder, but without a localName
- var AnonymousCoder = /** @class */ (function (_super) {
- __extends(AnonymousCoder, _super);
- function AnonymousCoder(coder) {
- var _this = _super.call(this, coder.name, coder.type, undefined, coder.dynamic) || this;
- _this.coder = coder;
- return _this;
- }
- AnonymousCoder.prototype.defaultValue = function () {
- return this.coder.defaultValue();
- };
- AnonymousCoder.prototype.encode = function (writer, value) {
- return this.coder.encode(writer, value);
- };
- AnonymousCoder.prototype.decode = function (reader) {
- return this.coder.decode(reader);
- };
- return AnonymousCoder;
- }(abstractCoder.Coder));
- exports.AnonymousCoder = AnonymousCoder;
- });
- var anonymous$1 = /*@__PURE__*/getDefaultExportFromCjs(anonymous);
- var array = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ArrayCoder = exports.unpack = exports.pack = void 0;
- var logger = new lib.Logger(_version$8.version);
- function pack(writer, coders, values) {
- var arrayValues = null;
- if (Array.isArray(values)) {
- arrayValues = values;
- }
- else if (values && typeof (values) === "object") {
- var unique_1 = {};
- arrayValues = coders.map(function (coder) {
- var name = coder.localName;
- if (!name) {
- logger.throwError("cannot encode object for signature with missing names", lib.Logger.errors.INVALID_ARGUMENT, {
- argument: "values",
- coder: coder,
- value: values
- });
- }
- if (unique_1[name]) {
- logger.throwError("cannot encode object for signature with duplicate names", lib.Logger.errors.INVALID_ARGUMENT, {
- argument: "values",
- coder: coder,
- value: values
- });
- }
- unique_1[name] = true;
- return values[name];
- });
- }
- else {
- logger.throwArgumentError("invalid tuple value", "tuple", values);
- }
- if (coders.length !== arrayValues.length) {
- logger.throwArgumentError("types/value length mismatch", "tuple", values);
- }
- var staticWriter = new abstractCoder.Writer(writer.wordSize);
- var dynamicWriter = new abstractCoder.Writer(writer.wordSize);
- var updateFuncs = [];
- coders.forEach(function (coder, index) {
- var value = arrayValues[index];
- if (coder.dynamic) {
- // Get current dynamic offset (for the future pointer)
- var dynamicOffset_1 = dynamicWriter.length;
- // Encode the dynamic value into the dynamicWriter
- coder.encode(dynamicWriter, value);
- // Prepare to populate the correct offset once we are done
- var updateFunc_1 = staticWriter.writeUpdatableValue();
- updateFuncs.push(function (baseOffset) {
- updateFunc_1(baseOffset + dynamicOffset_1);
- });
- }
- else {
- coder.encode(staticWriter, value);
- }
- });
- // Backfill all the dynamic offsets, now that we know the static length
- updateFuncs.forEach(function (func) { func(staticWriter.length); });
- var length = writer.appendWriter(staticWriter);
- length += writer.appendWriter(dynamicWriter);
- return length;
- }
- exports.pack = pack;
- function unpack(reader, coders) {
- var values = [];
- // A reader anchored to this base
- var baseReader = reader.subReader(0);
- coders.forEach(function (coder) {
- var value = null;
- if (coder.dynamic) {
- var offset = reader.readValue();
- var offsetReader = baseReader.subReader(offset.toNumber());
- try {
- value = coder.decode(offsetReader);
- }
- catch (error) {
- // Cannot recover from this
- if (error.code === lib.Logger.errors.BUFFER_OVERRUN) {
- throw error;
- }
- value = error;
- value.baseType = coder.name;
- value.name = coder.localName;
- value.type = coder.type;
- }
- }
- else {
- try {
- value = coder.decode(reader);
- }
- catch (error) {
- // Cannot recover from this
- if (error.code === lib.Logger.errors.BUFFER_OVERRUN) {
- throw error;
- }
- value = error;
- value.baseType = coder.name;
- value.name = coder.localName;
- value.type = coder.type;
- }
- }
- if (value != undefined) {
- values.push(value);
- }
- });
- // We only output named properties for uniquely named coders
- var uniqueNames = coders.reduce(function (accum, coder) {
- var name = coder.localName;
- if (name) {
- if (!accum[name]) {
- accum[name] = 0;
- }
- accum[name]++;
- }
- return accum;
- }, {});
- // Add any named parameters (i.e. tuples)
- coders.forEach(function (coder, index) {
- var name = coder.localName;
- if (!name || uniqueNames[name] !== 1) {
- return;
- }
- if (name === "length") {
- name = "_length";
- }
- if (values[name] != null) {
- return;
- }
- var value = values[index];
- if (value instanceof Error) {
- Object.defineProperty(values, name, {
- enumerable: true,
- get: function () { throw value; }
- });
- }
- else {
- values[name] = value;
- }
- });
- var _loop_1 = function (i) {
- var value = values[i];
- if (value instanceof Error) {
- Object.defineProperty(values, i, {
- enumerable: true,
- get: function () { throw value; }
- });
- }
- };
- for (var i = 0; i < values.length; i++) {
- _loop_1(i);
- }
- return Object.freeze(values);
- }
- exports.unpack = unpack;
- var ArrayCoder = /** @class */ (function (_super) {
- __extends(ArrayCoder, _super);
- function ArrayCoder(coder, length, localName) {
- var _this = this;
- var type = (coder.type + "[" + (length >= 0 ? length : "") + "]");
- var dynamic = (length === -1 || coder.dynamic);
- _this = _super.call(this, "array", type, localName, dynamic) || this;
- _this.coder = coder;
- _this.length = length;
- return _this;
- }
- ArrayCoder.prototype.defaultValue = function () {
- // Verifies the child coder is valid (even if the array is dynamic or 0-length)
- var defaultChild = this.coder.defaultValue();
- var result = [];
- for (var i = 0; i < this.length; i++) {
- result.push(defaultChild);
- }
- return result;
- };
- ArrayCoder.prototype.encode = function (writer, value) {
- if (!Array.isArray(value)) {
- this._throwError("expected array value", value);
- }
- var count = this.length;
- if (count === -1) {
- count = value.length;
- writer.writeValue(value.length);
- }
- logger.checkArgumentCount(value.length, count, "coder array" + (this.localName ? (" " + this.localName) : ""));
- var coders = [];
- for (var i = 0; i < value.length; i++) {
- coders.push(this.coder);
- }
- return pack(writer, coders, value);
- };
- ArrayCoder.prototype.decode = function (reader) {
- var count = this.length;
- if (count === -1) {
- count = reader.readValue().toNumber();
- // Check that there is *roughly* enough data to ensure
- // stray random data is not being read as a length. Each
- // slot requires at least 32 bytes for their value (or 32
- // bytes as a link to the data). This could use a much
- // tighter bound, but we are erroring on the side of safety.
- if (count * 32 > reader._data.length) {
- logger.throwError("insufficient data length", lib.Logger.errors.BUFFER_OVERRUN, {
- length: reader._data.length,
- count: count
- });
- }
- }
- var coders = [];
- for (var i = 0; i < count; i++) {
- coders.push(new anonymous.AnonymousCoder(this.coder));
- }
- return reader.coerce(this.name, unpack(reader, coders));
- };
- return ArrayCoder;
- }(abstractCoder.Coder));
- exports.ArrayCoder = ArrayCoder;
- });
- var array$1 = /*@__PURE__*/getDefaultExportFromCjs(array);
- var boolean_1 = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.BooleanCoder = void 0;
- var BooleanCoder = /** @class */ (function (_super) {
- __extends(BooleanCoder, _super);
- function BooleanCoder(localName) {
- return _super.call(this, "bool", "bool", localName, false) || this;
- }
- BooleanCoder.prototype.defaultValue = function () {
- return false;
- };
- BooleanCoder.prototype.encode = function (writer, value) {
- return writer.writeValue(value ? 1 : 0);
- };
- BooleanCoder.prototype.decode = function (reader) {
- return reader.coerce(this.type, !reader.readValue().isZero());
- };
- return BooleanCoder;
- }(abstractCoder.Coder));
- exports.BooleanCoder = BooleanCoder;
- });
- var boolean = /*@__PURE__*/getDefaultExportFromCjs(boolean_1);
- var bytes = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.BytesCoder = exports.DynamicBytesCoder = void 0;
- var DynamicBytesCoder = /** @class */ (function (_super) {
- __extends(DynamicBytesCoder, _super);
- function DynamicBytesCoder(type, localName) {
- return _super.call(this, type, type, localName, true) || this;
- }
- DynamicBytesCoder.prototype.defaultValue = function () {
- return "0x";
- };
- DynamicBytesCoder.prototype.encode = function (writer, value) {
- value = (0, lib$1.arrayify)(value);
- var length = writer.writeValue(value.length);
- length += writer.writeBytes(value);
- return length;
- };
- DynamicBytesCoder.prototype.decode = function (reader) {
- return reader.readBytes(reader.readValue().toNumber(), true);
- };
- return DynamicBytesCoder;
- }(abstractCoder.Coder));
- exports.DynamicBytesCoder = DynamicBytesCoder;
- var BytesCoder = /** @class */ (function (_super) {
- __extends(BytesCoder, _super);
- function BytesCoder(localName) {
- return _super.call(this, "bytes", localName) || this;
- }
- BytesCoder.prototype.decode = function (reader) {
- return reader.coerce(this.name, (0, lib$1.hexlify)(_super.prototype.decode.call(this, reader)));
- };
- return BytesCoder;
- }(DynamicBytesCoder));
- exports.BytesCoder = BytesCoder;
- });
- var bytes$1 = /*@__PURE__*/getDefaultExportFromCjs(bytes);
- var fixedBytes = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.FixedBytesCoder = void 0;
- // @TODO: Merge this with bytes
- var FixedBytesCoder = /** @class */ (function (_super) {
- __extends(FixedBytesCoder, _super);
- function FixedBytesCoder(size, localName) {
- var _this = this;
- var name = "bytes" + String(size);
- _this = _super.call(this, name, name, localName, false) || this;
- _this.size = size;
- return _this;
- }
- FixedBytesCoder.prototype.defaultValue = function () {
- return ("0x0000000000000000000000000000000000000000000000000000000000000000").substring(0, 2 + this.size * 2);
- };
- FixedBytesCoder.prototype.encode = function (writer, value) {
- var data = (0, lib$1.arrayify)(value);
- if (data.length !== this.size) {
- this._throwError("incorrect data length", value);
- }
- return writer.writeBytes(data);
- };
- FixedBytesCoder.prototype.decode = function (reader) {
- return reader.coerce(this.name, (0, lib$1.hexlify)(reader.readBytes(this.size)));
- };
- return FixedBytesCoder;
- }(abstractCoder.Coder));
- exports.FixedBytesCoder = FixedBytesCoder;
- });
- var fixedBytes$1 = /*@__PURE__*/getDefaultExportFromCjs(fixedBytes);
- var _null = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.NullCoder = void 0;
- var NullCoder = /** @class */ (function (_super) {
- __extends(NullCoder, _super);
- function NullCoder(localName) {
- return _super.call(this, "null", "", localName, false) || this;
- }
- NullCoder.prototype.defaultValue = function () {
- return null;
- };
- NullCoder.prototype.encode = function (writer, value) {
- if (value != null) {
- this._throwError("not null", value);
- }
- return writer.writeBytes([]);
- };
- NullCoder.prototype.decode = function (reader) {
- reader.readBytes(0);
- return reader.coerce(this.name, null);
- };
- return NullCoder;
- }(abstractCoder.Coder));
- exports.NullCoder = NullCoder;
- });
- var _null$1 = /*@__PURE__*/getDefaultExportFromCjs(_null);
- var addresses = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.AddressZero = void 0;
- exports.AddressZero = "0x0000000000000000000000000000000000000000";
- });
- var addresses$1 = /*@__PURE__*/getDefaultExportFromCjs(addresses);
- var bignumbers = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.MaxInt256 = exports.MinInt256 = exports.MaxUint256 = exports.WeiPerEther = exports.Two = exports.One = exports.Zero = exports.NegativeOne = void 0;
- var NegativeOne = ( /*#__PURE__*/lib$2.BigNumber.from(-1));
- exports.NegativeOne = NegativeOne;
- var Zero = ( /*#__PURE__*/lib$2.BigNumber.from(0));
- exports.Zero = Zero;
- var One = ( /*#__PURE__*/lib$2.BigNumber.from(1));
- exports.One = One;
- var Two = ( /*#__PURE__*/lib$2.BigNumber.from(2));
- exports.Two = Two;
- var WeiPerEther = ( /*#__PURE__*/lib$2.BigNumber.from("1000000000000000000"));
- exports.WeiPerEther = WeiPerEther;
- var MaxUint256 = ( /*#__PURE__*/lib$2.BigNumber.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"));
- exports.MaxUint256 = MaxUint256;
- var MinInt256 = ( /*#__PURE__*/lib$2.BigNumber.from("-0x8000000000000000000000000000000000000000000000000000000000000000"));
- exports.MinInt256 = MinInt256;
- var MaxInt256 = ( /*#__PURE__*/lib$2.BigNumber.from("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"));
- exports.MaxInt256 = MaxInt256;
- });
- var bignumbers$1 = /*@__PURE__*/getDefaultExportFromCjs(bignumbers);
- var hashes = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.HashZero = void 0;
- exports.HashZero = "0x0000000000000000000000000000000000000000000000000000000000000000";
- });
- var hashes$1 = /*@__PURE__*/getDefaultExportFromCjs(hashes);
- var strings = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.EtherSymbol = void 0;
- // NFKC (composed) // (decomposed)
- exports.EtherSymbol = "\u039e"; // "\uD835\uDF63";
- });
- var strings$1 = /*@__PURE__*/getDefaultExportFromCjs(strings);
- var lib$7 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.EtherSymbol = exports.HashZero = exports.MaxInt256 = exports.MinInt256 = exports.MaxUint256 = exports.WeiPerEther = exports.Two = exports.One = exports.Zero = exports.NegativeOne = exports.AddressZero = void 0;
- Object.defineProperty(exports, "AddressZero", { enumerable: true, get: function () { return addresses.AddressZero; } });
- Object.defineProperty(exports, "NegativeOne", { enumerable: true, get: function () { return bignumbers.NegativeOne; } });
- Object.defineProperty(exports, "Zero", { enumerable: true, get: function () { return bignumbers.Zero; } });
- Object.defineProperty(exports, "One", { enumerable: true, get: function () { return bignumbers.One; } });
- Object.defineProperty(exports, "Two", { enumerable: true, get: function () { return bignumbers.Two; } });
- Object.defineProperty(exports, "WeiPerEther", { enumerable: true, get: function () { return bignumbers.WeiPerEther; } });
- Object.defineProperty(exports, "MaxUint256", { enumerable: true, get: function () { return bignumbers.MaxUint256; } });
- Object.defineProperty(exports, "MinInt256", { enumerable: true, get: function () { return bignumbers.MinInt256; } });
- Object.defineProperty(exports, "MaxInt256", { enumerable: true, get: function () { return bignumbers.MaxInt256; } });
- Object.defineProperty(exports, "HashZero", { enumerable: true, get: function () { return hashes.HashZero; } });
- Object.defineProperty(exports, "EtherSymbol", { enumerable: true, get: function () { return strings.EtherSymbol; } });
- });
- var index$7 = /*@__PURE__*/getDefaultExportFromCjs(lib$7);
- var number = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.NumberCoder = void 0;
- var NumberCoder = /** @class */ (function (_super) {
- __extends(NumberCoder, _super);
- function NumberCoder(size, signed, localName) {
- var _this = this;
- var name = ((signed ? "int" : "uint") + (size * 8));
- _this = _super.call(this, name, name, localName, false) || this;
- _this.size = size;
- _this.signed = signed;
- return _this;
- }
- NumberCoder.prototype.defaultValue = function () {
- return 0;
- };
- NumberCoder.prototype.encode = function (writer, value) {
- var v = lib$2.BigNumber.from(value);
- // Check bounds are safe for encoding
- var maxUintValue = lib$7.MaxUint256.mask(writer.wordSize * 8);
- if (this.signed) {
- var bounds = maxUintValue.mask(this.size * 8 - 1);
- if (v.gt(bounds) || v.lt(bounds.add(lib$7.One).mul(lib$7.NegativeOne))) {
- this._throwError("value out-of-bounds", value);
- }
- }
- else if (v.lt(lib$7.Zero) || v.gt(maxUintValue.mask(this.size * 8))) {
- this._throwError("value out-of-bounds", value);
- }
- v = v.toTwos(this.size * 8).mask(this.size * 8);
- if (this.signed) {
- v = v.fromTwos(this.size * 8).toTwos(8 * writer.wordSize);
- }
- return writer.writeValue(v);
- };
- NumberCoder.prototype.decode = function (reader) {
- var value = reader.readValue().mask(this.size * 8);
- if (this.signed) {
- value = value.fromTwos(this.size * 8);
- }
- return reader.coerce(this.name, value);
- };
- return NumberCoder;
- }(abstractCoder.Coder));
- exports.NumberCoder = NumberCoder;
- });
- var number$1 = /*@__PURE__*/getDefaultExportFromCjs(number);
- var _version$e = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "strings/5.6.0";
- });
- var _version$f = /*@__PURE__*/getDefaultExportFromCjs(_version$e);
- var utf8 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.toUtf8CodePoints = exports.toUtf8String = exports._toUtf8String = exports._toEscapedUtf8String = exports.toUtf8Bytes = exports.Utf8ErrorFuncs = exports.Utf8ErrorReason = exports.UnicodeNormalizationForm = void 0;
- var logger = new lib.Logger(_version$e.version);
- ///////////////////////////////
- var UnicodeNormalizationForm;
- (function (UnicodeNormalizationForm) {
- UnicodeNormalizationForm["current"] = "";
- UnicodeNormalizationForm["NFC"] = "NFC";
- UnicodeNormalizationForm["NFD"] = "NFD";
- UnicodeNormalizationForm["NFKC"] = "NFKC";
- UnicodeNormalizationForm["NFKD"] = "NFKD";
- })(UnicodeNormalizationForm = exports.UnicodeNormalizationForm || (exports.UnicodeNormalizationForm = {}));
- ;
- var Utf8ErrorReason;
- (function (Utf8ErrorReason) {
- // A continuation byte was present where there was nothing to continue
- // - offset = the index the codepoint began in
- Utf8ErrorReason["UNEXPECTED_CONTINUE"] = "unexpected continuation byte";
- // An invalid (non-continuation) byte to start a UTF-8 codepoint was found
- // - offset = the index the codepoint began in
- Utf8ErrorReason["BAD_PREFIX"] = "bad codepoint prefix";
- // The string is too short to process the expected codepoint
- // - offset = the index the codepoint began in
- Utf8ErrorReason["OVERRUN"] = "string overrun";
- // A missing continuation byte was expected but not found
- // - offset = the index the continuation byte was expected at
- Utf8ErrorReason["MISSING_CONTINUE"] = "missing continuation byte";
- // The computed code point is outside the range for UTF-8
- // - offset = start of this codepoint
- // - badCodepoint = the computed codepoint; outside the UTF-8 range
- Utf8ErrorReason["OUT_OF_RANGE"] = "out of UTF-8 range";
- // UTF-8 strings may not contain UTF-16 surrogate pairs
- // - offset = start of this codepoint
- // - badCodepoint = the computed codepoint; inside the UTF-16 surrogate range
- Utf8ErrorReason["UTF16_SURROGATE"] = "UTF-16 surrogate";
- // The string is an overlong representation
- // - offset = start of this codepoint
- // - badCodepoint = the computed codepoint; already bounds checked
- Utf8ErrorReason["OVERLONG"] = "overlong representation";
- })(Utf8ErrorReason = exports.Utf8ErrorReason || (exports.Utf8ErrorReason = {}));
- ;
- function errorFunc(reason, offset, bytes, output, badCodepoint) {
- return logger.throwArgumentError("invalid codepoint at offset " + offset + "; " + reason, "bytes", bytes);
- }
- function ignoreFunc(reason, offset, bytes, output, badCodepoint) {
- // If there is an invalid prefix (including stray continuation), skip any additional continuation bytes
- if (reason === Utf8ErrorReason.BAD_PREFIX || reason === Utf8ErrorReason.UNEXPECTED_CONTINUE) {
- var i = 0;
- for (var o = offset + 1; o < bytes.length; o++) {
- if (bytes[o] >> 6 !== 0x02) {
- break;
- }
- i++;
- }
- return i;
- }
- // This byte runs us past the end of the string, so just jump to the end
- // (but the first byte was read already read and therefore skipped)
- if (reason === Utf8ErrorReason.OVERRUN) {
- return bytes.length - offset - 1;
- }
- // Nothing to skip
- return 0;
- }
- function replaceFunc(reason, offset, bytes, output, badCodepoint) {
- // Overlong representations are otherwise "valid" code points; just non-deistingtished
- if (reason === Utf8ErrorReason.OVERLONG) {
- output.push(badCodepoint);
- return 0;
- }
- // Put the replacement character into the output
- output.push(0xfffd);
- // Otherwise, process as if ignoring errors
- return ignoreFunc(reason, offset, bytes, output, badCodepoint);
- }
- // Common error handing strategies
- exports.Utf8ErrorFuncs = Object.freeze({
- error: errorFunc,
- ignore: ignoreFunc,
- replace: replaceFunc
- });
- // http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499
- function getUtf8CodePoints(bytes, onError) {
- if (onError == null) {
- onError = exports.Utf8ErrorFuncs.error;
- }
- bytes = (0, lib$1.arrayify)(bytes);
- var result = [];
- var i = 0;
- // Invalid bytes are ignored
- while (i < bytes.length) {
- var c = bytes[i++];
- // 0xxx xxxx
- if (c >> 7 === 0) {
- result.push(c);
- continue;
- }
- // Multibyte; how many bytes left for this character?
- var extraLength = null;
- var overlongMask = null;
- // 110x xxxx 10xx xxxx
- if ((c & 0xe0) === 0xc0) {
- extraLength = 1;
- overlongMask = 0x7f;
- // 1110 xxxx 10xx xxxx 10xx xxxx
- }
- else if ((c & 0xf0) === 0xe0) {
- extraLength = 2;
- overlongMask = 0x7ff;
- // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx
- }
- else if ((c & 0xf8) === 0xf0) {
- extraLength = 3;
- overlongMask = 0xffff;
- }
- else {
- if ((c & 0xc0) === 0x80) {
- i += onError(Utf8ErrorReason.UNEXPECTED_CONTINUE, i - 1, bytes, result);
- }
- else {
- i += onError(Utf8ErrorReason.BAD_PREFIX, i - 1, bytes, result);
- }
- continue;
- }
- // Do we have enough bytes in our data?
- if (i - 1 + extraLength >= bytes.length) {
- i += onError(Utf8ErrorReason.OVERRUN, i - 1, bytes, result);
- continue;
- }
- // Remove the length prefix from the char
- var res = c & ((1 << (8 - extraLength - 1)) - 1);
- for (var j = 0; j < extraLength; j++) {
- var nextChar = bytes[i];
- // Invalid continuation byte
- if ((nextChar & 0xc0) != 0x80) {
- i += onError(Utf8ErrorReason.MISSING_CONTINUE, i, bytes, result);
- res = null;
- break;
- }
- ;
- res = (res << 6) | (nextChar & 0x3f);
- i++;
- }
- // See above loop for invalid continuation byte
- if (res === null) {
- continue;
- }
- // Maximum code point
- if (res > 0x10ffff) {
- i += onError(Utf8ErrorReason.OUT_OF_RANGE, i - 1 - extraLength, bytes, result, res);
- continue;
- }
- // Reserved for UTF-16 surrogate halves
- if (res >= 0xd800 && res <= 0xdfff) {
- i += onError(Utf8ErrorReason.UTF16_SURROGATE, i - 1 - extraLength, bytes, result, res);
- continue;
- }
- // Check for overlong sequences (more bytes than needed)
- if (res <= overlongMask) {
- i += onError(Utf8ErrorReason.OVERLONG, i - 1 - extraLength, bytes, result, res);
- continue;
- }
- result.push(res);
- }
- return result;
- }
- // http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array
- function toUtf8Bytes(str, form) {
- if (form === void 0) { form = UnicodeNormalizationForm.current; }
- if (form != UnicodeNormalizationForm.current) {
- logger.checkNormalize();
- str = str.normalize(form);
- }
- var result = [];
- for (var i = 0; i < str.length; i++) {
- var c = str.charCodeAt(i);
- if (c < 0x80) {
- result.push(c);
- }
- else if (c < 0x800) {
- result.push((c >> 6) | 0xc0);
- result.push((c & 0x3f) | 0x80);
- }
- else if ((c & 0xfc00) == 0xd800) {
- i++;
- var c2 = str.charCodeAt(i);
- if (i >= str.length || (c2 & 0xfc00) !== 0xdc00) {
- throw new Error("invalid utf-8 string");
- }
- // Surrogate Pair
- var pair = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff);
- result.push((pair >> 18) | 0xf0);
- result.push(((pair >> 12) & 0x3f) | 0x80);
- result.push(((pair >> 6) & 0x3f) | 0x80);
- result.push((pair & 0x3f) | 0x80);
- }
- else {
- result.push((c >> 12) | 0xe0);
- result.push(((c >> 6) & 0x3f) | 0x80);
- result.push((c & 0x3f) | 0x80);
- }
- }
- return (0, lib$1.arrayify)(result);
- }
- exports.toUtf8Bytes = toUtf8Bytes;
- ;
- function escapeChar(value) {
- var hex = ("0000" + value.toString(16));
- return "\\u" + hex.substring(hex.length - 4);
- }
- function _toEscapedUtf8String(bytes, onError) {
- return '"' + getUtf8CodePoints(bytes, onError).map(function (codePoint) {
- if (codePoint < 256) {
- switch (codePoint) {
- case 8: return "\\b";
- case 9: return "\\t";
- case 10: return "\\n";
- case 13: return "\\r";
- case 34: return "\\\"";
- case 92: return "\\\\";
- }
- if (codePoint >= 32 && codePoint < 127) {
- return String.fromCharCode(codePoint);
- }
- }
- if (codePoint <= 0xffff) {
- return escapeChar(codePoint);
- }
- codePoint -= 0x10000;
- return escapeChar(((codePoint >> 10) & 0x3ff) + 0xd800) + escapeChar((codePoint & 0x3ff) + 0xdc00);
- }).join("") + '"';
- }
- exports._toEscapedUtf8String = _toEscapedUtf8String;
- function _toUtf8String(codePoints) {
- return codePoints.map(function (codePoint) {
- if (codePoint <= 0xffff) {
- return String.fromCharCode(codePoint);
- }
- codePoint -= 0x10000;
- return String.fromCharCode((((codePoint >> 10) & 0x3ff) + 0xd800), ((codePoint & 0x3ff) + 0xdc00));
- }).join("");
- }
- exports._toUtf8String = _toUtf8String;
- function toUtf8String(bytes, onError) {
- return _toUtf8String(getUtf8CodePoints(bytes, onError));
- }
- exports.toUtf8String = toUtf8String;
- function toUtf8CodePoints(str, form) {
- if (form === void 0) { form = UnicodeNormalizationForm.current; }
- return getUtf8CodePoints(toUtf8Bytes(str, form));
- }
- exports.toUtf8CodePoints = toUtf8CodePoints;
- });
- var utf8$1 = /*@__PURE__*/getDefaultExportFromCjs(utf8);
- var bytes32 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.parseBytes32String = exports.formatBytes32String = void 0;
- function formatBytes32String(text) {
- // Get the bytes
- var bytes = (0, utf8.toUtf8Bytes)(text);
- // Check we have room for null-termination
- if (bytes.length > 31) {
- throw new Error("bytes32 string must be less than 32 bytes");
- }
- // Zero-pad (implicitly null-terminates)
- return (0, lib$1.hexlify)((0, lib$1.concat)([bytes, lib$7.HashZero]).slice(0, 32));
- }
- exports.formatBytes32String = formatBytes32String;
- function parseBytes32String(bytes) {
- var data = (0, lib$1.arrayify)(bytes);
- // Must be 32 bytes with a null-termination
- if (data.length !== 32) {
- throw new Error("invalid bytes32 - not 32 bytes long");
- }
- if (data[31] !== 0) {
- throw new Error("invalid bytes32 string - no null terminator");
- }
- // Find the null termination
- var length = 31;
- while (data[length - 1] === 0) {
- length--;
- }
- // Determine the string value
- return (0, utf8.toUtf8String)(data.slice(0, length));
- }
- exports.parseBytes32String = parseBytes32String;
- });
- var bytes32$1 = /*@__PURE__*/getDefaultExportFromCjs(bytes32);
- var idna = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.nameprep = exports._nameprepTableC = exports._nameprepTableB2 = exports._nameprepTableA1 = void 0;
- function bytes2(data) {
- if ((data.length % 4) !== 0) {
- throw new Error("bad data");
- }
- var result = [];
- for (var i = 0; i < data.length; i += 4) {
- result.push(parseInt(data.substring(i, i + 4), 16));
- }
- return result;
- }
- function createTable(data, func) {
- if (!func) {
- func = function (value) { return [parseInt(value, 16)]; };
- }
- var lo = 0;
- var result = {};
- data.split(",").forEach(function (pair) {
- var comps = pair.split(":");
- lo += parseInt(comps[0], 16);
- result[lo] = func(comps[1]);
- });
- return result;
- }
- function createRangeTable(data) {
- var hi = 0;
- return data.split(",").map(function (v) {
- var comps = v.split("-");
- if (comps.length === 1) {
- comps[1] = "0";
- }
- else if (comps[1] === "") {
- comps[1] = "1";
- }
- var lo = hi + parseInt(comps[0], 16);
- hi = parseInt(comps[1], 16);
- return { l: lo, h: hi };
- });
- }
- function matchMap(value, ranges) {
- var lo = 0;
- for (var i = 0; i < ranges.length; i++) {
- var range = ranges[i];
- lo += range.l;
- if (value >= lo && value <= lo + range.h && ((value - lo) % (range.d || 1)) === 0) {
- if (range.e && range.e.indexOf(value - lo) !== -1) {
- continue;
- }
- return range;
- }
- }
- return null;
- }
- var Table_A_1_ranges = createRangeTable("221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d");
- // @TODO: Make this relative...
- var Table_B_1_flags = "ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff".split(",").map(function (v) { return parseInt(v, 16); });
- var Table_B_2_ranges = [
- { h: 25, s: 32, l: 65 },
- { h: 30, s: 32, e: [23], l: 127 },
- { h: 54, s: 1, e: [48], l: 64, d: 2 },
- { h: 14, s: 1, l: 57, d: 2 },
- { h: 44, s: 1, l: 17, d: 2 },
- { h: 10, s: 1, e: [2, 6, 8], l: 61, d: 2 },
- { h: 16, s: 1, l: 68, d: 2 },
- { h: 84, s: 1, e: [18, 24, 66], l: 19, d: 2 },
- { h: 26, s: 32, e: [17], l: 435 },
- { h: 22, s: 1, l: 71, d: 2 },
- { h: 15, s: 80, l: 40 },
- { h: 31, s: 32, l: 16 },
- { h: 32, s: 1, l: 80, d: 2 },
- { h: 52, s: 1, l: 42, d: 2 },
- { h: 12, s: 1, l: 55, d: 2 },
- { h: 40, s: 1, e: [38], l: 15, d: 2 },
- { h: 14, s: 1, l: 48, d: 2 },
- { h: 37, s: 48, l: 49 },
- { h: 148, s: 1, l: 6351, d: 2 },
- { h: 88, s: 1, l: 160, d: 2 },
- { h: 15, s: 16, l: 704 },
- { h: 25, s: 26, l: 854 },
- { h: 25, s: 32, l: 55915 },
- { h: 37, s: 40, l: 1247 },
- { h: 25, s: -119711, l: 53248 },
- { h: 25, s: -119763, l: 52 },
- { h: 25, s: -119815, l: 52 },
- { h: 25, s: -119867, e: [1, 4, 5, 7, 8, 11, 12, 17], l: 52 },
- { h: 25, s: -119919, l: 52 },
- { h: 24, s: -119971, e: [2, 7, 8, 17], l: 52 },
- { h: 24, s: -120023, e: [2, 7, 13, 15, 16, 17], l: 52 },
- { h: 25, s: -120075, l: 52 },
- { h: 25, s: -120127, l: 52 },
- { h: 25, s: -120179, l: 52 },
- { h: 25, s: -120231, l: 52 },
- { h: 25, s: -120283, l: 52 },
- { h: 25, s: -120335, l: 52 },
- { h: 24, s: -119543, e: [17], l: 56 },
- { h: 24, s: -119601, e: [17], l: 58 },
- { h: 24, s: -119659, e: [17], l: 58 },
- { h: 24, s: -119717, e: [17], l: 58 },
- { h: 24, s: -119775, e: [17], l: 58 }
- ];
- var Table_B_2_lut_abs = createTable("b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3");
- var Table_B_2_lut_rel = createTable("179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7");
- var Table_B_2_complex = createTable("df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D", bytes2);
- var Table_C_ranges = createRangeTable("80-20,2a0-,39c,32,f71,18e,7f2-f,19-7,30-4,7-5,f81-b,5,a800-20ff,4d1-1f,110,fa-6,d174-7,2e84-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,2,1f-5f,ff7f-20001");
- function flatten(values) {
- return values.reduce(function (accum, value) {
- value.forEach(function (value) { accum.push(value); });
- return accum;
- }, []);
- }
- function _nameprepTableA1(codepoint) {
- return !!matchMap(codepoint, Table_A_1_ranges);
- }
- exports._nameprepTableA1 = _nameprepTableA1;
- function _nameprepTableB2(codepoint) {
- var range = matchMap(codepoint, Table_B_2_ranges);
- if (range) {
- return [codepoint + range.s];
- }
- var codes = Table_B_2_lut_abs[codepoint];
- if (codes) {
- return codes;
- }
- var shift = Table_B_2_lut_rel[codepoint];
- if (shift) {
- return [codepoint + shift[0]];
- }
- var complex = Table_B_2_complex[codepoint];
- if (complex) {
- return complex;
- }
- return null;
- }
- exports._nameprepTableB2 = _nameprepTableB2;
- function _nameprepTableC(codepoint) {
- return !!matchMap(codepoint, Table_C_ranges);
- }
- exports._nameprepTableC = _nameprepTableC;
- function nameprep(value) {
- // This allows platforms with incomplete normalize to bypass
- // it for very basic names which the built-in toLowerCase
- // will certainly handle correctly
- if (value.match(/^[a-z0-9-]*$/i) && value.length <= 59) {
- return value.toLowerCase();
- }
- // Get the code points (keeping the current normalization)
- var codes = (0, utf8.toUtf8CodePoints)(value);
- codes = flatten(codes.map(function (code) {
- // Substitute Table B.1 (Maps to Nothing)
- if (Table_B_1_flags.indexOf(code) >= 0) {
- return [];
- }
- if (code >= 0xfe00 && code <= 0xfe0f) {
- return [];
- }
- // Substitute Table B.2 (Case Folding)
- var codesTableB2 = _nameprepTableB2(code);
- if (codesTableB2) {
- return codesTableB2;
- }
- // No Substitution
- return [code];
- }));
- // Normalize using form KC
- codes = (0, utf8.toUtf8CodePoints)((0, utf8._toUtf8String)(codes), utf8.UnicodeNormalizationForm.NFKC);
- // Prohibit Tables C.1.2, C.2.2, C.3, C.4, C.5, C.6, C.7, C.8, C.9
- codes.forEach(function (code) {
- if (_nameprepTableC(code)) {
- throw new Error("STRINGPREP_CONTAINS_PROHIBITED");
- }
- });
- // Prohibit Unassigned Code Points (Table A.1)
- codes.forEach(function (code) {
- if (_nameprepTableA1(code)) {
- throw new Error("STRINGPREP_CONTAINS_UNASSIGNED");
- }
- });
- // IDNA extras
- var name = (0, utf8._toUtf8String)(codes);
- // IDNA: 4.2.3.1
- if (name.substring(0, 1) === "-" || name.substring(2, 4) === "--" || name.substring(name.length - 1) === "-") {
- throw new Error("invalid hyphen");
- }
- // IDNA: 4.2.4
- if (name.length > 63) {
- throw new Error("too long");
- }
- return name;
- }
- exports.nameprep = nameprep;
- });
- var idna$1 = /*@__PURE__*/getDefaultExportFromCjs(idna);
- var lib$8 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.nameprep = exports.parseBytes32String = exports.formatBytes32String = exports.UnicodeNormalizationForm = exports.Utf8ErrorReason = exports.Utf8ErrorFuncs = exports.toUtf8String = exports.toUtf8CodePoints = exports.toUtf8Bytes = exports._toEscapedUtf8String = void 0;
- Object.defineProperty(exports, "formatBytes32String", { enumerable: true, get: function () { return bytes32.formatBytes32String; } });
- Object.defineProperty(exports, "parseBytes32String", { enumerable: true, get: function () { return bytes32.parseBytes32String; } });
- Object.defineProperty(exports, "nameprep", { enumerable: true, get: function () { return idna.nameprep; } });
- Object.defineProperty(exports, "_toEscapedUtf8String", { enumerable: true, get: function () { return utf8._toEscapedUtf8String; } });
- Object.defineProperty(exports, "toUtf8Bytes", { enumerable: true, get: function () { return utf8.toUtf8Bytes; } });
- Object.defineProperty(exports, "toUtf8CodePoints", { enumerable: true, get: function () { return utf8.toUtf8CodePoints; } });
- Object.defineProperty(exports, "toUtf8String", { enumerable: true, get: function () { return utf8.toUtf8String; } });
- Object.defineProperty(exports, "UnicodeNormalizationForm", { enumerable: true, get: function () { return utf8.UnicodeNormalizationForm; } });
- Object.defineProperty(exports, "Utf8ErrorFuncs", { enumerable: true, get: function () { return utf8.Utf8ErrorFuncs; } });
- Object.defineProperty(exports, "Utf8ErrorReason", { enumerable: true, get: function () { return utf8.Utf8ErrorReason; } });
- });
- var index$8 = /*@__PURE__*/getDefaultExportFromCjs(lib$8);
- var string = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.StringCoder = void 0;
- var StringCoder = /** @class */ (function (_super) {
- __extends(StringCoder, _super);
- function StringCoder(localName) {
- return _super.call(this, "string", localName) || this;
- }
- StringCoder.prototype.defaultValue = function () {
- return "";
- };
- StringCoder.prototype.encode = function (writer, value) {
- return _super.prototype.encode.call(this, writer, (0, lib$8.toUtf8Bytes)(value));
- };
- StringCoder.prototype.decode = function (reader) {
- return (0, lib$8.toUtf8String)(_super.prototype.decode.call(this, reader));
- };
- return StringCoder;
- }(bytes.DynamicBytesCoder));
- exports.StringCoder = StringCoder;
- });
- var string$1 = /*@__PURE__*/getDefaultExportFromCjs(string);
- var tuple = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.TupleCoder = void 0;
- var TupleCoder = /** @class */ (function (_super) {
- __extends(TupleCoder, _super);
- function TupleCoder(coders, localName) {
- var _this = this;
- var dynamic = false;
- var types = [];
- coders.forEach(function (coder) {
- if (coder.dynamic) {
- dynamic = true;
- }
- types.push(coder.type);
- });
- var type = ("tuple(" + types.join(",") + ")");
- _this = _super.call(this, "tuple", type, localName, dynamic) || this;
- _this.coders = coders;
- return _this;
- }
- TupleCoder.prototype.defaultValue = function () {
- var values = [];
- this.coders.forEach(function (coder) {
- values.push(coder.defaultValue());
- });
- // We only output named properties for uniquely named coders
- var uniqueNames = this.coders.reduce(function (accum, coder) {
- var name = coder.localName;
- if (name) {
- if (!accum[name]) {
- accum[name] = 0;
- }
- accum[name]++;
- }
- return accum;
- }, {});
- // Add named values
- this.coders.forEach(function (coder, index) {
- var name = coder.localName;
- if (!name || uniqueNames[name] !== 1) {
- return;
- }
- if (name === "length") {
- name = "_length";
- }
- if (values[name] != null) {
- return;
- }
- values[name] = values[index];
- });
- return Object.freeze(values);
- };
- TupleCoder.prototype.encode = function (writer, value) {
- return (0, array.pack)(writer, this.coders, value);
- };
- TupleCoder.prototype.decode = function (reader) {
- return reader.coerce(this.name, (0, array.unpack)(reader, this.coders));
- };
- return TupleCoder;
- }(abstractCoder.Coder));
- exports.TupleCoder = TupleCoder;
- });
- var tuple$1 = /*@__PURE__*/getDefaultExportFromCjs(tuple);
- var abiCoder = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.defaultAbiCoder = exports.AbiCoder = void 0;
- // See: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI
- var logger = new lib.Logger(_version$8.version);
- var paramTypeBytes = new RegExp(/^bytes([0-9]*)$/);
- var paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/);
- var AbiCoder = /** @class */ (function () {
- function AbiCoder(coerceFunc) {
- var _newTarget = this.constructor;
- logger.checkNew(_newTarget, AbiCoder);
- (0, lib$3.defineReadOnly)(this, "coerceFunc", coerceFunc || null);
- }
- AbiCoder.prototype._getCoder = function (param) {
- var _this = this;
- switch (param.baseType) {
- case "address":
- return new address.AddressCoder(param.name);
- case "bool":
- return new boolean_1.BooleanCoder(param.name);
- case "string":
- return new string.StringCoder(param.name);
- case "bytes":
- return new bytes.BytesCoder(param.name);
- case "array":
- return new array.ArrayCoder(this._getCoder(param.arrayChildren), param.arrayLength, param.name);
- case "tuple":
- return new tuple.TupleCoder((param.components || []).map(function (component) {
- return _this._getCoder(component);
- }), param.name);
- case "":
- return new _null.NullCoder(param.name);
- }
- // u?int[0-9]*
- var match = param.type.match(paramTypeNumber);
- if (match) {
- var size = parseInt(match[2] || "256");
- if (size === 0 || size > 256 || (size % 8) !== 0) {
- logger.throwArgumentError("invalid " + match[1] + " bit length", "param", param);
- }
- return new number.NumberCoder(size / 8, (match[1] === "int"), param.name);
- }
- // bytes[0-9]+
- match = param.type.match(paramTypeBytes);
- if (match) {
- var size = parseInt(match[1]);
- if (size === 0 || size > 32) {
- logger.throwArgumentError("invalid bytes length", "param", param);
- }
- return new fixedBytes.FixedBytesCoder(size, param.name);
- }
- return logger.throwArgumentError("invalid type", "type", param.type);
- };
- AbiCoder.prototype._getWordSize = function () { return 32; };
- AbiCoder.prototype._getReader = function (data, allowLoose) {
- return new abstractCoder.Reader(data, this._getWordSize(), this.coerceFunc, allowLoose);
- };
- AbiCoder.prototype._getWriter = function () {
- return new abstractCoder.Writer(this._getWordSize());
- };
- AbiCoder.prototype.getDefaultValue = function (types) {
- var _this = this;
- var coders = types.map(function (type) { return _this._getCoder(fragments.ParamType.from(type)); });
- var coder = new tuple.TupleCoder(coders, "_");
- return coder.defaultValue();
- };
- AbiCoder.prototype.encode = function (types, values) {
- var _this = this;
- if (types.length !== values.length) {
- logger.throwError("types/values length mismatch", lib.Logger.errors.INVALID_ARGUMENT, {
- count: { types: types.length, values: values.length },
- value: { types: types, values: values }
- });
- }
- var coders = types.map(function (type) { return _this._getCoder(fragments.ParamType.from(type)); });
- var coder = (new tuple.TupleCoder(coders, "_"));
- var writer = this._getWriter();
- coder.encode(writer, values);
- return writer.data;
- };
- AbiCoder.prototype.decode = function (types, data, loose) {
- var _this = this;
- var coders = types.map(function (type) { return _this._getCoder(fragments.ParamType.from(type)); });
- var coder = new tuple.TupleCoder(coders, "_");
- return coder.decode(this._getReader((0, lib$1.arrayify)(data), loose));
- };
- return AbiCoder;
- }());
- exports.AbiCoder = AbiCoder;
- exports.defaultAbiCoder = new AbiCoder();
- });
- var abiCoder$1 = /*@__PURE__*/getDefaultExportFromCjs(abiCoder);
- var id_1 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.id = void 0;
- function id(text) {
- return (0, lib$4.keccak256)((0, lib$8.toUtf8Bytes)(text));
- }
- exports.id = id;
- });
- var id = /*@__PURE__*/getDefaultExportFromCjs(id_1);
- var _version$g = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "hash/5.6.0";
- });
- var _version$h = /*@__PURE__*/getDefaultExportFromCjs(_version$g);
- var namehash_1 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.dnsEncode = exports.namehash = exports.isValidName = void 0;
- var logger = new lib.Logger(_version$g.version);
- var Zeros = new Uint8Array(32);
- Zeros.fill(0);
- var Partition = new RegExp("^((.*)\\.)?([^.]+)$");
- function isValidName(name) {
- try {
- var comps = name.split(".");
- for (var i = 0; i < comps.length; i++) {
- if ((0, lib$8.nameprep)(comps[i]).length === 0) {
- throw new Error("empty");
- }
- }
- return true;
- }
- catch (error) { }
- return false;
- }
- exports.isValidName = isValidName;
- function namehash(name) {
- /* istanbul ignore if */
- if (typeof (name) !== "string") {
- logger.throwArgumentError("invalid ENS name; not a string", "name", name);
- }
- var current = name;
- var result = Zeros;
- while (current.length) {
- var partition = current.match(Partition);
- if (partition == null || partition[2] === "") {
- logger.throwArgumentError("invalid ENS address; missing component", "name", name);
- }
- var label = (0, lib$8.toUtf8Bytes)((0, lib$8.nameprep)(partition[3]));
- result = (0, lib$4.keccak256)((0, lib$1.concat)([result, (0, lib$4.keccak256)(label)]));
- current = partition[2] || "";
- }
- return (0, lib$1.hexlify)(result);
- }
- exports.namehash = namehash;
- function dnsEncode(name) {
- return (0, lib$1.hexlify)((0, lib$1.concat)(name.split(".").map(function (comp) {
- // We jam in an _ prefix to fill in with the length later
- // Note: Nameprep throws if the component is over 63 bytes
- var bytes = (0, lib$8.toUtf8Bytes)("_" + (0, lib$8.nameprep)(comp));
- bytes[0] = bytes.length - 1;
- return bytes;
- }))) + "00";
- }
- exports.dnsEncode = dnsEncode;
- });
- var namehash = /*@__PURE__*/getDefaultExportFromCjs(namehash_1);
- var message = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.hashMessage = exports.messagePrefix = void 0;
- exports.messagePrefix = "\x19Ethereum Signed Message:\n";
- function hashMessage(message) {
- if (typeof (message) === "string") {
- message = (0, lib$8.toUtf8Bytes)(message);
- }
- return (0, lib$4.keccak256)((0, lib$1.concat)([
- (0, lib$8.toUtf8Bytes)(exports.messagePrefix),
- (0, lib$8.toUtf8Bytes)(String(message.length)),
- message
- ]));
- }
- exports.hashMessage = hashMessage;
- });
- var message$1 = /*@__PURE__*/getDefaultExportFromCjs(message);
- var typedData = createCommonjsModule(function (module, exports) {
- "use strict";
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.TypedDataEncoder = void 0;
- var logger = new lib.Logger(_version$g.version);
- var padding = new Uint8Array(32);
- padding.fill(0);
- var NegativeOne = lib$2.BigNumber.from(-1);
- var Zero = lib$2.BigNumber.from(0);
- var One = lib$2.BigNumber.from(1);
- var MaxUint256 = lib$2.BigNumber.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
- function hexPadRight(value) {
- var bytes = (0, lib$1.arrayify)(value);
- var padOffset = bytes.length % 32;
- if (padOffset) {
- return (0, lib$1.hexConcat)([bytes, padding.slice(padOffset)]);
- }
- return (0, lib$1.hexlify)(bytes);
- }
- var hexTrue = (0, lib$1.hexZeroPad)(One.toHexString(), 32);
- var hexFalse = (0, lib$1.hexZeroPad)(Zero.toHexString(), 32);
- var domainFieldTypes = {
- name: "string",
- version: "string",
- chainId: "uint256",
- verifyingContract: "address",
- salt: "bytes32"
- };
- var domainFieldNames = [
- "name", "version", "chainId", "verifyingContract", "salt"
- ];
- function checkString(key) {
- return function (value) {
- if (typeof (value) !== "string") {
- logger.throwArgumentError("invalid domain value for " + JSON.stringify(key), "domain." + key, value);
- }
- return value;
- };
- }
- var domainChecks = {
- name: checkString("name"),
- version: checkString("version"),
- chainId: function (value) {
- try {
- return lib$2.BigNumber.from(value).toString();
- }
- catch (error) { }
- return logger.throwArgumentError("invalid domain value for \"chainId\"", "domain.chainId", value);
- },
- verifyingContract: function (value) {
- try {
- return (0, lib$6.getAddress)(value).toLowerCase();
- }
- catch (error) { }
- return logger.throwArgumentError("invalid domain value \"verifyingContract\"", "domain.verifyingContract", value);
- },
- salt: function (value) {
- try {
- var bytes = (0, lib$1.arrayify)(value);
- if (bytes.length !== 32) {
- throw new Error("bad length");
- }
- return (0, lib$1.hexlify)(bytes);
- }
- catch (error) { }
- return logger.throwArgumentError("invalid domain value \"salt\"", "domain.salt", value);
- }
- };
- function getBaseEncoder(type) {
- // intXX and uintXX
- {
- var match = type.match(/^(u?)int(\d*)$/);
- if (match) {
- var signed = (match[1] === "");
- var width = parseInt(match[2] || "256");
- if (width % 8 !== 0 || width > 256 || (match[2] && match[2] !== String(width))) {
- logger.throwArgumentError("invalid numeric width", "type", type);
- }
- var boundsUpper_1 = MaxUint256.mask(signed ? (width - 1) : width);
- var boundsLower_1 = signed ? boundsUpper_1.add(One).mul(NegativeOne) : Zero;
- return function (value) {
- var v = lib$2.BigNumber.from(value);
- if (v.lt(boundsLower_1) || v.gt(boundsUpper_1)) {
- logger.throwArgumentError("value out-of-bounds for " + type, "value", value);
- }
- return (0, lib$1.hexZeroPad)(v.toTwos(256).toHexString(), 32);
- };
- }
- }
- // bytesXX
- {
- var match = type.match(/^bytes(\d+)$/);
- if (match) {
- var width_1 = parseInt(match[1]);
- if (width_1 === 0 || width_1 > 32 || match[1] !== String(width_1)) {
- logger.throwArgumentError("invalid bytes width", "type", type);
- }
- return function (value) {
- var bytes = (0, lib$1.arrayify)(value);
- if (bytes.length !== width_1) {
- logger.throwArgumentError("invalid length for " + type, "value", value);
- }
- return hexPadRight(value);
- };
- }
- }
- switch (type) {
- case "address": return function (value) {
- return (0, lib$1.hexZeroPad)((0, lib$6.getAddress)(value), 32);
- };
- case "bool": return function (value) {
- return ((!value) ? hexFalse : hexTrue);
- };
- case "bytes": return function (value) {
- return (0, lib$4.keccak256)(value);
- };
- case "string": return function (value) {
- return (0, id_1.id)(value);
- };
- }
- return null;
- }
- function encodeType(name, fields) {
- return name + "(" + fields.map(function (_a) {
- var name = _a.name, type = _a.type;
- return (type + " " + name);
- }).join(",") + ")";
- }
- var TypedDataEncoder = /** @class */ (function () {
- function TypedDataEncoder(types) {
- (0, lib$3.defineReadOnly)(this, "types", Object.freeze((0, lib$3.deepCopy)(types)));
- (0, lib$3.defineReadOnly)(this, "_encoderCache", {});
- (0, lib$3.defineReadOnly)(this, "_types", {});
- // Link struct types to their direct child structs
- var links = {};
- // Link structs to structs which contain them as a child
- var parents = {};
- // Link all subtypes within a given struct
- var subtypes = {};
- Object.keys(types).forEach(function (type) {
- links[type] = {};
- parents[type] = [];
- subtypes[type] = {};
- });
- var _loop_1 = function (name_1) {
- var uniqueNames = {};
- types[name_1].forEach(function (field) {
- // Check each field has a unique name
- if (uniqueNames[field.name]) {
- logger.throwArgumentError("duplicate variable name " + JSON.stringify(field.name) + " in " + JSON.stringify(name_1), "types", types);
- }
- uniqueNames[field.name] = true;
- // Get the base type (drop any array specifiers)
- var baseType = field.type.match(/^([^\x5b]*)(\x5b|$)/)[1];
- if (baseType === name_1) {
- logger.throwArgumentError("circular type reference to " + JSON.stringify(baseType), "types", types);
- }
- // Is this a base encoding type?
- var encoder = getBaseEncoder(baseType);
- if (encoder) {
- return;
- }
- if (!parents[baseType]) {
- logger.throwArgumentError("unknown type " + JSON.stringify(baseType), "types", types);
- }
- // Add linkage
- parents[baseType].push(name_1);
- links[name_1][baseType] = true;
- });
- };
- for (var name_1 in types) {
- _loop_1(name_1);
- }
- // Deduce the primary type
- var primaryTypes = Object.keys(parents).filter(function (n) { return (parents[n].length === 0); });
- if (primaryTypes.length === 0) {
- logger.throwArgumentError("missing primary type", "types", types);
- }
- else if (primaryTypes.length > 1) {
- logger.throwArgumentError("ambiguous primary types or unused types: " + primaryTypes.map(function (t) { return (JSON.stringify(t)); }).join(", "), "types", types);
- }
- (0, lib$3.defineReadOnly)(this, "primaryType", primaryTypes[0]);
- // Check for circular type references
- function checkCircular(type, found) {
- if (found[type]) {
- logger.throwArgumentError("circular type reference to " + JSON.stringify(type), "types", types);
- }
- found[type] = true;
- Object.keys(links[type]).forEach(function (child) {
- if (!parents[child]) {
- return;
- }
- // Recursively check children
- checkCircular(child, found);
- // Mark all ancestors as having this decendant
- Object.keys(found).forEach(function (subtype) {
- subtypes[subtype][child] = true;
- });
- });
- delete found[type];
- }
- checkCircular(this.primaryType, {});
- // Compute each fully describe type
- for (var name_2 in subtypes) {
- var st = Object.keys(subtypes[name_2]);
- st.sort();
- this._types[name_2] = encodeType(name_2, types[name_2]) + st.map(function (t) { return encodeType(t, types[t]); }).join("");
- }
- }
- TypedDataEncoder.prototype.getEncoder = function (type) {
- var encoder = this._encoderCache[type];
- if (!encoder) {
- encoder = this._encoderCache[type] = this._getEncoder(type);
- }
- return encoder;
- };
- TypedDataEncoder.prototype._getEncoder = function (type) {
- var _this = this;
- // Basic encoder type (address, bool, uint256, etc)
- {
- var encoder = getBaseEncoder(type);
- if (encoder) {
- return encoder;
- }
- }
- // Array
- var match = type.match(/^(.*)(\x5b(\d*)\x5d)$/);
- if (match) {
- var subtype_1 = match[1];
- var subEncoder_1 = this.getEncoder(subtype_1);
- var length_1 = parseInt(match[3]);
- return function (value) {
- if (length_1 >= 0 && value.length !== length_1) {
- logger.throwArgumentError("array length mismatch; expected length ${ arrayLength }", "value", value);
- }
- var result = value.map(subEncoder_1);
- if (_this._types[subtype_1]) {
- result = result.map(lib$4.keccak256);
- }
- return (0, lib$4.keccak256)((0, lib$1.hexConcat)(result));
- };
- }
- // Struct
- var fields = this.types[type];
- if (fields) {
- var encodedType_1 = (0, id_1.id)(this._types[type]);
- return function (value) {
- var values = fields.map(function (_a) {
- var name = _a.name, type = _a.type;
- var result = _this.getEncoder(type)(value[name]);
- if (_this._types[type]) {
- return (0, lib$4.keccak256)(result);
- }
- return result;
- });
- values.unshift(encodedType_1);
- return (0, lib$1.hexConcat)(values);
- };
- }
- return logger.throwArgumentError("unknown type: " + type, "type", type);
- };
- TypedDataEncoder.prototype.encodeType = function (name) {
- var result = this._types[name];
- if (!result) {
- logger.throwArgumentError("unknown type: " + JSON.stringify(name), "name", name);
- }
- return result;
- };
- TypedDataEncoder.prototype.encodeData = function (type, value) {
- return this.getEncoder(type)(value);
- };
- TypedDataEncoder.prototype.hashStruct = function (name, value) {
- return (0, lib$4.keccak256)(this.encodeData(name, value));
- };
- TypedDataEncoder.prototype.encode = function (value) {
- return this.encodeData(this.primaryType, value);
- };
- TypedDataEncoder.prototype.hash = function (value) {
- return this.hashStruct(this.primaryType, value);
- };
- TypedDataEncoder.prototype._visit = function (type, value, callback) {
- var _this = this;
- // Basic encoder type (address, bool, uint256, etc)
- {
- var encoder = getBaseEncoder(type);
- if (encoder) {
- return callback(type, value);
- }
- }
- // Array
- var match = type.match(/^(.*)(\x5b(\d*)\x5d)$/);
- if (match) {
- var subtype_2 = match[1];
- var length_2 = parseInt(match[3]);
- if (length_2 >= 0 && value.length !== length_2) {
- logger.throwArgumentError("array length mismatch; expected length ${ arrayLength }", "value", value);
- }
- return value.map(function (v) { return _this._visit(subtype_2, v, callback); });
- }
- // Struct
- var fields = this.types[type];
- if (fields) {
- return fields.reduce(function (accum, _a) {
- var name = _a.name, type = _a.type;
- accum[name] = _this._visit(type, value[name], callback);
- return accum;
- }, {});
- }
- return logger.throwArgumentError("unknown type: " + type, "type", type);
- };
- TypedDataEncoder.prototype.visit = function (value, callback) {
- return this._visit(this.primaryType, value, callback);
- };
- TypedDataEncoder.from = function (types) {
- return new TypedDataEncoder(types);
- };
- TypedDataEncoder.getPrimaryType = function (types) {
- return TypedDataEncoder.from(types).primaryType;
- };
- TypedDataEncoder.hashStruct = function (name, types, value) {
- return TypedDataEncoder.from(types).hashStruct(name, value);
- };
- TypedDataEncoder.hashDomain = function (domain) {
- var domainFields = [];
- for (var name_3 in domain) {
- var type = domainFieldTypes[name_3];
- if (!type) {
- logger.throwArgumentError("invalid typed-data domain key: " + JSON.stringify(name_3), "domain", domain);
- }
- domainFields.push({ name: name_3, type: type });
- }
- domainFields.sort(function (a, b) {
- return domainFieldNames.indexOf(a.name) - domainFieldNames.indexOf(b.name);
- });
- return TypedDataEncoder.hashStruct("EIP712Domain", { EIP712Domain: domainFields }, domain);
- };
- TypedDataEncoder.encode = function (domain, types, value) {
- return (0, lib$1.hexConcat)([
- "0x1901",
- TypedDataEncoder.hashDomain(domain),
- TypedDataEncoder.from(types).hash(value)
- ]);
- };
- TypedDataEncoder.hash = function (domain, types, value) {
- return (0, lib$4.keccak256)(TypedDataEncoder.encode(domain, types, value));
- };
- // Replaces all address types with ENS names with their looked up address
- TypedDataEncoder.resolveNames = function (domain, types, value, resolveName) {
- return __awaiter(this, void 0, void 0, function () {
- var ensCache, encoder, _a, _b, _i, name_4, _c, _d;
- return __generator(this, function (_e) {
- switch (_e.label) {
- case 0:
- // Make a copy to isolate it from the object passed in
- domain = (0, lib$3.shallowCopy)(domain);
- ensCache = {};
- // Do we need to look up the domain's verifyingContract?
- if (domain.verifyingContract && !(0, lib$1.isHexString)(domain.verifyingContract, 20)) {
- ensCache[domain.verifyingContract] = "0x";
- }
- encoder = TypedDataEncoder.from(types);
- // Get a list of all the addresses
- encoder.visit(value, function (type, value) {
- if (type === "address" && !(0, lib$1.isHexString)(value, 20)) {
- ensCache[value] = "0x";
- }
- return value;
- });
- _a = [];
- for (_b in ensCache)
- _a.push(_b);
- _i = 0;
- _e.label = 1;
- case 1:
- if (!(_i < _a.length)) return [3 /*break*/, 4];
- name_4 = _a[_i];
- _c = ensCache;
- _d = name_4;
- return [4 /*yield*/, resolveName(name_4)];
- case 2:
- _c[_d] = _e.sent();
- _e.label = 3;
- case 3:
- _i++;
- return [3 /*break*/, 1];
- case 4:
- // Replace the domain verifyingContract if needed
- if (domain.verifyingContract && ensCache[domain.verifyingContract]) {
- domain.verifyingContract = ensCache[domain.verifyingContract];
- }
- // Replace all ENS names with their address
- value = encoder.visit(value, function (type, value) {
- if (type === "address" && ensCache[value]) {
- return ensCache[value];
- }
- return value;
- });
- return [2 /*return*/, { domain: domain, value: value }];
- }
- });
- });
- };
- TypedDataEncoder.getPayload = function (domain, types, value) {
- // Validate the domain fields
- TypedDataEncoder.hashDomain(domain);
- // Derive the EIP712Domain Struct reference type
- var domainValues = {};
- var domainTypes = [];
- domainFieldNames.forEach(function (name) {
- var value = domain[name];
- if (value == null) {
- return;
- }
- domainValues[name] = domainChecks[name](value);
- domainTypes.push({ name: name, type: domainFieldTypes[name] });
- });
- var encoder = TypedDataEncoder.from(types);
- var typesWithDomain = (0, lib$3.shallowCopy)(types);
- if (typesWithDomain.EIP712Domain) {
- logger.throwArgumentError("types must not contain EIP712Domain type", "types.EIP712Domain", types);
- }
- else {
- typesWithDomain.EIP712Domain = domainTypes;
- }
- // Validate the data structures and types
- encoder.encode(value);
- return {
- types: typesWithDomain,
- domain: domainValues,
- primaryType: encoder.primaryType,
- message: encoder.visit(value, function (type, value) {
- // bytes
- if (type.match(/^bytes(\d*)/)) {
- return (0, lib$1.hexlify)((0, lib$1.arrayify)(value));
- }
- // uint or int
- if (type.match(/^u?int/)) {
- return lib$2.BigNumber.from(value).toString();
- }
- switch (type) {
- case "address":
- return value.toLowerCase();
- case "bool":
- return !!value;
- case "string":
- if (typeof (value) !== "string") {
- logger.throwArgumentError("invalid string", "value", value);
- }
- return value;
- }
- return logger.throwArgumentError("unsupported type", "type", type);
- })
- };
- };
- return TypedDataEncoder;
- }());
- exports.TypedDataEncoder = TypedDataEncoder;
- });
- var typedData$1 = /*@__PURE__*/getDefaultExportFromCjs(typedData);
- var lib$9 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports._TypedDataEncoder = exports.hashMessage = exports.messagePrefix = exports.isValidName = exports.namehash = exports.dnsEncode = exports.id = void 0;
- Object.defineProperty(exports, "id", { enumerable: true, get: function () { return id_1.id; } });
- Object.defineProperty(exports, "dnsEncode", { enumerable: true, get: function () { return namehash_1.dnsEncode; } });
- Object.defineProperty(exports, "isValidName", { enumerable: true, get: function () { return namehash_1.isValidName; } });
- Object.defineProperty(exports, "namehash", { enumerable: true, get: function () { return namehash_1.namehash; } });
- Object.defineProperty(exports, "hashMessage", { enumerable: true, get: function () { return message.hashMessage; } });
- Object.defineProperty(exports, "messagePrefix", { enumerable: true, get: function () { return message.messagePrefix; } });
- Object.defineProperty(exports, "_TypedDataEncoder", { enumerable: true, get: function () { return typedData.TypedDataEncoder; } });
- });
- var index$9 = /*@__PURE__*/getDefaultExportFromCjs(lib$9);
- var _interface = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Interface = exports.Indexed = exports.ErrorDescription = exports.TransactionDescription = exports.LogDescription = exports.checkResultErrors = void 0;
- Object.defineProperty(exports, "checkResultErrors", { enumerable: true, get: function () { return abstractCoder.checkResultErrors; } });
- var logger = new lib.Logger(_version$8.version);
- var LogDescription = /** @class */ (function (_super) {
- __extends(LogDescription, _super);
- function LogDescription() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- return LogDescription;
- }(lib$3.Description));
- exports.LogDescription = LogDescription;
- var TransactionDescription = /** @class */ (function (_super) {
- __extends(TransactionDescription, _super);
- function TransactionDescription() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- return TransactionDescription;
- }(lib$3.Description));
- exports.TransactionDescription = TransactionDescription;
- var ErrorDescription = /** @class */ (function (_super) {
- __extends(ErrorDescription, _super);
- function ErrorDescription() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- return ErrorDescription;
- }(lib$3.Description));
- exports.ErrorDescription = ErrorDescription;
- var Indexed = /** @class */ (function (_super) {
- __extends(Indexed, _super);
- function Indexed() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- Indexed.isIndexed = function (value) {
- return !!(value && value._isIndexed);
- };
- return Indexed;
- }(lib$3.Description));
- exports.Indexed = Indexed;
- var BuiltinErrors = {
- "0x08c379a0": { signature: "Error(string)", name: "Error", inputs: ["string"], reason: true },
- "0x4e487b71": { signature: "Panic(uint256)", name: "Panic", inputs: ["uint256"] }
- };
- function wrapAccessError(property, error) {
- var wrap = new Error("deferred error during ABI decoding triggered accessing " + property);
- wrap.error = error;
- return wrap;
- }
- /*
- function checkNames(fragment: Fragment, type: "input" | "output", params: Array<ParamType>): void {
- params.reduce((accum, param) => {
- if (param.name) {
- if (accum[param.name]) {
- logger.throwArgumentError(`duplicate ${ type } parameter ${ JSON.stringify(param.name) } in ${ fragment.format("full") }`, "fragment", fragment);
- }
- accum[param.name] = true;
- }
- return accum;
- }, <{ [ name: string ]: boolean }>{ });
- }
- */
- var Interface = /** @class */ (function () {
- function Interface(fragments$1) {
- var _newTarget = this.constructor;
- var _this = this;
- logger.checkNew(_newTarget, Interface);
- var abi = [];
- if (typeof (fragments$1) === "string") {
- abi = JSON.parse(fragments$1);
- }
- else {
- abi = fragments$1;
- }
- (0, lib$3.defineReadOnly)(this, "fragments", abi.map(function (fragment) {
- return fragments.Fragment.from(fragment);
- }).filter(function (fragment) { return (fragment != null); }));
- (0, lib$3.defineReadOnly)(this, "_abiCoder", (0, lib$3.getStatic)(_newTarget, "getAbiCoder")());
- (0, lib$3.defineReadOnly)(this, "functions", {});
- (0, lib$3.defineReadOnly)(this, "errors", {});
- (0, lib$3.defineReadOnly)(this, "events", {});
- (0, lib$3.defineReadOnly)(this, "structs", {});
- // Add all fragments by their signature
- this.fragments.forEach(function (fragment) {
- var bucket = null;
- switch (fragment.type) {
- case "constructor":
- if (_this.deploy) {
- logger.warn("duplicate definition - constructor");
- return;
- }
- //checkNames(fragment, "input", fragment.inputs);
- (0, lib$3.defineReadOnly)(_this, "deploy", fragment);
- return;
- case "function":
- //checkNames(fragment, "input", fragment.inputs);
- //checkNames(fragment, "output", (<FunctionFragment>fragment).outputs);
- bucket = _this.functions;
- break;
- case "event":
- //checkNames(fragment, "input", fragment.inputs);
- bucket = _this.events;
- break;
- case "error":
- bucket = _this.errors;
- break;
- default:
- return;
- }
- var signature = fragment.format();
- if (bucket[signature]) {
- logger.warn("duplicate definition - " + signature);
- return;
- }
- bucket[signature] = fragment;
- });
- // If we do not have a constructor add a default
- if (!this.deploy) {
- (0, lib$3.defineReadOnly)(this, "deploy", fragments.ConstructorFragment.from({
- payable: false,
- type: "constructor"
- }));
- }
- (0, lib$3.defineReadOnly)(this, "_isInterface", true);
- }
- Interface.prototype.format = function (format) {
- if (!format) {
- format = fragments.FormatTypes.full;
- }
- if (format === fragments.FormatTypes.sighash) {
- logger.throwArgumentError("interface does not support formatting sighash", "format", format);
- }
- var abi = this.fragments.map(function (fragment) { return fragment.format(format); });
- // We need to re-bundle the JSON fragments a bit
- if (format === fragments.FormatTypes.json) {
- return JSON.stringify(abi.map(function (j) { return JSON.parse(j); }));
- }
- return abi;
- };
- // Sub-classes can override these to handle other blockchains
- Interface.getAbiCoder = function () {
- return abiCoder.defaultAbiCoder;
- };
- Interface.getAddress = function (address) {
- return (0, lib$6.getAddress)(address);
- };
- Interface.getSighash = function (fragment) {
- return (0, lib$1.hexDataSlice)((0, lib$9.id)(fragment.format()), 0, 4);
- };
- Interface.getEventTopic = function (eventFragment) {
- return (0, lib$9.id)(eventFragment.format());
- };
- // Find a function definition by any means necessary (unless it is ambiguous)
- Interface.prototype.getFunction = function (nameOrSignatureOrSighash) {
- if ((0, lib$1.isHexString)(nameOrSignatureOrSighash)) {
- for (var name_1 in this.functions) {
- if (nameOrSignatureOrSighash === this.getSighash(name_1)) {
- return this.functions[name_1];
- }
- }
- logger.throwArgumentError("no matching function", "sighash", nameOrSignatureOrSighash);
- }
- // It is a bare name, look up the function (will return null if ambiguous)
- if (nameOrSignatureOrSighash.indexOf("(") === -1) {
- var name_2 = nameOrSignatureOrSighash.trim();
- var matching = Object.keys(this.functions).filter(function (f) { return (f.split("(" /* fix:) */)[0] === name_2); });
- if (matching.length === 0) {
- logger.throwArgumentError("no matching function", "name", name_2);
- }
- else if (matching.length > 1) {
- logger.throwArgumentError("multiple matching functions", "name", name_2);
- }
- return this.functions[matching[0]];
- }
- // Normalize the signature and lookup the function
- var result = this.functions[fragments.FunctionFragment.fromString(nameOrSignatureOrSighash).format()];
- if (!result) {
- logger.throwArgumentError("no matching function", "signature", nameOrSignatureOrSighash);
- }
- return result;
- };
- // Find an event definition by any means necessary (unless it is ambiguous)
- Interface.prototype.getEvent = function (nameOrSignatureOrTopic) {
- if ((0, lib$1.isHexString)(nameOrSignatureOrTopic)) {
- var topichash = nameOrSignatureOrTopic.toLowerCase();
- for (var name_3 in this.events) {
- if (topichash === this.getEventTopic(name_3)) {
- return this.events[name_3];
- }
- }
- logger.throwArgumentError("no matching event", "topichash", topichash);
- }
- // It is a bare name, look up the function (will return null if ambiguous)
- if (nameOrSignatureOrTopic.indexOf("(") === -1) {
- var name_4 = nameOrSignatureOrTopic.trim();
- var matching = Object.keys(this.events).filter(function (f) { return (f.split("(" /* fix:) */)[0] === name_4); });
- if (matching.length === 0) {
- logger.throwArgumentError("no matching event", "name", name_4);
- }
- else if (matching.length > 1) {
- logger.throwArgumentError("multiple matching events", "name", name_4);
- }
- return this.events[matching[0]];
- }
- // Normalize the signature and lookup the function
- var result = this.events[fragments.EventFragment.fromString(nameOrSignatureOrTopic).format()];
- if (!result) {
- logger.throwArgumentError("no matching event", "signature", nameOrSignatureOrTopic);
- }
- return result;
- };
- // Find a function definition by any means necessary (unless it is ambiguous)
- Interface.prototype.getError = function (nameOrSignatureOrSighash) {
- if ((0, lib$1.isHexString)(nameOrSignatureOrSighash)) {
- var getSighash = (0, lib$3.getStatic)(this.constructor, "getSighash");
- for (var name_5 in this.errors) {
- var error = this.errors[name_5];
- if (nameOrSignatureOrSighash === getSighash(error)) {
- return this.errors[name_5];
- }
- }
- logger.throwArgumentError("no matching error", "sighash", nameOrSignatureOrSighash);
- }
- // It is a bare name, look up the function (will return null if ambiguous)
- if (nameOrSignatureOrSighash.indexOf("(") === -1) {
- var name_6 = nameOrSignatureOrSighash.trim();
- var matching = Object.keys(this.errors).filter(function (f) { return (f.split("(" /* fix:) */)[0] === name_6); });
- if (matching.length === 0) {
- logger.throwArgumentError("no matching error", "name", name_6);
- }
- else if (matching.length > 1) {
- logger.throwArgumentError("multiple matching errors", "name", name_6);
- }
- return this.errors[matching[0]];
- }
- // Normalize the signature and lookup the function
- var result = this.errors[fragments.FunctionFragment.fromString(nameOrSignatureOrSighash).format()];
- if (!result) {
- logger.throwArgumentError("no matching error", "signature", nameOrSignatureOrSighash);
- }
- return result;
- };
- // Get the sighash (the bytes4 selector) used by Solidity to identify a function
- Interface.prototype.getSighash = function (fragment) {
- if (typeof (fragment) === "string") {
- try {
- fragment = this.getFunction(fragment);
- }
- catch (error) {
- try {
- fragment = this.getError(fragment);
- }
- catch (_) {
- throw error;
- }
- }
- }
- return (0, lib$3.getStatic)(this.constructor, "getSighash")(fragment);
- };
- // Get the topic (the bytes32 hash) used by Solidity to identify an event
- Interface.prototype.getEventTopic = function (eventFragment) {
- if (typeof (eventFragment) === "string") {
- eventFragment = this.getEvent(eventFragment);
- }
- return (0, lib$3.getStatic)(this.constructor, "getEventTopic")(eventFragment);
- };
- Interface.prototype._decodeParams = function (params, data) {
- return this._abiCoder.decode(params, data);
- };
- Interface.prototype._encodeParams = function (params, values) {
- return this._abiCoder.encode(params, values);
- };
- Interface.prototype.encodeDeploy = function (values) {
- return this._encodeParams(this.deploy.inputs, values || []);
- };
- Interface.prototype.decodeErrorResult = function (fragment, data) {
- if (typeof (fragment) === "string") {
- fragment = this.getError(fragment);
- }
- var bytes = (0, lib$1.arrayify)(data);
- if ((0, lib$1.hexlify)(bytes.slice(0, 4)) !== this.getSighash(fragment)) {
- logger.throwArgumentError("data signature does not match error " + fragment.name + ".", "data", (0, lib$1.hexlify)(bytes));
- }
- return this._decodeParams(fragment.inputs, bytes.slice(4));
- };
- Interface.prototype.encodeErrorResult = function (fragment, values) {
- if (typeof (fragment) === "string") {
- fragment = this.getError(fragment);
- }
- return (0, lib$1.hexlify)((0, lib$1.concat)([
- this.getSighash(fragment),
- this._encodeParams(fragment.inputs, values || [])
- ]));
- };
- // Decode the data for a function call (e.g. tx.data)
- Interface.prototype.decodeFunctionData = function (functionFragment, data) {
- if (typeof (functionFragment) === "string") {
- functionFragment = this.getFunction(functionFragment);
- }
- var bytes = (0, lib$1.arrayify)(data);
- if ((0, lib$1.hexlify)(bytes.slice(0, 4)) !== this.getSighash(functionFragment)) {
- logger.throwArgumentError("data signature does not match function " + functionFragment.name + ".", "data", (0, lib$1.hexlify)(bytes));
- }
- return this._decodeParams(functionFragment.inputs, bytes.slice(4));
- };
- // Encode the data for a function call (e.g. tx.data)
- Interface.prototype.encodeFunctionData = function (functionFragment, values) {
- if (typeof (functionFragment) === "string") {
- functionFragment = this.getFunction(functionFragment);
- }
- return (0, lib$1.hexlify)((0, lib$1.concat)([
- this.getSighash(functionFragment),
- this._encodeParams(functionFragment.inputs, values || [])
- ]));
- };
- // Decode the result from a function call (e.g. from eth_call)
- Interface.prototype.decodeFunctionResult = function (functionFragment, data) {
- if (typeof (functionFragment) === "string") {
- functionFragment = this.getFunction(functionFragment);
- }
- var bytes = (0, lib$1.arrayify)(data);
- var reason = null;
- var errorArgs = null;
- var errorName = null;
- var errorSignature = null;
- switch (bytes.length % this._abiCoder._getWordSize()) {
- case 0:
- try {
- return this._abiCoder.decode(functionFragment.outputs, bytes);
- }
- catch (error) { }
- break;
- case 4: {
- var selector = (0, lib$1.hexlify)(bytes.slice(0, 4));
- var builtin = BuiltinErrors[selector];
- if (builtin) {
- errorArgs = this._abiCoder.decode(builtin.inputs, bytes.slice(4));
- errorName = builtin.name;
- errorSignature = builtin.signature;
- if (builtin.reason) {
- reason = errorArgs[0];
- }
- }
- else {
- try {
- var error = this.getError(selector);
- errorArgs = this._abiCoder.decode(error.inputs, bytes.slice(4));
- errorName = error.name;
- errorSignature = error.format();
- }
- catch (error) { }
- }
- break;
- }
- }
- return logger.throwError("call revert exception", lib.Logger.errors.CALL_EXCEPTION, {
- method: functionFragment.format(),
- errorArgs: errorArgs,
- errorName: errorName,
- errorSignature: errorSignature,
- reason: reason
- });
- };
- // Encode the result for a function call (e.g. for eth_call)
- Interface.prototype.encodeFunctionResult = function (functionFragment, values) {
- if (typeof (functionFragment) === "string") {
- functionFragment = this.getFunction(functionFragment);
- }
- return (0, lib$1.hexlify)(this._abiCoder.encode(functionFragment.outputs, values || []));
- };
- // Create the filter for the event with search criteria (e.g. for eth_filterLog)
- Interface.prototype.encodeFilterTopics = function (eventFragment, values) {
- var _this = this;
- if (typeof (eventFragment) === "string") {
- eventFragment = this.getEvent(eventFragment);
- }
- if (values.length > eventFragment.inputs.length) {
- logger.throwError("too many arguments for " + eventFragment.format(), lib.Logger.errors.UNEXPECTED_ARGUMENT, {
- argument: "values",
- value: values
- });
- }
- var topics = [];
- if (!eventFragment.anonymous) {
- topics.push(this.getEventTopic(eventFragment));
- }
- var encodeTopic = function (param, value) {
- if (param.type === "string") {
- return (0, lib$9.id)(value);
- }
- else if (param.type === "bytes") {
- return (0, lib$4.keccak256)((0, lib$1.hexlify)(value));
- }
- // Check addresses are valid
- if (param.type === "address") {
- _this._abiCoder.encode(["address"], [value]);
- }
- return (0, lib$1.hexZeroPad)((0, lib$1.hexlify)(value), 32);
- };
- values.forEach(function (value, index) {
- var param = eventFragment.inputs[index];
- if (!param.indexed) {
- if (value != null) {
- logger.throwArgumentError("cannot filter non-indexed parameters; must be null", ("contract." + param.name), value);
- }
- return;
- }
- if (value == null) {
- topics.push(null);
- }
- else if (param.baseType === "array" || param.baseType === "tuple") {
- logger.throwArgumentError("filtering with tuples or arrays not supported", ("contract." + param.name), value);
- }
- else if (Array.isArray(value)) {
- topics.push(value.map(function (value) { return encodeTopic(param, value); }));
- }
- else {
- topics.push(encodeTopic(param, value));
- }
- });
- // Trim off trailing nulls
- while (topics.length && topics[topics.length - 1] === null) {
- topics.pop();
- }
- return topics;
- };
- Interface.prototype.encodeEventLog = function (eventFragment, values) {
- var _this = this;
- if (typeof (eventFragment) === "string") {
- eventFragment = this.getEvent(eventFragment);
- }
- var topics = [];
- var dataTypes = [];
- var dataValues = [];
- if (!eventFragment.anonymous) {
- topics.push(this.getEventTopic(eventFragment));
- }
- if (values.length !== eventFragment.inputs.length) {
- logger.throwArgumentError("event arguments/values mismatch", "values", values);
- }
- eventFragment.inputs.forEach(function (param, index) {
- var value = values[index];
- if (param.indexed) {
- if (param.type === "string") {
- topics.push((0, lib$9.id)(value));
- }
- else if (param.type === "bytes") {
- topics.push((0, lib$4.keccak256)(value));
- }
- else if (param.baseType === "tuple" || param.baseType === "array") {
- // @TODO
- throw new Error("not implemented");
- }
- else {
- topics.push(_this._abiCoder.encode([param.type], [value]));
- }
- }
- else {
- dataTypes.push(param);
- dataValues.push(value);
- }
- });
- return {
- data: this._abiCoder.encode(dataTypes, dataValues),
- topics: topics
- };
- };
- // Decode a filter for the event and the search criteria
- Interface.prototype.decodeEventLog = function (eventFragment, data, topics) {
- if (typeof (eventFragment) === "string") {
- eventFragment = this.getEvent(eventFragment);
- }
- if (topics != null && !eventFragment.anonymous) {
- var topicHash = this.getEventTopic(eventFragment);
- if (!(0, lib$1.isHexString)(topics[0], 32) || topics[0].toLowerCase() !== topicHash) {
- logger.throwError("fragment/topic mismatch", lib.Logger.errors.INVALID_ARGUMENT, { argument: "topics[0]", expected: topicHash, value: topics[0] });
- }
- topics = topics.slice(1);
- }
- var indexed = [];
- var nonIndexed = [];
- var dynamic = [];
- eventFragment.inputs.forEach(function (param, index) {
- if (param.indexed) {
- if (param.type === "string" || param.type === "bytes" || param.baseType === "tuple" || param.baseType === "array") {
- indexed.push(fragments.ParamType.fromObject({ type: "bytes32", name: param.name }));
- dynamic.push(true);
- }
- else {
- indexed.push(param);
- dynamic.push(false);
- }
- }
- else {
- nonIndexed.push(param);
- dynamic.push(false);
- }
- });
- var resultIndexed = (topics != null) ? this._abiCoder.decode(indexed, (0, lib$1.concat)(topics)) : null;
- var resultNonIndexed = this._abiCoder.decode(nonIndexed, data, true);
- var result = [];
- var nonIndexedIndex = 0, indexedIndex = 0;
- eventFragment.inputs.forEach(function (param, index) {
- if (param.indexed) {
- if (resultIndexed == null) {
- result[index] = new Indexed({ _isIndexed: true, hash: null });
- }
- else if (dynamic[index]) {
- result[index] = new Indexed({ _isIndexed: true, hash: resultIndexed[indexedIndex++] });
- }
- else {
- try {
- result[index] = resultIndexed[indexedIndex++];
- }
- catch (error) {
- result[index] = error;
- }
- }
- }
- else {
- try {
- result[index] = resultNonIndexed[nonIndexedIndex++];
- }
- catch (error) {
- result[index] = error;
- }
- }
- // Add the keyword argument if named and safe
- if (param.name && result[param.name] == null) {
- var value_1 = result[index];
- // Make error named values throw on access
- if (value_1 instanceof Error) {
- Object.defineProperty(result, param.name, {
- enumerable: true,
- get: function () { throw wrapAccessError("property " + JSON.stringify(param.name), value_1); }
- });
- }
- else {
- result[param.name] = value_1;
- }
- }
- });
- var _loop_1 = function (i) {
- var value = result[i];
- if (value instanceof Error) {
- Object.defineProperty(result, i, {
- enumerable: true,
- get: function () { throw wrapAccessError("index " + i, value); }
- });
- }
- };
- // Make all error indexed values throw on access
- for (var i = 0; i < result.length; i++) {
- _loop_1(i);
- }
- return Object.freeze(result);
- };
- // Given a transaction, find the matching function fragment (if any) and
- // determine all its properties and call parameters
- Interface.prototype.parseTransaction = function (tx) {
- var fragment = this.getFunction(tx.data.substring(0, 10).toLowerCase());
- if (!fragment) {
- return null;
- }
- return new TransactionDescription({
- args: this._abiCoder.decode(fragment.inputs, "0x" + tx.data.substring(10)),
- functionFragment: fragment,
- name: fragment.name,
- signature: fragment.format(),
- sighash: this.getSighash(fragment),
- value: lib$2.BigNumber.from(tx.value || "0"),
- });
- };
- // @TODO
- //parseCallResult(data: BytesLike): ??
- // Given an event log, find the matching event fragment (if any) and
- // determine all its properties and values
- Interface.prototype.parseLog = function (log) {
- var fragment = this.getEvent(log.topics[0]);
- if (!fragment || fragment.anonymous) {
- return null;
- }
- // @TODO: If anonymous, and the only method, and the input count matches, should we parse?
- // Probably not, because just because it is the only event in the ABI does
- // not mean we have the full ABI; maybe just a fragment?
- return new LogDescription({
- eventFragment: fragment,
- name: fragment.name,
- signature: fragment.format(),
- topic: this.getEventTopic(fragment),
- args: this.decodeEventLog(fragment, log.data, log.topics)
- });
- };
- Interface.prototype.parseError = function (data) {
- var hexData = (0, lib$1.hexlify)(data);
- var fragment = this.getError(hexData.substring(0, 10).toLowerCase());
- if (!fragment) {
- return null;
- }
- return new ErrorDescription({
- args: this._abiCoder.decode(fragment.inputs, "0x" + hexData.substring(10)),
- errorFragment: fragment,
- name: fragment.name,
- signature: fragment.format(),
- sighash: this.getSighash(fragment),
- });
- };
- /*
- static from(value: Array<Fragment | string | JsonAbi> | string | Interface) {
- if (Interface.isInterface(value)) {
- return value;
- }
- if (typeof(value) === "string") {
- return new Interface(JSON.parse(value));
- }
- return new Interface(value);
- }
- */
- Interface.isInterface = function (value) {
- return !!(value && value._isInterface);
- };
- return Interface;
- }());
- exports.Interface = Interface;
- });
- var _interface$1 = /*@__PURE__*/getDefaultExportFromCjs(_interface);
- var lib$a = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.TransactionDescription = exports.LogDescription = exports.checkResultErrors = exports.Indexed = exports.Interface = exports.defaultAbiCoder = exports.AbiCoder = exports.FormatTypes = exports.ParamType = exports.FunctionFragment = exports.Fragment = exports.EventFragment = exports.ErrorFragment = exports.ConstructorFragment = void 0;
- Object.defineProperty(exports, "ConstructorFragment", { enumerable: true, get: function () { return fragments.ConstructorFragment; } });
- Object.defineProperty(exports, "ErrorFragment", { enumerable: true, get: function () { return fragments.ErrorFragment; } });
- Object.defineProperty(exports, "EventFragment", { enumerable: true, get: function () { return fragments.EventFragment; } });
- Object.defineProperty(exports, "FormatTypes", { enumerable: true, get: function () { return fragments.FormatTypes; } });
- Object.defineProperty(exports, "Fragment", { enumerable: true, get: function () { return fragments.Fragment; } });
- Object.defineProperty(exports, "FunctionFragment", { enumerable: true, get: function () { return fragments.FunctionFragment; } });
- Object.defineProperty(exports, "ParamType", { enumerable: true, get: function () { return fragments.ParamType; } });
- Object.defineProperty(exports, "AbiCoder", { enumerable: true, get: function () { return abiCoder.AbiCoder; } });
- Object.defineProperty(exports, "defaultAbiCoder", { enumerable: true, get: function () { return abiCoder.defaultAbiCoder; } });
- Object.defineProperty(exports, "checkResultErrors", { enumerable: true, get: function () { return _interface.checkResultErrors; } });
- Object.defineProperty(exports, "Indexed", { enumerable: true, get: function () { return _interface.Indexed; } });
- Object.defineProperty(exports, "Interface", { enumerable: true, get: function () { return _interface.Interface; } });
- Object.defineProperty(exports, "LogDescription", { enumerable: true, get: function () { return _interface.LogDescription; } });
- Object.defineProperty(exports, "TransactionDescription", { enumerable: true, get: function () { return _interface.TransactionDescription; } });
- });
- var index$a = /*@__PURE__*/getDefaultExportFromCjs(lib$a);
- var _version$i = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "abstract-provider/5.6.0";
- });
- var _version$j = /*@__PURE__*/getDefaultExportFromCjs(_version$i);
- var lib$b = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Provider = exports.TransactionOrderForkEvent = exports.TransactionForkEvent = exports.BlockForkEvent = exports.ForkEvent = void 0;
- var logger = new lib.Logger(_version$i.version);
- ;
- ;
- //export type CallTransactionable = {
- // call(transaction: TransactionRequest): Promise<TransactionResponse>;
- //};
- var ForkEvent = /** @class */ (function (_super) {
- __extends(ForkEvent, _super);
- function ForkEvent() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- ForkEvent.isForkEvent = function (value) {
- return !!(value && value._isForkEvent);
- };
- return ForkEvent;
- }(lib$3.Description));
- exports.ForkEvent = ForkEvent;
- var BlockForkEvent = /** @class */ (function (_super) {
- __extends(BlockForkEvent, _super);
- function BlockForkEvent(blockHash, expiry) {
- var _this = this;
- if (!(0, lib$1.isHexString)(blockHash, 32)) {
- logger.throwArgumentError("invalid blockHash", "blockHash", blockHash);
- }
- _this = _super.call(this, {
- _isForkEvent: true,
- _isBlockForkEvent: true,
- expiry: (expiry || 0),
- blockHash: blockHash
- }) || this;
- return _this;
- }
- return BlockForkEvent;
- }(ForkEvent));
- exports.BlockForkEvent = BlockForkEvent;
- var TransactionForkEvent = /** @class */ (function (_super) {
- __extends(TransactionForkEvent, _super);
- function TransactionForkEvent(hash, expiry) {
- var _this = this;
- if (!(0, lib$1.isHexString)(hash, 32)) {
- logger.throwArgumentError("invalid transaction hash", "hash", hash);
- }
- _this = _super.call(this, {
- _isForkEvent: true,
- _isTransactionForkEvent: true,
- expiry: (expiry || 0),
- hash: hash
- }) || this;
- return _this;
- }
- return TransactionForkEvent;
- }(ForkEvent));
- exports.TransactionForkEvent = TransactionForkEvent;
- var TransactionOrderForkEvent = /** @class */ (function (_super) {
- __extends(TransactionOrderForkEvent, _super);
- function TransactionOrderForkEvent(beforeHash, afterHash, expiry) {
- var _this = this;
- if (!(0, lib$1.isHexString)(beforeHash, 32)) {
- logger.throwArgumentError("invalid transaction hash", "beforeHash", beforeHash);
- }
- if (!(0, lib$1.isHexString)(afterHash, 32)) {
- logger.throwArgumentError("invalid transaction hash", "afterHash", afterHash);
- }
- _this = _super.call(this, {
- _isForkEvent: true,
- _isTransactionOrderForkEvent: true,
- expiry: (expiry || 0),
- beforeHash: beforeHash,
- afterHash: afterHash
- }) || this;
- return _this;
- }
- return TransactionOrderForkEvent;
- }(ForkEvent));
- exports.TransactionOrderForkEvent = TransactionOrderForkEvent;
- ///////////////////////////////
- // Exported Abstracts
- var Provider = /** @class */ (function () {
- function Provider() {
- var _newTarget = this.constructor;
- logger.checkAbstract(_newTarget, Provider);
- (0, lib$3.defineReadOnly)(this, "_isProvider", true);
- }
- Provider.prototype.getFeeData = function () {
- return __awaiter(this, void 0, void 0, function () {
- var _a, block, gasPrice, maxFeePerGas, maxPriorityFeePerGas;
- return __generator(this, function (_b) {
- switch (_b.label) {
- case 0: return [4 /*yield*/, (0, lib$3.resolveProperties)({
- block: this.getBlock("latest"),
- gasPrice: this.getGasPrice().catch(function (error) {
- // @TODO: Why is this now failing on Calaveras?
- //console.log(error);
- return null;
- })
- })];
- case 1:
- _a = _b.sent(), block = _a.block, gasPrice = _a.gasPrice;
- maxFeePerGas = null, maxPriorityFeePerGas = null;
- if (block && block.baseFeePerGas) {
- // We may want to compute this more accurately in the future,
- // using the formula "check if the base fee is correct".
- // See: https://eips.ethereum.org/EIPS/eip-1559
- maxPriorityFeePerGas = lib$2.BigNumber.from("1500000000");
- maxFeePerGas = block.baseFeePerGas.mul(2).add(maxPriorityFeePerGas);
- }
- return [2 /*return*/, { maxFeePerGas: maxFeePerGas, maxPriorityFeePerGas: maxPriorityFeePerGas, gasPrice: gasPrice }];
- }
- });
- });
- };
- // Alias for "on"
- Provider.prototype.addListener = function (eventName, listener) {
- return this.on(eventName, listener);
- };
- // Alias for "off"
- Provider.prototype.removeListener = function (eventName, listener) {
- return this.off(eventName, listener);
- };
- Provider.isProvider = function (value) {
- return !!(value && value._isProvider);
- };
- return Provider;
- }());
- exports.Provider = Provider;
- });
- var index$b = /*@__PURE__*/getDefaultExportFromCjs(lib$b);
- var _version$k = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "abstract-signer/5.6.0";
- });
- var _version$l = /*@__PURE__*/getDefaultExportFromCjs(_version$k);
- var lib$c = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.VoidSigner = exports.Signer = void 0;
- var logger = new lib.Logger(_version$k.version);
- var allowedTransactionKeys = [
- "accessList", "ccipReadEnabled", "chainId", "customData", "data", "from", "gasLimit", "gasPrice", "maxFeePerGas", "maxPriorityFeePerGas", "nonce", "to", "type", "value"
- ];
- var forwardErrors = [
- lib.Logger.errors.INSUFFICIENT_FUNDS,
- lib.Logger.errors.NONCE_EXPIRED,
- lib.Logger.errors.REPLACEMENT_UNDERPRICED,
- ];
- ;
- ;
- var Signer = /** @class */ (function () {
- ///////////////////
- // Sub-classes MUST call super
- function Signer() {
- var _newTarget = this.constructor;
- logger.checkAbstract(_newTarget, Signer);
- (0, lib$3.defineReadOnly)(this, "_isSigner", true);
- }
- ///////////////////
- // Sub-classes MAY override these
- Signer.prototype.getBalance = function (blockTag) {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- this._checkProvider("getBalance");
- return [4 /*yield*/, this.provider.getBalance(this.getAddress(), blockTag)];
- case 1: return [2 /*return*/, _a.sent()];
- }
- });
- });
- };
- Signer.prototype.getTransactionCount = function (blockTag) {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- this._checkProvider("getTransactionCount");
- return [4 /*yield*/, this.provider.getTransactionCount(this.getAddress(), blockTag)];
- case 1: return [2 /*return*/, _a.sent()];
- }
- });
- });
- };
- // Populates "from" if unspecified, and estimates the gas for the transaction
- Signer.prototype.estimateGas = function (transaction) {
- return __awaiter(this, void 0, void 0, function () {
- var tx;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- this._checkProvider("estimateGas");
- return [4 /*yield*/, (0, lib$3.resolveProperties)(this.checkTransaction(transaction))];
- case 1:
- tx = _a.sent();
- return [4 /*yield*/, this.provider.estimateGas(tx)];
- case 2: return [2 /*return*/, _a.sent()];
- }
- });
- });
- };
- // Populates "from" if unspecified, and calls with the transaction
- Signer.prototype.call = function (transaction, blockTag) {
- return __awaiter(this, void 0, void 0, function () {
- var tx;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- this._checkProvider("call");
- return [4 /*yield*/, (0, lib$3.resolveProperties)(this.checkTransaction(transaction))];
- case 1:
- tx = _a.sent();
- return [4 /*yield*/, this.provider.call(tx, blockTag)];
- case 2: return [2 /*return*/, _a.sent()];
- }
- });
- });
- };
- // Populates all fields in a transaction, signs it and sends it to the network
- Signer.prototype.sendTransaction = function (transaction) {
- return __awaiter(this, void 0, void 0, function () {
- var tx, signedTx;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- this._checkProvider("sendTransaction");
- return [4 /*yield*/, this.populateTransaction(transaction)];
- case 1:
- tx = _a.sent();
- return [4 /*yield*/, this.signTransaction(tx)];
- case 2:
- signedTx = _a.sent();
- return [4 /*yield*/, this.provider.sendTransaction(signedTx)];
- case 3: return [2 /*return*/, _a.sent()];
- }
- });
- });
- };
- Signer.prototype.getChainId = function () {
- return __awaiter(this, void 0, void 0, function () {
- var network;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- this._checkProvider("getChainId");
- return [4 /*yield*/, this.provider.getNetwork()];
- case 1:
- network = _a.sent();
- return [2 /*return*/, network.chainId];
- }
- });
- });
- };
- Signer.prototype.getGasPrice = function () {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- this._checkProvider("getGasPrice");
- return [4 /*yield*/, this.provider.getGasPrice()];
- case 1: return [2 /*return*/, _a.sent()];
- }
- });
- });
- };
- Signer.prototype.getFeeData = function () {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- this._checkProvider("getFeeData");
- return [4 /*yield*/, this.provider.getFeeData()];
- case 1: return [2 /*return*/, _a.sent()];
- }
- });
- });
- };
- Signer.prototype.resolveName = function (name) {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- this._checkProvider("resolveName");
- return [4 /*yield*/, this.provider.resolveName(name)];
- case 1: return [2 /*return*/, _a.sent()];
- }
- });
- });
- };
- // Checks a transaction does not contain invalid keys and if
- // no "from" is provided, populates it.
- // - does NOT require a provider
- // - adds "from" is not present
- // - returns a COPY (safe to mutate the result)
- // By default called from: (overriding these prevents it)
- // - call
- // - estimateGas
- // - populateTransaction (and therefor sendTransaction)
- Signer.prototype.checkTransaction = function (transaction) {
- for (var key in transaction) {
- if (allowedTransactionKeys.indexOf(key) === -1) {
- logger.throwArgumentError("invalid transaction key: " + key, "transaction", transaction);
- }
- }
- var tx = (0, lib$3.shallowCopy)(transaction);
- if (tx.from == null) {
- tx.from = this.getAddress();
- }
- else {
- // Make sure any provided address matches this signer
- tx.from = Promise.all([
- Promise.resolve(tx.from),
- this.getAddress()
- ]).then(function (result) {
- if (result[0].toLowerCase() !== result[1].toLowerCase()) {
- logger.throwArgumentError("from address mismatch", "transaction", transaction);
- }
- return result[0];
- });
- }
- return tx;
- };
- // Populates ALL keys for a transaction and checks that "from" matches
- // this Signer. Should be used by sendTransaction but NOT by signTransaction.
- // By default called from: (overriding these prevents it)
- // - sendTransaction
- //
- // Notes:
- // - We allow gasPrice for EIP-1559 as long as it matches maxFeePerGas
- Signer.prototype.populateTransaction = function (transaction) {
- return __awaiter(this, void 0, void 0, function () {
- var tx, hasEip1559, feeData, gasPrice;
- var _this = this;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, (0, lib$3.resolveProperties)(this.checkTransaction(transaction))];
- case 1:
- tx = _a.sent();
- if (tx.to != null) {
- tx.to = Promise.resolve(tx.to).then(function (to) { return __awaiter(_this, void 0, void 0, function () {
- var address;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (to == null) {
- return [2 /*return*/, null];
- }
- return [4 /*yield*/, this.resolveName(to)];
- case 1:
- address = _a.sent();
- if (address == null) {
- logger.throwArgumentError("provided ENS name resolves to null", "tx.to", to);
- }
- return [2 /*return*/, address];
- }
- });
- }); });
- // Prevent this error from causing an UnhandledPromiseException
- tx.to.catch(function (error) { });
- }
- hasEip1559 = (tx.maxFeePerGas != null || tx.maxPriorityFeePerGas != null);
- if (tx.gasPrice != null && (tx.type === 2 || hasEip1559)) {
- logger.throwArgumentError("eip-1559 transaction do not support gasPrice", "transaction", transaction);
- }
- else if ((tx.type === 0 || tx.type === 1) && hasEip1559) {
- logger.throwArgumentError("pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas", "transaction", transaction);
- }
- if (!((tx.type === 2 || tx.type == null) && (tx.maxFeePerGas != null && tx.maxPriorityFeePerGas != null))) return [3 /*break*/, 2];
- // Fully-formed EIP-1559 transaction (skip getFeeData)
- tx.type = 2;
- return [3 /*break*/, 5];
- case 2:
- if (!(tx.type === 0 || tx.type === 1)) return [3 /*break*/, 3];
- // Explicit Legacy or EIP-2930 transaction
- // Populate missing gasPrice
- if (tx.gasPrice == null) {
- tx.gasPrice = this.getGasPrice();
- }
- return [3 /*break*/, 5];
- case 3: return [4 /*yield*/, this.getFeeData()];
- case 4:
- feeData = _a.sent();
- if (tx.type == null) {
- // We need to auto-detect the intended type of this transaction...
- if (feeData.maxFeePerGas != null && feeData.maxPriorityFeePerGas != null) {
- // The network supports EIP-1559!
- // Upgrade transaction from null to eip-1559
- tx.type = 2;
- if (tx.gasPrice != null) {
- gasPrice = tx.gasPrice;
- delete tx.gasPrice;
- tx.maxFeePerGas = gasPrice;
- tx.maxPriorityFeePerGas = gasPrice;
- }
- else {
- // Populate missing fee data
- if (tx.maxFeePerGas == null) {
- tx.maxFeePerGas = feeData.maxFeePerGas;
- }
- if (tx.maxPriorityFeePerGas == null) {
- tx.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas;
- }
- }
- }
- else if (feeData.gasPrice != null) {
- // Network doesn't support EIP-1559...
- // ...but they are trying to use EIP-1559 properties
- if (hasEip1559) {
- logger.throwError("network does not support EIP-1559", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "populateTransaction"
- });
- }
- // Populate missing fee data
- if (tx.gasPrice == null) {
- tx.gasPrice = feeData.gasPrice;
- }
- // Explicitly set untyped transaction to legacy
- tx.type = 0;
- }
- else {
- // getFeeData has failed us.
- logger.throwError("failed to get consistent fee data", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "signer.getFeeData"
- });
- }
- }
- else if (tx.type === 2) {
- // Explicitly using EIP-1559
- // Populate missing fee data
- if (tx.maxFeePerGas == null) {
- tx.maxFeePerGas = feeData.maxFeePerGas;
- }
- if (tx.maxPriorityFeePerGas == null) {
- tx.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas;
- }
- }
- _a.label = 5;
- case 5:
- if (tx.nonce == null) {
- tx.nonce = this.getTransactionCount("pending");
- }
- if (tx.gasLimit == null) {
- tx.gasLimit = this.estimateGas(tx).catch(function (error) {
- if (forwardErrors.indexOf(error.code) >= 0) {
- throw error;
- }
- return logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", lib.Logger.errors.UNPREDICTABLE_GAS_LIMIT, {
- error: error,
- tx: tx
- });
- });
- }
- if (tx.chainId == null) {
- tx.chainId = this.getChainId();
- }
- else {
- tx.chainId = Promise.all([
- Promise.resolve(tx.chainId),
- this.getChainId()
- ]).then(function (results) {
- if (results[1] !== 0 && results[0] !== results[1]) {
- logger.throwArgumentError("chainId address mismatch", "transaction", transaction);
- }
- return results[0];
- });
- }
- return [4 /*yield*/, (0, lib$3.resolveProperties)(tx)];
- case 6: return [2 /*return*/, _a.sent()];
- }
- });
- });
- };
- ///////////////////
- // Sub-classes SHOULD leave these alone
- Signer.prototype._checkProvider = function (operation) {
- if (!this.provider) {
- logger.throwError("missing provider", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: (operation || "_checkProvider")
- });
- }
- };
- Signer.isSigner = function (value) {
- return !!(value && value._isSigner);
- };
- return Signer;
- }());
- exports.Signer = Signer;
- var VoidSigner = /** @class */ (function (_super) {
- __extends(VoidSigner, _super);
- function VoidSigner(address, provider) {
- var _newTarget = this.constructor;
- var _this = this;
- logger.checkNew(_newTarget, VoidSigner);
- _this = _super.call(this) || this;
- (0, lib$3.defineReadOnly)(_this, "address", address);
- (0, lib$3.defineReadOnly)(_this, "provider", provider || null);
- return _this;
- }
- VoidSigner.prototype.getAddress = function () {
- return Promise.resolve(this.address);
- };
- VoidSigner.prototype._fail = function (message, operation) {
- return Promise.resolve().then(function () {
- logger.throwError(message, lib.Logger.errors.UNSUPPORTED_OPERATION, { operation: operation });
- });
- };
- VoidSigner.prototype.signMessage = function (message) {
- return this._fail("VoidSigner cannot sign messages", "signMessage");
- };
- VoidSigner.prototype.signTransaction = function (transaction) {
- return this._fail("VoidSigner cannot sign transactions", "signTransaction");
- };
- VoidSigner.prototype._signTypedData = function (domain, types, value) {
- return this._fail("VoidSigner cannot sign typed data", "signTypedData");
- };
- VoidSigner.prototype.connect = function (provider) {
- return new VoidSigner(this.address, provider);
- };
- return VoidSigner;
- }(Signer));
- exports.VoidSigner = VoidSigner;
- });
- var index$c = /*@__PURE__*/getDefaultExportFromCjs(lib$c);
- var minimalisticAssert = assert;
- function assert(val, msg) {
- if (!val)
- throw new Error(msg || 'Assertion failed');
- }
- assert.equal = function assertEqual(l, r, msg) {
- if (l != r)
- throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
- };
- var utils_1 = createCommonjsModule(function (module, exports) {
- 'use strict';
- var utils = exports;
- function toArray(msg, enc) {
- if (Array.isArray(msg))
- return msg.slice();
- if (!msg)
- return [];
- var res = [];
- if (typeof msg !== 'string') {
- for (var i = 0; i < msg.length; i++)
- res[i] = msg[i] | 0;
- return res;
- }
- if (enc === 'hex') {
- msg = msg.replace(/[^a-z0-9]+/ig, '');
- if (msg.length % 2 !== 0)
- msg = '0' + msg;
- for (var i = 0; i < msg.length; i += 2)
- res.push(parseInt(msg[i] + msg[i + 1], 16));
- } else {
- for (var i = 0; i < msg.length; i++) {
- var c = msg.charCodeAt(i);
- var hi = c >> 8;
- var lo = c & 0xff;
- if (hi)
- res.push(hi, lo);
- else
- res.push(lo);
- }
- }
- return res;
- }
- utils.toArray = toArray;
- function zero2(word) {
- if (word.length === 1)
- return '0' + word;
- else
- return word;
- }
- utils.zero2 = zero2;
- function toHex(msg) {
- var res = '';
- for (var i = 0; i < msg.length; i++)
- res += zero2(msg[i].toString(16));
- return res;
- }
- utils.toHex = toHex;
- utils.encode = function encode(arr, enc) {
- if (enc === 'hex')
- return toHex(arr);
- else
- return arr;
- };
- });
- var utils_1$1 = createCommonjsModule(function (module, exports) {
- 'use strict';
- var utils = exports;
- utils.assert = minimalisticAssert;
- utils.toArray = utils_1.toArray;
- utils.zero2 = utils_1.zero2;
- utils.toHex = utils_1.toHex;
- utils.encode = utils_1.encode;
- // Represent num in a w-NAF form
- function getNAF(num, w, bits) {
- var naf = new Array(Math.max(num.bitLength(), bits) + 1);
- naf.fill(0);
- var ws = 1 << (w + 1);
- var k = num.clone();
- for (var i = 0; i < naf.length; i++) {
- var z;
- var mod = k.andln(ws - 1);
- if (k.isOdd()) {
- if (mod > (ws >> 1) - 1)
- z = (ws >> 1) - mod;
- else
- z = mod;
- k.isubn(z);
- } else {
- z = 0;
- }
- naf[i] = z;
- k.iushrn(1);
- }
- return naf;
- }
- utils.getNAF = getNAF;
- // Represent k1, k2 in a Joint Sparse Form
- function getJSF(k1, k2) {
- var jsf = [
- [],
- [],
- ];
- k1 = k1.clone();
- k2 = k2.clone();
- var d1 = 0;
- var d2 = 0;
- var m8;
- while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
- // First phase
- var m14 = (k1.andln(3) + d1) & 3;
- var m24 = (k2.andln(3) + d2) & 3;
- if (m14 === 3)
- m14 = -1;
- if (m24 === 3)
- m24 = -1;
- var u1;
- if ((m14 & 1) === 0) {
- u1 = 0;
- } else {
- m8 = (k1.andln(7) + d1) & 7;
- if ((m8 === 3 || m8 === 5) && m24 === 2)
- u1 = -m14;
- else
- u1 = m14;
- }
- jsf[0].push(u1);
- var u2;
- if ((m24 & 1) === 0) {
- u2 = 0;
- } else {
- m8 = (k2.andln(7) + d2) & 7;
- if ((m8 === 3 || m8 === 5) && m14 === 2)
- u2 = -m24;
- else
- u2 = m24;
- }
- jsf[1].push(u2);
- // Second phase
- if (2 * d1 === u1 + 1)
- d1 = 1 - d1;
- if (2 * d2 === u2 + 1)
- d2 = 1 - d2;
- k1.iushrn(1);
- k2.iushrn(1);
- }
- return jsf;
- }
- utils.getJSF = getJSF;
- function cachedProperty(obj, name, computer) {
- var key = '_' + name;
- obj.prototype[name] = function cachedProperty() {
- return this[key] !== undefined ? this[key] :
- this[key] = computer.call(this);
- };
- }
- utils.cachedProperty = cachedProperty;
- function parseBytes(bytes) {
- return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
- bytes;
- }
- utils.parseBytes = parseBytes;
- function intFromLE(bytes) {
- return new bn(bytes, 'hex', 'le');
- }
- utils.intFromLE = intFromLE;
- });
- 'use strict';
- var getNAF = utils_1$1.getNAF;
- var getJSF = utils_1$1.getJSF;
- var assert$1 = utils_1$1.assert;
- function BaseCurve(type, conf) {
- this.type = type;
- this.p = new bn(conf.p, 16);
- // Use Montgomery, when there is no fast reduction for the prime
- this.red = conf.prime ? bn.red(conf.prime) : bn.mont(this.p);
- // Useful for many curves
- this.zero = new bn(0).toRed(this.red);
- this.one = new bn(1).toRed(this.red);
- this.two = new bn(2).toRed(this.red);
- // Curve configuration, optional
- this.n = conf.n && new bn(conf.n, 16);
- this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
- // Temporary arrays
- this._wnafT1 = new Array(4);
- this._wnafT2 = new Array(4);
- this._wnafT3 = new Array(4);
- this._wnafT4 = new Array(4);
- this._bitLength = this.n ? this.n.bitLength() : 0;
- // Generalized Greg Maxwell's trick
- var adjustCount = this.n && this.p.div(this.n);
- if (!adjustCount || adjustCount.cmpn(100) > 0) {
- this.redN = null;
- } else {
- this._maxwellTrick = true;
- this.redN = this.n.toRed(this.red);
- }
- }
- var base = BaseCurve;
- BaseCurve.prototype.point = function point() {
- throw new Error('Not implemented');
- };
- BaseCurve.prototype.validate = function validate() {
- throw new Error('Not implemented');
- };
- BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
- assert$1(p.precomputed);
- var doubles = p._getDoubles();
- var naf = getNAF(k, 1, this._bitLength);
- var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
- I /= 3;
- // Translate into more windowed form
- var repr = [];
- var j;
- var nafW;
- for (j = 0; j < naf.length; j += doubles.step) {
- nafW = 0;
- for (var l = j + doubles.step - 1; l >= j; l--)
- nafW = (nafW << 1) + naf[l];
- repr.push(nafW);
- }
- var a = this.jpoint(null, null, null);
- var b = this.jpoint(null, null, null);
- for (var i = I; i > 0; i--) {
- for (j = 0; j < repr.length; j++) {
- nafW = repr[j];
- if (nafW === i)
- b = b.mixedAdd(doubles.points[j]);
- else if (nafW === -i)
- b = b.mixedAdd(doubles.points[j].neg());
- }
- a = a.add(b);
- }
- return a.toP();
- };
- BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
- var w = 4;
- // Precompute window
- var nafPoints = p._getNAFPoints(w);
- w = nafPoints.wnd;
- var wnd = nafPoints.points;
- // Get NAF form
- var naf = getNAF(k, w, this._bitLength);
- // Add `this`*(N+1) for every w-NAF index
- var acc = this.jpoint(null, null, null);
- for (var i = naf.length - 1; i >= 0; i--) {
- // Count zeroes
- for (var l = 0; i >= 0 && naf[i] === 0; i--)
- l++;
- if (i >= 0)
- l++;
- acc = acc.dblp(l);
- if (i < 0)
- break;
- var z = naf[i];
- assert$1(z !== 0);
- if (p.type === 'affine') {
- // J +- P
- if (z > 0)
- acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
- else
- acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
- } else {
- // J +- J
- if (z > 0)
- acc = acc.add(wnd[(z - 1) >> 1]);
- else
- acc = acc.add(wnd[(-z - 1) >> 1].neg());
- }
- }
- return p.type === 'affine' ? acc.toP() : acc;
- };
- BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
- points,
- coeffs,
- len,
- jacobianResult) {
- var wndWidth = this._wnafT1;
- var wnd = this._wnafT2;
- var naf = this._wnafT3;
- // Fill all arrays
- var max = 0;
- var i;
- var j;
- var p;
- for (i = 0; i < len; i++) {
- p = points[i];
- var nafPoints = p._getNAFPoints(defW);
- wndWidth[i] = nafPoints.wnd;
- wnd[i] = nafPoints.points;
- }
- // Comb small window NAFs
- for (i = len - 1; i >= 1; i -= 2) {
- var a = i - 1;
- var b = i;
- if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
- naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength);
- naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength);
- max = Math.max(naf[a].length, max);
- max = Math.max(naf[b].length, max);
- continue;
- }
- var comb = [
- points[a], /* 1 */
- null, /* 3 */
- null, /* 5 */
- points[b], /* 7 */
- ];
- // Try to avoid Projective points, if possible
- if (points[a].y.cmp(points[b].y) === 0) {
- comb[1] = points[a].add(points[b]);
- comb[2] = points[a].toJ().mixedAdd(points[b].neg());
- } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
- comb[1] = points[a].toJ().mixedAdd(points[b]);
- comb[2] = points[a].add(points[b].neg());
- } else {
- comb[1] = points[a].toJ().mixedAdd(points[b]);
- comb[2] = points[a].toJ().mixedAdd(points[b].neg());
- }
- var index = [
- -3, /* -1 -1 */
- -1, /* -1 0 */
- -5, /* -1 1 */
- -7, /* 0 -1 */
- 0, /* 0 0 */
- 7, /* 0 1 */
- 5, /* 1 -1 */
- 1, /* 1 0 */
- 3, /* 1 1 */
- ];
- var jsf = getJSF(coeffs[a], coeffs[b]);
- max = Math.max(jsf[0].length, max);
- naf[a] = new Array(max);
- naf[b] = new Array(max);
- for (j = 0; j < max; j++) {
- var ja = jsf[0][j] | 0;
- var jb = jsf[1][j] | 0;
- naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
- naf[b][j] = 0;
- wnd[a] = comb;
- }
- }
- var acc = this.jpoint(null, null, null);
- var tmp = this._wnafT4;
- for (i = max; i >= 0; i--) {
- var k = 0;
- while (i >= 0) {
- var zero = true;
- for (j = 0; j < len; j++) {
- tmp[j] = naf[j][i] | 0;
- if (tmp[j] !== 0)
- zero = false;
- }
- if (!zero)
- break;
- k++;
- i--;
- }
- if (i >= 0)
- k++;
- acc = acc.dblp(k);
- if (i < 0)
- break;
- for (j = 0; j < len; j++) {
- var z = tmp[j];
- p;
- if (z === 0)
- continue;
- else if (z > 0)
- p = wnd[j][(z - 1) >> 1];
- else if (z < 0)
- p = wnd[j][(-z - 1) >> 1].neg();
- if (p.type === 'affine')
- acc = acc.mixedAdd(p);
- else
- acc = acc.add(p);
- }
- }
- // Zeroify references
- for (i = 0; i < len; i++)
- wnd[i] = null;
- if (jacobianResult)
- return acc;
- else
- return acc.toP();
- };
- function BasePoint(curve, type) {
- this.curve = curve;
- this.type = type;
- this.precomputed = null;
- }
- BaseCurve.BasePoint = BasePoint;
- BasePoint.prototype.eq = function eq(/*other*/) {
- throw new Error('Not implemented');
- };
- BasePoint.prototype.validate = function validate() {
- return this.curve.validate(this);
- };
- BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
- bytes = utils_1$1.toArray(bytes, enc);
- var len = this.p.byteLength();
- // uncompressed, hybrid-odd, hybrid-even
- if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
- bytes.length - 1 === 2 * len) {
- if (bytes[0] === 0x06)
- assert$1(bytes[bytes.length - 1] % 2 === 0);
- else if (bytes[0] === 0x07)
- assert$1(bytes[bytes.length - 1] % 2 === 1);
- var res = this.point(bytes.slice(1, 1 + len),
- bytes.slice(1 + len, 1 + 2 * len));
- return res;
- } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
- bytes.length - 1 === len) {
- return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
- }
- throw new Error('Unknown point format');
- };
- BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
- return this.encode(enc, true);
- };
- BasePoint.prototype._encode = function _encode(compact) {
- var len = this.curve.p.byteLength();
- var x = this.getX().toArray('be', len);
- if (compact)
- return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);
- return [ 0x04 ].concat(x, this.getY().toArray('be', len));
- };
- BasePoint.prototype.encode = function encode(enc, compact) {
- return utils_1$1.encode(this._encode(compact), enc);
- };
- BasePoint.prototype.precompute = function precompute(power) {
- if (this.precomputed)
- return this;
- var precomputed = {
- doubles: null,
- naf: null,
- beta: null,
- };
- precomputed.naf = this._getNAFPoints(8);
- precomputed.doubles = this._getDoubles(4, power);
- precomputed.beta = this._getBeta();
- this.precomputed = precomputed;
- return this;
- };
- BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
- if (!this.precomputed)
- return false;
- var doubles = this.precomputed.doubles;
- if (!doubles)
- return false;
- return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
- };
- BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
- if (this.precomputed && this.precomputed.doubles)
- return this.precomputed.doubles;
- var doubles = [ this ];
- var acc = this;
- for (var i = 0; i < power; i += step) {
- for (var j = 0; j < step; j++)
- acc = acc.dbl();
- doubles.push(acc);
- }
- return {
- step: step,
- points: doubles,
- };
- };
- BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
- if (this.precomputed && this.precomputed.naf)
- return this.precomputed.naf;
- var res = [ this ];
- var max = (1 << wnd) - 1;
- var dbl = max === 1 ? null : this.dbl();
- for (var i = 1; i < max; i++)
- res[i] = res[i - 1].add(dbl);
- return {
- wnd: wnd,
- points: res,
- };
- };
- BasePoint.prototype._getBeta = function _getBeta() {
- return null;
- };
- BasePoint.prototype.dblp = function dblp(k) {
- var r = this;
- for (var i = 0; i < k; i++)
- r = r.dbl();
- return r;
- };
- var inherits_browser = createCommonjsModule(function (module) {
- if (typeof Object.create === 'function') {
- // implementation from standard node.js 'util' module
- module.exports = function inherits(ctor, superCtor) {
- if (superCtor) {
- ctor.super_ = superCtor;
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- }
- };
- } else {
- // old school shim for old browsers
- module.exports = function inherits(ctor, superCtor) {
- if (superCtor) {
- ctor.super_ = superCtor;
- var TempCtor = function () {};
- TempCtor.prototype = superCtor.prototype;
- ctor.prototype = new TempCtor();
- ctor.prototype.constructor = ctor;
- }
- };
- }
- });
- 'use strict';
- var assert$2 = utils_1$1.assert;
- function ShortCurve(conf) {
- base.call(this, 'short', conf);
- this.a = new bn(conf.a, 16).toRed(this.red);
- this.b = new bn(conf.b, 16).toRed(this.red);
- this.tinv = this.two.redInvm();
- this.zeroA = this.a.fromRed().cmpn(0) === 0;
- this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
- // If the curve is endomorphic, precalculate beta and lambda
- this.endo = this._getEndomorphism(conf);
- this._endoWnafT1 = new Array(4);
- this._endoWnafT2 = new Array(4);
- }
- inherits_browser(ShortCurve, base);
- var short_1 = ShortCurve;
- ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
- // No efficient endomorphism
- if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
- return;
- // Compute beta and lambda, that lambda * P = (beta * Px; Py)
- var beta;
- var lambda;
- if (conf.beta) {
- beta = new bn(conf.beta, 16).toRed(this.red);
- } else {
- var betas = this._getEndoRoots(this.p);
- // Choose the smallest beta
- beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
- beta = beta.toRed(this.red);
- }
- if (conf.lambda) {
- lambda = new bn(conf.lambda, 16);
- } else {
- // Choose the lambda that is matching selected beta
- var lambdas = this._getEndoRoots(this.n);
- if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
- lambda = lambdas[0];
- } else {
- lambda = lambdas[1];
- assert$2(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
- }
- }
- // Get basis vectors, used for balanced length-two representation
- var basis;
- if (conf.basis) {
- basis = conf.basis.map(function(vec) {
- return {
- a: new bn(vec.a, 16),
- b: new bn(vec.b, 16),
- };
- });
- } else {
- basis = this._getEndoBasis(lambda);
- }
- return {
- beta: beta,
- lambda: lambda,
- basis: basis,
- };
- };
- ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
- // Find roots of for x^2 + x + 1 in F
- // Root = (-1 +- Sqrt(-3)) / 2
- //
- var red = num === this.p ? this.red : bn.mont(num);
- var tinv = new bn(2).toRed(red).redInvm();
- var ntinv = tinv.redNeg();
- var s = new bn(3).toRed(red).redNeg().redSqrt().redMul(tinv);
- var l1 = ntinv.redAdd(s).fromRed();
- var l2 = ntinv.redSub(s).fromRed();
- return [ l1, l2 ];
- };
- ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
- // aprxSqrt >= sqrt(this.n)
- var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
- // 3.74
- // Run EGCD, until r(L + 1) < aprxSqrt
- var u = lambda;
- var v = this.n.clone();
- var x1 = new bn(1);
- var y1 = new bn(0);
- var x2 = new bn(0);
- var y2 = new bn(1);
- // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
- var a0;
- var b0;
- // First vector
- var a1;
- var b1;
- // Second vector
- var a2;
- var b2;
- var prevR;
- var i = 0;
- var r;
- var x;
- while (u.cmpn(0) !== 0) {
- var q = v.div(u);
- r = v.sub(q.mul(u));
- x = x2.sub(q.mul(x1));
- var y = y2.sub(q.mul(y1));
- if (!a1 && r.cmp(aprxSqrt) < 0) {
- a0 = prevR.neg();
- b0 = x1;
- a1 = r.neg();
- b1 = x;
- } else if (a1 && ++i === 2) {
- break;
- }
- prevR = r;
- v = u;
- u = r;
- x2 = x1;
- x1 = x;
- y2 = y1;
- y1 = y;
- }
- a2 = r.neg();
- b2 = x;
- var len1 = a1.sqr().add(b1.sqr());
- var len2 = a2.sqr().add(b2.sqr());
- if (len2.cmp(len1) >= 0) {
- a2 = a0;
- b2 = b0;
- }
- // Normalize signs
- if (a1.negative) {
- a1 = a1.neg();
- b1 = b1.neg();
- }
- if (a2.negative) {
- a2 = a2.neg();
- b2 = b2.neg();
- }
- return [
- { a: a1, b: b1 },
- { a: a2, b: b2 },
- ];
- };
- ShortCurve.prototype._endoSplit = function _endoSplit(k) {
- var basis = this.endo.basis;
- var v1 = basis[0];
- var v2 = basis[1];
- var c1 = v2.b.mul(k).divRound(this.n);
- var c2 = v1.b.neg().mul(k).divRound(this.n);
- var p1 = c1.mul(v1.a);
- var p2 = c2.mul(v2.a);
- var q1 = c1.mul(v1.b);
- var q2 = c2.mul(v2.b);
- // Calculate answer
- var k1 = k.sub(p1).sub(p2);
- var k2 = q1.add(q2).neg();
- return { k1: k1, k2: k2 };
- };
- ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
- x = new bn(x, 16);
- if (!x.red)
- x = x.toRed(this.red);
- var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
- var y = y2.redSqrt();
- if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
- throw new Error('invalid point');
- // XXX Is there any way to tell if the number is odd without converting it
- // to non-red form?
- var isOdd = y.fromRed().isOdd();
- if (odd && !isOdd || !odd && isOdd)
- y = y.redNeg();
- return this.point(x, y);
- };
- ShortCurve.prototype.validate = function validate(point) {
- if (point.inf)
- return true;
- var x = point.x;
- var y = point.y;
- var ax = this.a.redMul(x);
- var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
- return y.redSqr().redISub(rhs).cmpn(0) === 0;
- };
- ShortCurve.prototype._endoWnafMulAdd =
- function _endoWnafMulAdd(points, coeffs, jacobianResult) {
- var npoints = this._endoWnafT1;
- var ncoeffs = this._endoWnafT2;
- for (var i = 0; i < points.length; i++) {
- var split = this._endoSplit(coeffs[i]);
- var p = points[i];
- var beta = p._getBeta();
- if (split.k1.negative) {
- split.k1.ineg();
- p = p.neg(true);
- }
- if (split.k2.negative) {
- split.k2.ineg();
- beta = beta.neg(true);
- }
- npoints[i * 2] = p;
- npoints[i * 2 + 1] = beta;
- ncoeffs[i * 2] = split.k1;
- ncoeffs[i * 2 + 1] = split.k2;
- }
- var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);
- // Clean-up references to points and coefficients
- for (var j = 0; j < i * 2; j++) {
- npoints[j] = null;
- ncoeffs[j] = null;
- }
- return res;
- };
- function Point(curve, x, y, isRed) {
- base.BasePoint.call(this, curve, 'affine');
- if (x === null && y === null) {
- this.x = null;
- this.y = null;
- this.inf = true;
- } else {
- this.x = new bn(x, 16);
- this.y = new bn(y, 16);
- // Force redgomery representation when loading from JSON
- if (isRed) {
- this.x.forceRed(this.curve.red);
- this.y.forceRed(this.curve.red);
- }
- if (!this.x.red)
- this.x = this.x.toRed(this.curve.red);
- if (!this.y.red)
- this.y = this.y.toRed(this.curve.red);
- this.inf = false;
- }
- }
- inherits_browser(Point, base.BasePoint);
- ShortCurve.prototype.point = function point(x, y, isRed) {
- return new Point(this, x, y, isRed);
- };
- ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
- return Point.fromJSON(this, obj, red);
- };
- Point.prototype._getBeta = function _getBeta() {
- if (!this.curve.endo)
- return;
- var pre = this.precomputed;
- if (pre && pre.beta)
- return pre.beta;
- var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
- if (pre) {
- var curve = this.curve;
- var endoMul = function(p) {
- return curve.point(p.x.redMul(curve.endo.beta), p.y);
- };
- pre.beta = beta;
- beta.precomputed = {
- beta: null,
- naf: pre.naf && {
- wnd: pre.naf.wnd,
- points: pre.naf.points.map(endoMul),
- },
- doubles: pre.doubles && {
- step: pre.doubles.step,
- points: pre.doubles.points.map(endoMul),
- },
- };
- }
- return beta;
- };
- Point.prototype.toJSON = function toJSON() {
- if (!this.precomputed)
- return [ this.x, this.y ];
- return [ this.x, this.y, this.precomputed && {
- doubles: this.precomputed.doubles && {
- step: this.precomputed.doubles.step,
- points: this.precomputed.doubles.points.slice(1),
- },
- naf: this.precomputed.naf && {
- wnd: this.precomputed.naf.wnd,
- points: this.precomputed.naf.points.slice(1),
- },
- } ];
- };
- Point.fromJSON = function fromJSON(curve, obj, red) {
- if (typeof obj === 'string')
- obj = JSON.parse(obj);
- var res = curve.point(obj[0], obj[1], red);
- if (!obj[2])
- return res;
- function obj2point(obj) {
- return curve.point(obj[0], obj[1], red);
- }
- var pre = obj[2];
- res.precomputed = {
- beta: null,
- doubles: pre.doubles && {
- step: pre.doubles.step,
- points: [ res ].concat(pre.doubles.points.map(obj2point)),
- },
- naf: pre.naf && {
- wnd: pre.naf.wnd,
- points: [ res ].concat(pre.naf.points.map(obj2point)),
- },
- };
- return res;
- };
- Point.prototype.inspect = function inspect() {
- if (this.isInfinity())
- return '<EC Point Infinity>';
- return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
- ' y: ' + this.y.fromRed().toString(16, 2) + '>';
- };
- Point.prototype.isInfinity = function isInfinity() {
- return this.inf;
- };
- Point.prototype.add = function add(p) {
- // O + P = P
- if (this.inf)
- return p;
- // P + O = P
- if (p.inf)
- return this;
- // P + P = 2P
- if (this.eq(p))
- return this.dbl();
- // P + (-P) = O
- if (this.neg().eq(p))
- return this.curve.point(null, null);
- // P + Q = O
- if (this.x.cmp(p.x) === 0)
- return this.curve.point(null, null);
- var c = this.y.redSub(p.y);
- if (c.cmpn(0) !== 0)
- c = c.redMul(this.x.redSub(p.x).redInvm());
- var nx = c.redSqr().redISub(this.x).redISub(p.x);
- var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
- return this.curve.point(nx, ny);
- };
- Point.prototype.dbl = function dbl() {
- if (this.inf)
- return this;
- // 2P = O
- var ys1 = this.y.redAdd(this.y);
- if (ys1.cmpn(0) === 0)
- return this.curve.point(null, null);
- var a = this.curve.a;
- var x2 = this.x.redSqr();
- var dyinv = ys1.redInvm();
- var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
- var nx = c.redSqr().redISub(this.x.redAdd(this.x));
- var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
- return this.curve.point(nx, ny);
- };
- Point.prototype.getX = function getX() {
- return this.x.fromRed();
- };
- Point.prototype.getY = function getY() {
- return this.y.fromRed();
- };
- Point.prototype.mul = function mul(k) {
- k = new bn(k, 16);
- if (this.isInfinity())
- return this;
- else if (this._hasDoubles(k))
- return this.curve._fixedNafMul(this, k);
- else if (this.curve.endo)
- return this.curve._endoWnafMulAdd([ this ], [ k ]);
- else
- return this.curve._wnafMul(this, k);
- };
- Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
- var points = [ this, p2 ];
- var coeffs = [ k1, k2 ];
- if (this.curve.endo)
- return this.curve._endoWnafMulAdd(points, coeffs);
- else
- return this.curve._wnafMulAdd(1, points, coeffs, 2);
- };
- Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
- var points = [ this, p2 ];
- var coeffs = [ k1, k2 ];
- if (this.curve.endo)
- return this.curve._endoWnafMulAdd(points, coeffs, true);
- else
- return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
- };
- Point.prototype.eq = function eq(p) {
- return this === p ||
- this.inf === p.inf &&
- (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
- };
- Point.prototype.neg = function neg(_precompute) {
- if (this.inf)
- return this;
- var res = this.curve.point(this.x, this.y.redNeg());
- if (_precompute && this.precomputed) {
- var pre = this.precomputed;
- var negate = function(p) {
- return p.neg();
- };
- res.precomputed = {
- naf: pre.naf && {
- wnd: pre.naf.wnd,
- points: pre.naf.points.map(negate),
- },
- doubles: pre.doubles && {
- step: pre.doubles.step,
- points: pre.doubles.points.map(negate),
- },
- };
- }
- return res;
- };
- Point.prototype.toJ = function toJ() {
- if (this.inf)
- return this.curve.jpoint(null, null, null);
- var res = this.curve.jpoint(this.x, this.y, this.curve.one);
- return res;
- };
- function JPoint(curve, x, y, z) {
- base.BasePoint.call(this, curve, 'jacobian');
- if (x === null && y === null && z === null) {
- this.x = this.curve.one;
- this.y = this.curve.one;
- this.z = new bn(0);
- } else {
- this.x = new bn(x, 16);
- this.y = new bn(y, 16);
- this.z = new bn(z, 16);
- }
- if (!this.x.red)
- this.x = this.x.toRed(this.curve.red);
- if (!this.y.red)
- this.y = this.y.toRed(this.curve.red);
- if (!this.z.red)
- this.z = this.z.toRed(this.curve.red);
- this.zOne = this.z === this.curve.one;
- }
- inherits_browser(JPoint, base.BasePoint);
- ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
- return new JPoint(this, x, y, z);
- };
- JPoint.prototype.toP = function toP() {
- if (this.isInfinity())
- return this.curve.point(null, null);
- var zinv = this.z.redInvm();
- var zinv2 = zinv.redSqr();
- var ax = this.x.redMul(zinv2);
- var ay = this.y.redMul(zinv2).redMul(zinv);
- return this.curve.point(ax, ay);
- };
- JPoint.prototype.neg = function neg() {
- return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
- };
- JPoint.prototype.add = function add(p) {
- // O + P = P
- if (this.isInfinity())
- return p;
- // P + O = P
- if (p.isInfinity())
- return this;
- // 12M + 4S + 7A
- var pz2 = p.z.redSqr();
- var z2 = this.z.redSqr();
- var u1 = this.x.redMul(pz2);
- var u2 = p.x.redMul(z2);
- var s1 = this.y.redMul(pz2.redMul(p.z));
- var s2 = p.y.redMul(z2.redMul(this.z));
- var h = u1.redSub(u2);
- var r = s1.redSub(s2);
- if (h.cmpn(0) === 0) {
- if (r.cmpn(0) !== 0)
- return this.curve.jpoint(null, null, null);
- else
- return this.dbl();
- }
- var h2 = h.redSqr();
- var h3 = h2.redMul(h);
- var v = u1.redMul(h2);
- var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
- var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
- var nz = this.z.redMul(p.z).redMul(h);
- return this.curve.jpoint(nx, ny, nz);
- };
- JPoint.prototype.mixedAdd = function mixedAdd(p) {
- // O + P = P
- if (this.isInfinity())
- return p.toJ();
- // P + O = P
- if (p.isInfinity())
- return this;
- // 8M + 3S + 7A
- var z2 = this.z.redSqr();
- var u1 = this.x;
- var u2 = p.x.redMul(z2);
- var s1 = this.y;
- var s2 = p.y.redMul(z2).redMul(this.z);
- var h = u1.redSub(u2);
- var r = s1.redSub(s2);
- if (h.cmpn(0) === 0) {
- if (r.cmpn(0) !== 0)
- return this.curve.jpoint(null, null, null);
- else
- return this.dbl();
- }
- var h2 = h.redSqr();
- var h3 = h2.redMul(h);
- var v = u1.redMul(h2);
- var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
- var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
- var nz = this.z.redMul(h);
- return this.curve.jpoint(nx, ny, nz);
- };
- JPoint.prototype.dblp = function dblp(pow) {
- if (pow === 0)
- return this;
- if (this.isInfinity())
- return this;
- if (!pow)
- return this.dbl();
- var i;
- if (this.curve.zeroA || this.curve.threeA) {
- var r = this;
- for (i = 0; i < pow; i++)
- r = r.dbl();
- return r;
- }
- // 1M + 2S + 1A + N * (4S + 5M + 8A)
- // N = 1 => 6M + 6S + 9A
- var a = this.curve.a;
- var tinv = this.curve.tinv;
- var jx = this.x;
- var jy = this.y;
- var jz = this.z;
- var jz4 = jz.redSqr().redSqr();
- // Reuse results
- var jyd = jy.redAdd(jy);
- for (i = 0; i < pow; i++) {
- var jx2 = jx.redSqr();
- var jyd2 = jyd.redSqr();
- var jyd4 = jyd2.redSqr();
- var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
- var t1 = jx.redMul(jyd2);
- var nx = c.redSqr().redISub(t1.redAdd(t1));
- var t2 = t1.redISub(nx);
- var dny = c.redMul(t2);
- dny = dny.redIAdd(dny).redISub(jyd4);
- var nz = jyd.redMul(jz);
- if (i + 1 < pow)
- jz4 = jz4.redMul(jyd4);
- jx = nx;
- jz = nz;
- jyd = dny;
- }
- return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
- };
- JPoint.prototype.dbl = function dbl() {
- if (this.isInfinity())
- return this;
- if (this.curve.zeroA)
- return this._zeroDbl();
- else if (this.curve.threeA)
- return this._threeDbl();
- else
- return this._dbl();
- };
- JPoint.prototype._zeroDbl = function _zeroDbl() {
- var nx;
- var ny;
- var nz;
- // Z = 1
- if (this.zOne) {
- // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
- // #doubling-mdbl-2007-bl
- // 1M + 5S + 14A
- // XX = X1^2
- var xx = this.x.redSqr();
- // YY = Y1^2
- var yy = this.y.redSqr();
- // YYYY = YY^2
- var yyyy = yy.redSqr();
- // S = 2 * ((X1 + YY)^2 - XX - YYYY)
- var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
- s = s.redIAdd(s);
- // M = 3 * XX + a; a = 0
- var m = xx.redAdd(xx).redIAdd(xx);
- // T = M ^ 2 - 2*S
- var t = m.redSqr().redISub(s).redISub(s);
- // 8 * YYYY
- var yyyy8 = yyyy.redIAdd(yyyy);
- yyyy8 = yyyy8.redIAdd(yyyy8);
- yyyy8 = yyyy8.redIAdd(yyyy8);
- // X3 = T
- nx = t;
- // Y3 = M * (S - T) - 8 * YYYY
- ny = m.redMul(s.redISub(t)).redISub(yyyy8);
- // Z3 = 2*Y1
- nz = this.y.redAdd(this.y);
- } else {
- // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
- // #doubling-dbl-2009-l
- // 2M + 5S + 13A
- // A = X1^2
- var a = this.x.redSqr();
- // B = Y1^2
- var b = this.y.redSqr();
- // C = B^2
- var c = b.redSqr();
- // D = 2 * ((X1 + B)^2 - A - C)
- var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
- d = d.redIAdd(d);
- // E = 3 * A
- var e = a.redAdd(a).redIAdd(a);
- // F = E^2
- var f = e.redSqr();
- // 8 * C
- var c8 = c.redIAdd(c);
- c8 = c8.redIAdd(c8);
- c8 = c8.redIAdd(c8);
- // X3 = F - 2 * D
- nx = f.redISub(d).redISub(d);
- // Y3 = E * (D - X3) - 8 * C
- ny = e.redMul(d.redISub(nx)).redISub(c8);
- // Z3 = 2 * Y1 * Z1
- nz = this.y.redMul(this.z);
- nz = nz.redIAdd(nz);
- }
- return this.curve.jpoint(nx, ny, nz);
- };
- JPoint.prototype._threeDbl = function _threeDbl() {
- var nx;
- var ny;
- var nz;
- // Z = 1
- if (this.zOne) {
- // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
- // #doubling-mdbl-2007-bl
- // 1M + 5S + 15A
- // XX = X1^2
- var xx = this.x.redSqr();
- // YY = Y1^2
- var yy = this.y.redSqr();
- // YYYY = YY^2
- var yyyy = yy.redSqr();
- // S = 2 * ((X1 + YY)^2 - XX - YYYY)
- var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
- s = s.redIAdd(s);
- // M = 3 * XX + a
- var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
- // T = M^2 - 2 * S
- var t = m.redSqr().redISub(s).redISub(s);
- // X3 = T
- nx = t;
- // Y3 = M * (S - T) - 8 * YYYY
- var yyyy8 = yyyy.redIAdd(yyyy);
- yyyy8 = yyyy8.redIAdd(yyyy8);
- yyyy8 = yyyy8.redIAdd(yyyy8);
- ny = m.redMul(s.redISub(t)).redISub(yyyy8);
- // Z3 = 2 * Y1
- nz = this.y.redAdd(this.y);
- } else {
- // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
- // 3M + 5S
- // delta = Z1^2
- var delta = this.z.redSqr();
- // gamma = Y1^2
- var gamma = this.y.redSqr();
- // beta = X1 * gamma
- var beta = this.x.redMul(gamma);
- // alpha = 3 * (X1 - delta) * (X1 + delta)
- var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
- alpha = alpha.redAdd(alpha).redIAdd(alpha);
- // X3 = alpha^2 - 8 * beta
- var beta4 = beta.redIAdd(beta);
- beta4 = beta4.redIAdd(beta4);
- var beta8 = beta4.redAdd(beta4);
- nx = alpha.redSqr().redISub(beta8);
- // Z3 = (Y1 + Z1)^2 - gamma - delta
- nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
- // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
- var ggamma8 = gamma.redSqr();
- ggamma8 = ggamma8.redIAdd(ggamma8);
- ggamma8 = ggamma8.redIAdd(ggamma8);
- ggamma8 = ggamma8.redIAdd(ggamma8);
- ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
- }
- return this.curve.jpoint(nx, ny, nz);
- };
- JPoint.prototype._dbl = function _dbl() {
- var a = this.curve.a;
- // 4M + 6S + 10A
- var jx = this.x;
- var jy = this.y;
- var jz = this.z;
- var jz4 = jz.redSqr().redSqr();
- var jx2 = jx.redSqr();
- var jy2 = jy.redSqr();
- var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
- var jxd4 = jx.redAdd(jx);
- jxd4 = jxd4.redIAdd(jxd4);
- var t1 = jxd4.redMul(jy2);
- var nx = c.redSqr().redISub(t1.redAdd(t1));
- var t2 = t1.redISub(nx);
- var jyd8 = jy2.redSqr();
- jyd8 = jyd8.redIAdd(jyd8);
- jyd8 = jyd8.redIAdd(jyd8);
- jyd8 = jyd8.redIAdd(jyd8);
- var ny = c.redMul(t2).redISub(jyd8);
- var nz = jy.redAdd(jy).redMul(jz);
- return this.curve.jpoint(nx, ny, nz);
- };
- JPoint.prototype.trpl = function trpl() {
- if (!this.curve.zeroA)
- return this.dbl().add(this);
- // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
- // 5M + 10S + ...
- // XX = X1^2
- var xx = this.x.redSqr();
- // YY = Y1^2
- var yy = this.y.redSqr();
- // ZZ = Z1^2
- var zz = this.z.redSqr();
- // YYYY = YY^2
- var yyyy = yy.redSqr();
- // M = 3 * XX + a * ZZ2; a = 0
- var m = xx.redAdd(xx).redIAdd(xx);
- // MM = M^2
- var mm = m.redSqr();
- // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
- var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
- e = e.redIAdd(e);
- e = e.redAdd(e).redIAdd(e);
- e = e.redISub(mm);
- // EE = E^2
- var ee = e.redSqr();
- // T = 16*YYYY
- var t = yyyy.redIAdd(yyyy);
- t = t.redIAdd(t);
- t = t.redIAdd(t);
- t = t.redIAdd(t);
- // U = (M + E)^2 - MM - EE - T
- var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
- // X3 = 4 * (X1 * EE - 4 * YY * U)
- var yyu4 = yy.redMul(u);
- yyu4 = yyu4.redIAdd(yyu4);
- yyu4 = yyu4.redIAdd(yyu4);
- var nx = this.x.redMul(ee).redISub(yyu4);
- nx = nx.redIAdd(nx);
- nx = nx.redIAdd(nx);
- // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
- var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
- ny = ny.redIAdd(ny);
- ny = ny.redIAdd(ny);
- ny = ny.redIAdd(ny);
- // Z3 = (Z1 + E)^2 - ZZ - EE
- var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
- return this.curve.jpoint(nx, ny, nz);
- };
- JPoint.prototype.mul = function mul(k, kbase) {
- k = new bn(k, kbase);
- return this.curve._wnafMul(this, k);
- };
- JPoint.prototype.eq = function eq(p) {
- if (p.type === 'affine')
- return this.eq(p.toJ());
- if (this === p)
- return true;
- // x1 * z2^2 == x2 * z1^2
- var z2 = this.z.redSqr();
- var pz2 = p.z.redSqr();
- if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
- return false;
- // y1 * z2^3 == y2 * z1^3
- var z3 = z2.redMul(this.z);
- var pz3 = pz2.redMul(p.z);
- return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
- };
- JPoint.prototype.eqXToP = function eqXToP(x) {
- var zs = this.z.redSqr();
- var rx = x.toRed(this.curve.red).redMul(zs);
- if (this.x.cmp(rx) === 0)
- return true;
- var xc = x.clone();
- var t = this.curve.redN.redMul(zs);
- for (;;) {
- xc.iadd(this.curve.n);
- if (xc.cmp(this.curve.p) >= 0)
- return false;
- rx.redIAdd(t);
- if (this.x.cmp(rx) === 0)
- return true;
- }
- };
- JPoint.prototype.inspect = function inspect() {
- if (this.isInfinity())
- return '<EC JPoint Infinity>';
- return '<EC JPoint x: ' + this.x.toString(16, 2) +
- ' y: ' + this.y.toString(16, 2) +
- ' z: ' + this.z.toString(16, 2) + '>';
- };
- JPoint.prototype.isInfinity = function isInfinity() {
- // XXX This code assumes that zero is always zero in red
- return this.z.cmpn(0) === 0;
- };
- var curve_1 = createCommonjsModule(function (module, exports) {
- 'use strict';
- var curve = exports;
- curve.base = base;
- curve.short = short_1;
- curve.mont = /*RicMoo:ethers:require(./mont)*/(null);
- curve.edwards = /*RicMoo:ethers:require(./edwards)*/(null);
- });
- 'use strict';
- var inherits_1 = inherits_browser;
- function isSurrogatePair(msg, i) {
- if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) {
- return false;
- }
- if (i < 0 || i + 1 >= msg.length) {
- return false;
- }
- return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00;
- }
- function toArray(msg, enc) {
- if (Array.isArray(msg))
- return msg.slice();
- if (!msg)
- return [];
- var res = [];
- if (typeof msg === 'string') {
- if (!enc) {
- // Inspired by stringToUtf8ByteArray() in closure-library by Google
- // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
- // Apache License 2.0
- // https://github.com/google/closure-library/blob/master/LICENSE
- var p = 0;
- for (var i = 0; i < msg.length; i++) {
- var c = msg.charCodeAt(i);
- if (c < 128) {
- res[p++] = c;
- } else if (c < 2048) {
- res[p++] = (c >> 6) | 192;
- res[p++] = (c & 63) | 128;
- } else if (isSurrogatePair(msg, i)) {
- c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF);
- res[p++] = (c >> 18) | 240;
- res[p++] = ((c >> 12) & 63) | 128;
- res[p++] = ((c >> 6) & 63) | 128;
- res[p++] = (c & 63) | 128;
- } else {
- res[p++] = (c >> 12) | 224;
- res[p++] = ((c >> 6) & 63) | 128;
- res[p++] = (c & 63) | 128;
- }
- }
- } else if (enc === 'hex') {
- msg = msg.replace(/[^a-z0-9]+/ig, '');
- if (msg.length % 2 !== 0)
- msg = '0' + msg;
- for (i = 0; i < msg.length; i += 2)
- res.push(parseInt(msg[i] + msg[i + 1], 16));
- }
- } else {
- for (i = 0; i < msg.length; i++)
- res[i] = msg[i] | 0;
- }
- return res;
- }
- var toArray_1 = toArray;
- function toHex(msg) {
- var res = '';
- for (var i = 0; i < msg.length; i++)
- res += zero2(msg[i].toString(16));
- return res;
- }
- var toHex_1 = toHex;
- function htonl(w) {
- var res = (w >>> 24) |
- ((w >>> 8) & 0xff00) |
- ((w << 8) & 0xff0000) |
- ((w & 0xff) << 24);
- return res >>> 0;
- }
- var htonl_1 = htonl;
- function toHex32(msg, endian) {
- var res = '';
- for (var i = 0; i < msg.length; i++) {
- var w = msg[i];
- if (endian === 'little')
- w = htonl(w);
- res += zero8(w.toString(16));
- }
- return res;
- }
- var toHex32_1 = toHex32;
- function zero2(word) {
- if (word.length === 1)
- return '0' + word;
- else
- return word;
- }
- var zero2_1 = zero2;
- function zero8(word) {
- if (word.length === 7)
- return '0' + word;
- else if (word.length === 6)
- return '00' + word;
- else if (word.length === 5)
- return '000' + word;
- else if (word.length === 4)
- return '0000' + word;
- else if (word.length === 3)
- return '00000' + word;
- else if (word.length === 2)
- return '000000' + word;
- else if (word.length === 1)
- return '0000000' + word;
- else
- return word;
- }
- var zero8_1 = zero8;
- function join32(msg, start, end, endian) {
- var len = end - start;
- minimalisticAssert(len % 4 === 0);
- var res = new Array(len / 4);
- for (var i = 0, k = start; i < res.length; i++, k += 4) {
- var w;
- if (endian === 'big')
- w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
- else
- w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
- res[i] = w >>> 0;
- }
- return res;
- }
- var join32_1 = join32;
- function split32(msg, endian) {
- var res = new Array(msg.length * 4);
- for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
- var m = msg[i];
- if (endian === 'big') {
- res[k] = m >>> 24;
- res[k + 1] = (m >>> 16) & 0xff;
- res[k + 2] = (m >>> 8) & 0xff;
- res[k + 3] = m & 0xff;
- } else {
- res[k + 3] = m >>> 24;
- res[k + 2] = (m >>> 16) & 0xff;
- res[k + 1] = (m >>> 8) & 0xff;
- res[k] = m & 0xff;
- }
- }
- return res;
- }
- var split32_1 = split32;
- function rotr32(w, b) {
- return (w >>> b) | (w << (32 - b));
- }
- var rotr32_1 = rotr32;
- function rotl32(w, b) {
- return (w << b) | (w >>> (32 - b));
- }
- var rotl32_1 = rotl32;
- function sum32(a, b) {
- return (a + b) >>> 0;
- }
- var sum32_1 = sum32;
- function sum32_3(a, b, c) {
- return (a + b + c) >>> 0;
- }
- var sum32_3_1 = sum32_3;
- function sum32_4(a, b, c, d) {
- return (a + b + c + d) >>> 0;
- }
- var sum32_4_1 = sum32_4;
- function sum32_5(a, b, c, d, e) {
- return (a + b + c + d + e) >>> 0;
- }
- var sum32_5_1 = sum32_5;
- function sum64(buf, pos, ah, al) {
- var bh = buf[pos];
- var bl = buf[pos + 1];
- var lo = (al + bl) >>> 0;
- var hi = (lo < al ? 1 : 0) + ah + bh;
- buf[pos] = hi >>> 0;
- buf[pos + 1] = lo;
- }
- var sum64_1 = sum64;
- function sum64_hi(ah, al, bh, bl) {
- var lo = (al + bl) >>> 0;
- var hi = (lo < al ? 1 : 0) + ah + bh;
- return hi >>> 0;
- }
- var sum64_hi_1 = sum64_hi;
- function sum64_lo(ah, al, bh, bl) {
- var lo = al + bl;
- return lo >>> 0;
- }
- var sum64_lo_1 = sum64_lo;
- function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
- var carry = 0;
- var lo = al;
- lo = (lo + bl) >>> 0;
- carry += lo < al ? 1 : 0;
- lo = (lo + cl) >>> 0;
- carry += lo < cl ? 1 : 0;
- lo = (lo + dl) >>> 0;
- carry += lo < dl ? 1 : 0;
- var hi = ah + bh + ch + dh + carry;
- return hi >>> 0;
- }
- var sum64_4_hi_1 = sum64_4_hi;
- function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
- var lo = al + bl + cl + dl;
- return lo >>> 0;
- }
- var sum64_4_lo_1 = sum64_4_lo;
- function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
- var carry = 0;
- var lo = al;
- lo = (lo + bl) >>> 0;
- carry += lo < al ? 1 : 0;
- lo = (lo + cl) >>> 0;
- carry += lo < cl ? 1 : 0;
- lo = (lo + dl) >>> 0;
- carry += lo < dl ? 1 : 0;
- lo = (lo + el) >>> 0;
- carry += lo < el ? 1 : 0;
- var hi = ah + bh + ch + dh + eh + carry;
- return hi >>> 0;
- }
- var sum64_5_hi_1 = sum64_5_hi;
- function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
- var lo = al + bl + cl + dl + el;
- return lo >>> 0;
- }
- var sum64_5_lo_1 = sum64_5_lo;
- function rotr64_hi(ah, al, num) {
- var r = (al << (32 - num)) | (ah >>> num);
- return r >>> 0;
- }
- var rotr64_hi_1 = rotr64_hi;
- function rotr64_lo(ah, al, num) {
- var r = (ah << (32 - num)) | (al >>> num);
- return r >>> 0;
- }
- var rotr64_lo_1 = rotr64_lo;
- function shr64_hi(ah, al, num) {
- return ah >>> num;
- }
- var shr64_hi_1 = shr64_hi;
- function shr64_lo(ah, al, num) {
- var r = (ah << (32 - num)) | (al >>> num);
- return r >>> 0;
- }
- var shr64_lo_1 = shr64_lo;
- var utils = {
- inherits: inherits_1,
- toArray: toArray_1,
- toHex: toHex_1,
- htonl: htonl_1,
- toHex32: toHex32_1,
- zero2: zero2_1,
- zero8: zero8_1,
- join32: join32_1,
- split32: split32_1,
- rotr32: rotr32_1,
- rotl32: rotl32_1,
- sum32: sum32_1,
- sum32_3: sum32_3_1,
- sum32_4: sum32_4_1,
- sum32_5: sum32_5_1,
- sum64: sum64_1,
- sum64_hi: sum64_hi_1,
- sum64_lo: sum64_lo_1,
- sum64_4_hi: sum64_4_hi_1,
- sum64_4_lo: sum64_4_lo_1,
- sum64_5_hi: sum64_5_hi_1,
- sum64_5_lo: sum64_5_lo_1,
- rotr64_hi: rotr64_hi_1,
- rotr64_lo: rotr64_lo_1,
- shr64_hi: shr64_hi_1,
- shr64_lo: shr64_lo_1
- };
- 'use strict';
- function BlockHash() {
- this.pending = null;
- this.pendingTotal = 0;
- this.blockSize = this.constructor.blockSize;
- this.outSize = this.constructor.outSize;
- this.hmacStrength = this.constructor.hmacStrength;
- this.padLength = this.constructor.padLength / 8;
- this.endian = 'big';
- this._delta8 = this.blockSize / 8;
- this._delta32 = this.blockSize / 32;
- }
- var BlockHash_1 = BlockHash;
- BlockHash.prototype.update = function update(msg, enc) {
- // Convert message to array, pad it, and join into 32bit blocks
- msg = utils.toArray(msg, enc);
- if (!this.pending)
- this.pending = msg;
- else
- this.pending = this.pending.concat(msg);
- this.pendingTotal += msg.length;
- // Enough data, try updating
- if (this.pending.length >= this._delta8) {
- msg = this.pending;
- // Process pending data in blocks
- var r = msg.length % this._delta8;
- this.pending = msg.slice(msg.length - r, msg.length);
- if (this.pending.length === 0)
- this.pending = null;
- msg = utils.join32(msg, 0, msg.length - r, this.endian);
- for (var i = 0; i < msg.length; i += this._delta32)
- this._update(msg, i, i + this._delta32);
- }
- return this;
- };
- BlockHash.prototype.digest = function digest(enc) {
- this.update(this._pad());
- minimalisticAssert(this.pending === null);
- return this._digest(enc);
- };
- BlockHash.prototype._pad = function pad() {
- var len = this.pendingTotal;
- var bytes = this._delta8;
- var k = bytes - ((len + this.padLength) % bytes);
- var res = new Array(k + this.padLength);
- res[0] = 0x80;
- for (var i = 1; i < k; i++)
- res[i] = 0;
- // Append length
- len <<= 3;
- if (this.endian === 'big') {
- for (var t = 8; t < this.padLength; t++)
- res[i++] = 0;
- res[i++] = 0;
- res[i++] = 0;
- res[i++] = 0;
- res[i++] = 0;
- res[i++] = (len >>> 24) & 0xff;
- res[i++] = (len >>> 16) & 0xff;
- res[i++] = (len >>> 8) & 0xff;
- res[i++] = len & 0xff;
- } else {
- res[i++] = len & 0xff;
- res[i++] = (len >>> 8) & 0xff;
- res[i++] = (len >>> 16) & 0xff;
- res[i++] = (len >>> 24) & 0xff;
- res[i++] = 0;
- res[i++] = 0;
- res[i++] = 0;
- res[i++] = 0;
- for (t = 8; t < this.padLength; t++)
- res[i++] = 0;
- }
- return res;
- };
- var common = {
- BlockHash: BlockHash_1
- };
- 'use strict';
- var rotr32$1 = utils.rotr32;
- function ft_1(s, x, y, z) {
- if (s === 0)
- return ch32(x, y, z);
- if (s === 1 || s === 3)
- return p32(x, y, z);
- if (s === 2)
- return maj32(x, y, z);
- }
- var ft_1_1 = ft_1;
- function ch32(x, y, z) {
- return (x & y) ^ ((~x) & z);
- }
- var ch32_1 = ch32;
- function maj32(x, y, z) {
- return (x & y) ^ (x & z) ^ (y & z);
- }
- var maj32_1 = maj32;
- function p32(x, y, z) {
- return x ^ y ^ z;
- }
- var p32_1 = p32;
- function s0_256(x) {
- return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22);
- }
- var s0_256_1 = s0_256;
- function s1_256(x) {
- return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25);
- }
- var s1_256_1 = s1_256;
- function g0_256(x) {
- return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ (x >>> 3);
- }
- var g0_256_1 = g0_256;
- function g1_256(x) {
- return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ (x >>> 10);
- }
- var g1_256_1 = g1_256;
- var common$1 = {
- ft_1: ft_1_1,
- ch32: ch32_1,
- maj32: maj32_1,
- p32: p32_1,
- s0_256: s0_256_1,
- s1_256: s1_256_1,
- g0_256: g0_256_1,
- g1_256: g1_256_1
- };
- 'use strict';
- var rotl32$1 = utils.rotl32;
- var sum32$1 = utils.sum32;
- var sum32_5$1 = utils.sum32_5;
- var ft_1$1 = common$1.ft_1;
- var BlockHash$1 = common.BlockHash;
- var sha1_K = [
- 0x5A827999, 0x6ED9EBA1,
- 0x8F1BBCDC, 0xCA62C1D6
- ];
- function SHA1() {
- if (!(this instanceof SHA1))
- return new SHA1();
- BlockHash$1.call(this);
- this.h = [
- 0x67452301, 0xefcdab89, 0x98badcfe,
- 0x10325476, 0xc3d2e1f0 ];
- this.W = new Array(80);
- }
- utils.inherits(SHA1, BlockHash$1);
- var _1 = SHA1;
- SHA1.blockSize = 512;
- SHA1.outSize = 160;
- SHA1.hmacStrength = 80;
- SHA1.padLength = 64;
- SHA1.prototype._update = function _update(msg, start) {
- var W = this.W;
- for (var i = 0; i < 16; i++)
- W[i] = msg[start + i];
- for(; i < W.length; i++)
- W[i] = rotl32$1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
- var a = this.h[0];
- var b = this.h[1];
- var c = this.h[2];
- var d = this.h[3];
- var e = this.h[4];
- for (i = 0; i < W.length; i++) {
- var s = ~~(i / 20);
- var t = sum32_5$1(rotl32$1(a, 5), ft_1$1(s, b, c, d), e, W[i], sha1_K[s]);
- e = d;
- d = c;
- c = rotl32$1(b, 30);
- b = a;
- a = t;
- }
- this.h[0] = sum32$1(this.h[0], a);
- this.h[1] = sum32$1(this.h[1], b);
- this.h[2] = sum32$1(this.h[2], c);
- this.h[3] = sum32$1(this.h[3], d);
- this.h[4] = sum32$1(this.h[4], e);
- };
- SHA1.prototype._digest = function digest(enc) {
- if (enc === 'hex')
- return utils.toHex32(this.h, 'big');
- else
- return utils.split32(this.h, 'big');
- };
- 'use strict';
- var sum32$2 = utils.sum32;
- var sum32_4$1 = utils.sum32_4;
- var sum32_5$2 = utils.sum32_5;
- var ch32$1 = common$1.ch32;
- var maj32$1 = common$1.maj32;
- var s0_256$1 = common$1.s0_256;
- var s1_256$1 = common$1.s1_256;
- var g0_256$1 = common$1.g0_256;
- var g1_256$1 = common$1.g1_256;
- var BlockHash$2 = common.BlockHash;
- var sha256_K = [
- 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
- 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
- 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
- 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
- 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
- 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
- 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
- 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
- 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
- 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
- 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
- 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
- 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
- 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
- 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
- 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
- ];
- function SHA256() {
- if (!(this instanceof SHA256))
- return new SHA256();
- BlockHash$2.call(this);
- this.h = [
- 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
- 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
- ];
- this.k = sha256_K;
- this.W = new Array(64);
- }
- utils.inherits(SHA256, BlockHash$2);
- var _256 = SHA256;
- SHA256.blockSize = 512;
- SHA256.outSize = 256;
- SHA256.hmacStrength = 192;
- SHA256.padLength = 64;
- SHA256.prototype._update = function _update(msg, start) {
- var W = this.W;
- for (var i = 0; i < 16; i++)
- W[i] = msg[start + i];
- for (; i < W.length; i++)
- W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]);
- var a = this.h[0];
- var b = this.h[1];
- var c = this.h[2];
- var d = this.h[3];
- var e = this.h[4];
- var f = this.h[5];
- var g = this.h[6];
- var h = this.h[7];
- minimalisticAssert(this.k.length === W.length);
- for (i = 0; i < W.length; i++) {
- var T1 = sum32_5$2(h, s1_256$1(e), ch32$1(e, f, g), this.k[i], W[i]);
- var T2 = sum32$2(s0_256$1(a), maj32$1(a, b, c));
- h = g;
- g = f;
- f = e;
- e = sum32$2(d, T1);
- d = c;
- c = b;
- b = a;
- a = sum32$2(T1, T2);
- }
- this.h[0] = sum32$2(this.h[0], a);
- this.h[1] = sum32$2(this.h[1], b);
- this.h[2] = sum32$2(this.h[2], c);
- this.h[3] = sum32$2(this.h[3], d);
- this.h[4] = sum32$2(this.h[4], e);
- this.h[5] = sum32$2(this.h[5], f);
- this.h[6] = sum32$2(this.h[6], g);
- this.h[7] = sum32$2(this.h[7], h);
- };
- SHA256.prototype._digest = function digest(enc) {
- if (enc === 'hex')
- return utils.toHex32(this.h, 'big');
- else
- return utils.split32(this.h, 'big');
- };
- 'use strict';
- function SHA224() {
- if (!(this instanceof SHA224))
- return new SHA224();
- _256.call(this);
- this.h = [
- 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
- 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
- }
- utils.inherits(SHA224, _256);
- var _224 = SHA224;
- SHA224.blockSize = 512;
- SHA224.outSize = 224;
- SHA224.hmacStrength = 192;
- SHA224.padLength = 64;
- SHA224.prototype._digest = function digest(enc) {
- // Just truncate output
- if (enc === 'hex')
- return utils.toHex32(this.h.slice(0, 7), 'big');
- else
- return utils.split32(this.h.slice(0, 7), 'big');
- };
- 'use strict';
- var rotr64_hi$1 = utils.rotr64_hi;
- var rotr64_lo$1 = utils.rotr64_lo;
- var shr64_hi$1 = utils.shr64_hi;
- var shr64_lo$1 = utils.shr64_lo;
- var sum64$1 = utils.sum64;
- var sum64_hi$1 = utils.sum64_hi;
- var sum64_lo$1 = utils.sum64_lo;
- var sum64_4_hi$1 = utils.sum64_4_hi;
- var sum64_4_lo$1 = utils.sum64_4_lo;
- var sum64_5_hi$1 = utils.sum64_5_hi;
- var sum64_5_lo$1 = utils.sum64_5_lo;
- var BlockHash$3 = common.BlockHash;
- var sha512_K = [
- 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
- 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
- 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
- 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
- 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
- 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
- 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
- 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
- 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
- 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
- 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
- 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
- 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
- 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
- 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
- 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
- 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
- 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
- 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
- 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
- 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
- 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
- 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
- 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
- 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
- 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
- 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
- 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
- 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
- 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
- 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
- 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
- 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
- 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
- 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
- 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
- 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
- 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
- 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
- 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
- ];
- function SHA512() {
- if (!(this instanceof SHA512))
- return new SHA512();
- BlockHash$3.call(this);
- this.h = [
- 0x6a09e667, 0xf3bcc908,
- 0xbb67ae85, 0x84caa73b,
- 0x3c6ef372, 0xfe94f82b,
- 0xa54ff53a, 0x5f1d36f1,
- 0x510e527f, 0xade682d1,
- 0x9b05688c, 0x2b3e6c1f,
- 0x1f83d9ab, 0xfb41bd6b,
- 0x5be0cd19, 0x137e2179 ];
- this.k = sha512_K;
- this.W = new Array(160);
- }
- utils.inherits(SHA512, BlockHash$3);
- var _512 = SHA512;
- SHA512.blockSize = 1024;
- SHA512.outSize = 512;
- SHA512.hmacStrength = 192;
- SHA512.padLength = 128;
- SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
- var W = this.W;
- // 32 x 32bit words
- for (var i = 0; i < 32; i++)
- W[i] = msg[start + i];
- for (; i < W.length; i += 2) {
- var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
- var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
- var c1_hi = W[i - 14]; // i - 7
- var c1_lo = W[i - 13];
- var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
- var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
- var c3_hi = W[i - 32]; // i - 16
- var c3_lo = W[i - 31];
- W[i] = sum64_4_hi$1(
- c0_hi, c0_lo,
- c1_hi, c1_lo,
- c2_hi, c2_lo,
- c3_hi, c3_lo);
- W[i + 1] = sum64_4_lo$1(
- c0_hi, c0_lo,
- c1_hi, c1_lo,
- c2_hi, c2_lo,
- c3_hi, c3_lo);
- }
- };
- SHA512.prototype._update = function _update(msg, start) {
- this._prepareBlock(msg, start);
- var W = this.W;
- var ah = this.h[0];
- var al = this.h[1];
- var bh = this.h[2];
- var bl = this.h[3];
- var ch = this.h[4];
- var cl = this.h[5];
- var dh = this.h[6];
- var dl = this.h[7];
- var eh = this.h[8];
- var el = this.h[9];
- var fh = this.h[10];
- var fl = this.h[11];
- var gh = this.h[12];
- var gl = this.h[13];
- var hh = this.h[14];
- var hl = this.h[15];
- minimalisticAssert(this.k.length === W.length);
- for (var i = 0; i < W.length; i += 2) {
- var c0_hi = hh;
- var c0_lo = hl;
- var c1_hi = s1_512_hi(eh, el);
- var c1_lo = s1_512_lo(eh, el);
- var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);
- var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
- var c3_hi = this.k[i];
- var c3_lo = this.k[i + 1];
- var c4_hi = W[i];
- var c4_lo = W[i + 1];
- var T1_hi = sum64_5_hi$1(
- c0_hi, c0_lo,
- c1_hi, c1_lo,
- c2_hi, c2_lo,
- c3_hi, c3_lo,
- c4_hi, c4_lo);
- var T1_lo = sum64_5_lo$1(
- c0_hi, c0_lo,
- c1_hi, c1_lo,
- c2_hi, c2_lo,
- c3_hi, c3_lo,
- c4_hi, c4_lo);
- c0_hi = s0_512_hi(ah, al);
- c0_lo = s0_512_lo(ah, al);
- c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);
- c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
- var T2_hi = sum64_hi$1(c0_hi, c0_lo, c1_hi, c1_lo);
- var T2_lo = sum64_lo$1(c0_hi, c0_lo, c1_hi, c1_lo);
- hh = gh;
- hl = gl;
- gh = fh;
- gl = fl;
- fh = eh;
- fl = el;
- eh = sum64_hi$1(dh, dl, T1_hi, T1_lo);
- el = sum64_lo$1(dl, dl, T1_hi, T1_lo);
- dh = ch;
- dl = cl;
- ch = bh;
- cl = bl;
- bh = ah;
- bl = al;
- ah = sum64_hi$1(T1_hi, T1_lo, T2_hi, T2_lo);
- al = sum64_lo$1(T1_hi, T1_lo, T2_hi, T2_lo);
- }
- sum64$1(this.h, 0, ah, al);
- sum64$1(this.h, 2, bh, bl);
- sum64$1(this.h, 4, ch, cl);
- sum64$1(this.h, 6, dh, dl);
- sum64$1(this.h, 8, eh, el);
- sum64$1(this.h, 10, fh, fl);
- sum64$1(this.h, 12, gh, gl);
- sum64$1(this.h, 14, hh, hl);
- };
- SHA512.prototype._digest = function digest(enc) {
- if (enc === 'hex')
- return utils.toHex32(this.h, 'big');
- else
- return utils.split32(this.h, 'big');
- };
- function ch64_hi(xh, xl, yh, yl, zh) {
- var r = (xh & yh) ^ ((~xh) & zh);
- if (r < 0)
- r += 0x100000000;
- return r;
- }
- function ch64_lo(xh, xl, yh, yl, zh, zl) {
- var r = (xl & yl) ^ ((~xl) & zl);
- if (r < 0)
- r += 0x100000000;
- return r;
- }
- function maj64_hi(xh, xl, yh, yl, zh) {
- var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
- if (r < 0)
- r += 0x100000000;
- return r;
- }
- function maj64_lo(xh, xl, yh, yl, zh, zl) {
- var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
- if (r < 0)
- r += 0x100000000;
- return r;
- }
- function s0_512_hi(xh, xl) {
- var c0_hi = rotr64_hi$1(xh, xl, 28);
- var c1_hi = rotr64_hi$1(xl, xh, 2); // 34
- var c2_hi = rotr64_hi$1(xl, xh, 7); // 39
- var r = c0_hi ^ c1_hi ^ c2_hi;
- if (r < 0)
- r += 0x100000000;
- return r;
- }
- function s0_512_lo(xh, xl) {
- var c0_lo = rotr64_lo$1(xh, xl, 28);
- var c1_lo = rotr64_lo$1(xl, xh, 2); // 34
- var c2_lo = rotr64_lo$1(xl, xh, 7); // 39
- var r = c0_lo ^ c1_lo ^ c2_lo;
- if (r < 0)
- r += 0x100000000;
- return r;
- }
- function s1_512_hi(xh, xl) {
- var c0_hi = rotr64_hi$1(xh, xl, 14);
- var c1_hi = rotr64_hi$1(xh, xl, 18);
- var c2_hi = rotr64_hi$1(xl, xh, 9); // 41
- var r = c0_hi ^ c1_hi ^ c2_hi;
- if (r < 0)
- r += 0x100000000;
- return r;
- }
- function s1_512_lo(xh, xl) {
- var c0_lo = rotr64_lo$1(xh, xl, 14);
- var c1_lo = rotr64_lo$1(xh, xl, 18);
- var c2_lo = rotr64_lo$1(xl, xh, 9); // 41
- var r = c0_lo ^ c1_lo ^ c2_lo;
- if (r < 0)
- r += 0x100000000;
- return r;
- }
- function g0_512_hi(xh, xl) {
- var c0_hi = rotr64_hi$1(xh, xl, 1);
- var c1_hi = rotr64_hi$1(xh, xl, 8);
- var c2_hi = shr64_hi$1(xh, xl, 7);
- var r = c0_hi ^ c1_hi ^ c2_hi;
- if (r < 0)
- r += 0x100000000;
- return r;
- }
- function g0_512_lo(xh, xl) {
- var c0_lo = rotr64_lo$1(xh, xl, 1);
- var c1_lo = rotr64_lo$1(xh, xl, 8);
- var c2_lo = shr64_lo$1(xh, xl, 7);
- var r = c0_lo ^ c1_lo ^ c2_lo;
- if (r < 0)
- r += 0x100000000;
- return r;
- }
- function g1_512_hi(xh, xl) {
- var c0_hi = rotr64_hi$1(xh, xl, 19);
- var c1_hi = rotr64_hi$1(xl, xh, 29); // 61
- var c2_hi = shr64_hi$1(xh, xl, 6);
- var r = c0_hi ^ c1_hi ^ c2_hi;
- if (r < 0)
- r += 0x100000000;
- return r;
- }
- function g1_512_lo(xh, xl) {
- var c0_lo = rotr64_lo$1(xh, xl, 19);
- var c1_lo = rotr64_lo$1(xl, xh, 29); // 61
- var c2_lo = shr64_lo$1(xh, xl, 6);
- var r = c0_lo ^ c1_lo ^ c2_lo;
- if (r < 0)
- r += 0x100000000;
- return r;
- }
- 'use strict';
- function SHA384() {
- if (!(this instanceof SHA384))
- return new SHA384();
- _512.call(this);
- this.h = [
- 0xcbbb9d5d, 0xc1059ed8,
- 0x629a292a, 0x367cd507,
- 0x9159015a, 0x3070dd17,
- 0x152fecd8, 0xf70e5939,
- 0x67332667, 0xffc00b31,
- 0x8eb44a87, 0x68581511,
- 0xdb0c2e0d, 0x64f98fa7,
- 0x47b5481d, 0xbefa4fa4 ];
- }
- utils.inherits(SHA384, _512);
- var _384 = SHA384;
- SHA384.blockSize = 1024;
- SHA384.outSize = 384;
- SHA384.hmacStrength = 192;
- SHA384.padLength = 128;
- SHA384.prototype._digest = function digest(enc) {
- if (enc === 'hex')
- return utils.toHex32(this.h.slice(0, 12), 'big');
- else
- return utils.split32(this.h.slice(0, 12), 'big');
- };
- 'use strict';
- var sha1 = _1;
- var sha224 = _224;
- var sha256 = _256;
- var sha384 = _384;
- var sha512 = _512;
- var sha = {
- sha1: sha1,
- sha224: sha224,
- sha256: sha256,
- sha384: sha384,
- sha512: sha512
- };
- 'use strict';
- var rotl32$2 = utils.rotl32;
- var sum32$3 = utils.sum32;
- var sum32_3$1 = utils.sum32_3;
- var sum32_4$2 = utils.sum32_4;
- var BlockHash$4 = common.BlockHash;
- function RIPEMD160() {
- if (!(this instanceof RIPEMD160))
- return new RIPEMD160();
- BlockHash$4.call(this);
- this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
- this.endian = 'little';
- }
- utils.inherits(RIPEMD160, BlockHash$4);
- var ripemd160 = RIPEMD160;
- RIPEMD160.blockSize = 512;
- RIPEMD160.outSize = 160;
- RIPEMD160.hmacStrength = 192;
- RIPEMD160.padLength = 64;
- RIPEMD160.prototype._update = function update(msg, start) {
- var A = this.h[0];
- var B = this.h[1];
- var C = this.h[2];
- var D = this.h[3];
- var E = this.h[4];
- var Ah = A;
- var Bh = B;
- var Ch = C;
- var Dh = D;
- var Eh = E;
- for (var j = 0; j < 80; j++) {
- var T = sum32$3(
- rotl32$2(
- sum32_4$2(A, f(j, B, C, D), msg[r[j] + start], K(j)),
- s[j]),
- E);
- A = E;
- E = D;
- D = rotl32$2(C, 10);
- C = B;
- B = T;
- T = sum32$3(
- rotl32$2(
- sum32_4$2(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
- sh[j]),
- Eh);
- Ah = Eh;
- Eh = Dh;
- Dh = rotl32$2(Ch, 10);
- Ch = Bh;
- Bh = T;
- }
- T = sum32_3$1(this.h[1], C, Dh);
- this.h[1] = sum32_3$1(this.h[2], D, Eh);
- this.h[2] = sum32_3$1(this.h[3], E, Ah);
- this.h[3] = sum32_3$1(this.h[4], A, Bh);
- this.h[4] = sum32_3$1(this.h[0], B, Ch);
- this.h[0] = T;
- };
- RIPEMD160.prototype._digest = function digest(enc) {
- if (enc === 'hex')
- return utils.toHex32(this.h, 'little');
- else
- return utils.split32(this.h, 'little');
- };
- function f(j, x, y, z) {
- if (j <= 15)
- return x ^ y ^ z;
- else if (j <= 31)
- return (x & y) | ((~x) & z);
- else if (j <= 47)
- return (x | (~y)) ^ z;
- else if (j <= 63)
- return (x & z) | (y & (~z));
- else
- return x ^ (y | (~z));
- }
- function K(j) {
- if (j <= 15)
- return 0x00000000;
- else if (j <= 31)
- return 0x5a827999;
- else if (j <= 47)
- return 0x6ed9eba1;
- else if (j <= 63)
- return 0x8f1bbcdc;
- else
- return 0xa953fd4e;
- }
- function Kh(j) {
- if (j <= 15)
- return 0x50a28be6;
- else if (j <= 31)
- return 0x5c4dd124;
- else if (j <= 47)
- return 0x6d703ef3;
- else if (j <= 63)
- return 0x7a6d76e9;
- else
- return 0x00000000;
- }
- var r = [
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
- 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
- 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
- 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
- 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
- ];
- var rh = [
- 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
- 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
- 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
- 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
- 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
- ];
- var s = [
- 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
- 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
- 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
- 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
- 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
- ];
- var sh = [
- 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
- 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
- 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
- 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
- 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
- ];
- var ripemd = {
- ripemd160: ripemd160
- };
- 'use strict';
- function Hmac(hash, key, enc) {
- if (!(this instanceof Hmac))
- return new Hmac(hash, key, enc);
- this.Hash = hash;
- this.blockSize = hash.blockSize / 8;
- this.outSize = hash.outSize / 8;
- this.inner = null;
- this.outer = null;
- this._init(utils.toArray(key, enc));
- }
- var hmac = Hmac;
- Hmac.prototype._init = function init(key) {
- // Shorten key, if needed
- if (key.length > this.blockSize)
- key = new this.Hash().update(key).digest();
- minimalisticAssert(key.length <= this.blockSize);
- // Add padding to key
- for (var i = key.length; i < this.blockSize; i++)
- key.push(0);
- for (i = 0; i < key.length; i++)
- key[i] ^= 0x36;
- this.inner = new this.Hash().update(key);
- // 0x36 ^ 0x5c = 0x6a
- for (i = 0; i < key.length; i++)
- key[i] ^= 0x6a;
- this.outer = new this.Hash().update(key);
- };
- Hmac.prototype.update = function update(msg, enc) {
- this.inner.update(msg, enc);
- return this;
- };
- Hmac.prototype.digest = function digest(enc) {
- this.outer.update(this.inner.digest());
- return this.outer.digest(enc);
- };
- var hash_1 = createCommonjsModule(function (module, exports) {
- var hash = exports;
- hash.utils = utils;
- hash.common = common;
- hash.sha = sha;
- hash.ripemd = ripemd;
- hash.hmac = hmac;
- // Proxy hash functions to the main object
- hash.sha1 = hash.sha.sha1;
- hash.sha256 = hash.sha.sha256;
- hash.sha224 = hash.sha.sha224;
- hash.sha384 = hash.sha.sha384;
- hash.sha512 = hash.sha.sha512;
- hash.ripemd160 = hash.ripemd.ripemd160;
- });
- var curves_1 = createCommonjsModule(function (module, exports) {
- 'use strict';
- var curves = exports;
- var assert = utils_1$1.assert;
- function PresetCurve(options) {
- if (options.type === 'short')
- this.curve = new curve_1.short(options);
- else if (options.type === 'edwards')
- this.curve = new curve_1.edwards(options);
- else
- this.curve = new curve_1.mont(options);
- this.g = this.curve.g;
- this.n = this.curve.n;
- this.hash = options.hash;
- assert(this.g.validate(), 'Invalid curve');
- assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');
- }
- curves.PresetCurve = PresetCurve;
- function defineCurve(name, options) {
- Object.defineProperty(curves, name, {
- configurable: true,
- enumerable: true,
- get: function() {
- var curve = new PresetCurve(options);
- Object.defineProperty(curves, name, {
- configurable: true,
- enumerable: true,
- value: curve,
- });
- return curve;
- },
- });
- }
- defineCurve('p192', {
- type: 'short',
- prime: 'p192',
- p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
- a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
- b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
- n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
- hash: hash_1.sha256,
- gRed: false,
- g: [
- '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
- '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811',
- ],
- });
- defineCurve('p224', {
- type: 'short',
- prime: 'p224',
- p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
- a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
- b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
- n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
- hash: hash_1.sha256,
- gRed: false,
- g: [
- 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
- 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34',
- ],
- });
- defineCurve('p256', {
- type: 'short',
- prime: null,
- p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
- a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
- b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
- n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
- hash: hash_1.sha256,
- gRed: false,
- g: [
- '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
- '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5',
- ],
- });
- defineCurve('p384', {
- type: 'short',
- prime: null,
- p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
- 'fffffffe ffffffff 00000000 00000000 ffffffff',
- a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
- 'fffffffe ffffffff 00000000 00000000 fffffffc',
- b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
- '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
- n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
- 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
- hash: hash_1.sha384,
- gRed: false,
- g: [
- 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
- '5502f25d bf55296c 3a545e38 72760ab7',
- '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
- '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f',
- ],
- });
- defineCurve('p521', {
- type: 'short',
- prime: null,
- p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
- 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
- 'ffffffff ffffffff ffffffff ffffffff ffffffff',
- a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
- 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
- 'ffffffff ffffffff ffffffff ffffffff fffffffc',
- b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
- '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
- '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
- n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
- 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
- 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
- hash: hash_1.sha512,
- gRed: false,
- g: [
- '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
- '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
- 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
- '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
- '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
- '3fad0761 353c7086 a272c240 88be9476 9fd16650',
- ],
- });
- defineCurve('curve25519', {
- type: 'mont',
- prime: 'p25519',
- p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
- a: '76d06',
- b: '1',
- n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
- hash: hash_1.sha256,
- gRed: false,
- g: [
- '9',
- ],
- });
- defineCurve('ed25519', {
- type: 'edwards',
- prime: 'p25519',
- p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
- a: '-1',
- c: '1',
- // -121665 * (121666^(-1)) (mod P)
- d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
- n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
- hash: hash_1.sha256,
- gRed: false,
- g: [
- '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
- // 4/5
- '6666666666666666666666666666666666666666666666666666666666666658',
- ],
- });
- var pre;
- try {
- pre = /*RicMoo:ethers:require(./precomputed/secp256k1)*/(null).crash();
- } catch (e) {
- pre = undefined;
- }
- defineCurve('secp256k1', {
- type: 'short',
- prime: 'k256',
- p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
- a: '0',
- b: '7',
- n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
- h: '1',
- hash: hash_1.sha256,
- // Precomputed endomorphism
- beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
- lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
- basis: [
- {
- a: '3086d221a7d46bcde86c90e49284eb15',
- b: '-e4437ed6010e88286f547fa90abfe4c3',
- },
- {
- a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
- b: '3086d221a7d46bcde86c90e49284eb15',
- },
- ],
- gRed: false,
- g: [
- '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
- '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
- pre,
- ],
- });
- });
- 'use strict';
- function HmacDRBG(options) {
- if (!(this instanceof HmacDRBG))
- return new HmacDRBG(options);
- this.hash = options.hash;
- this.predResist = !!options.predResist;
- this.outLen = this.hash.outSize;
- this.minEntropy = options.minEntropy || this.hash.hmacStrength;
- this._reseed = null;
- this.reseedInterval = null;
- this.K = null;
- this.V = null;
- var entropy = utils_1.toArray(options.entropy, options.entropyEnc || 'hex');
- var nonce = utils_1.toArray(options.nonce, options.nonceEnc || 'hex');
- var pers = utils_1.toArray(options.pers, options.persEnc || 'hex');
- minimalisticAssert(entropy.length >= (this.minEntropy / 8),
- 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
- this._init(entropy, nonce, pers);
- }
- var hmacDrbg = HmacDRBG;
- HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
- var seed = entropy.concat(nonce).concat(pers);
- this.K = new Array(this.outLen / 8);
- this.V = new Array(this.outLen / 8);
- for (var i = 0; i < this.V.length; i++) {
- this.K[i] = 0x00;
- this.V[i] = 0x01;
- }
- this._update(seed);
- this._reseed = 1;
- this.reseedInterval = 0x1000000000000; // 2^48
- };
- HmacDRBG.prototype._hmac = function hmac() {
- return new hash_1.hmac(this.hash, this.K);
- };
- HmacDRBG.prototype._update = function update(seed) {
- var kmac = this._hmac()
- .update(this.V)
- .update([ 0x00 ]);
- if (seed)
- kmac = kmac.update(seed);
- this.K = kmac.digest();
- this.V = this._hmac().update(this.V).digest();
- if (!seed)
- return;
- this.K = this._hmac()
- .update(this.V)
- .update([ 0x01 ])
- .update(seed)
- .digest();
- this.V = this._hmac().update(this.V).digest();
- };
- HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
- // Optional entropy enc
- if (typeof entropyEnc !== 'string') {
- addEnc = add;
- add = entropyEnc;
- entropyEnc = null;
- }
- entropy = utils_1.toArray(entropy, entropyEnc);
- add = utils_1.toArray(add, addEnc);
- minimalisticAssert(entropy.length >= (this.minEntropy / 8),
- 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
- this._update(entropy.concat(add || []));
- this._reseed = 1;
- };
- HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
- if (this._reseed > this.reseedInterval)
- throw new Error('Reseed is required');
- // Optional encoding
- if (typeof enc !== 'string') {
- addEnc = add;
- add = enc;
- enc = null;
- }
- // Optional additional data
- if (add) {
- add = utils_1.toArray(add, addEnc || 'hex');
- this._update(add);
- }
- var temp = [];
- while (temp.length < len) {
- this.V = this._hmac().update(this.V).digest();
- temp = temp.concat(this.V);
- }
- var res = temp.slice(0, len);
- this._update(add);
- this._reseed++;
- return utils_1.encode(res, enc);
- };
- 'use strict';
- var assert$3 = utils_1$1.assert;
- function KeyPair(ec, options) {
- this.ec = ec;
- this.priv = null;
- this.pub = null;
- // KeyPair(ec, { priv: ..., pub: ... })
- if (options.priv)
- this._importPrivate(options.priv, options.privEnc);
- if (options.pub)
- this._importPublic(options.pub, options.pubEnc);
- }
- var key = KeyPair;
- KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
- if (pub instanceof KeyPair)
- return pub;
- return new KeyPair(ec, {
- pub: pub,
- pubEnc: enc,
- });
- };
- KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
- if (priv instanceof KeyPair)
- return priv;
- return new KeyPair(ec, {
- priv: priv,
- privEnc: enc,
- });
- };
- KeyPair.prototype.validate = function validate() {
- var pub = this.getPublic();
- if (pub.isInfinity())
- return { result: false, reason: 'Invalid public key' };
- if (!pub.validate())
- return { result: false, reason: 'Public key is not a point' };
- if (!pub.mul(this.ec.curve.n).isInfinity())
- return { result: false, reason: 'Public key * N != O' };
- return { result: true, reason: null };
- };
- KeyPair.prototype.getPublic = function getPublic(compact, enc) {
- // compact is optional argument
- if (typeof compact === 'string') {
- enc = compact;
- compact = null;
- }
- if (!this.pub)
- this.pub = this.ec.g.mul(this.priv);
- if (!enc)
- return this.pub;
- return this.pub.encode(enc, compact);
- };
- KeyPair.prototype.getPrivate = function getPrivate(enc) {
- if (enc === 'hex')
- return this.priv.toString(16, 2);
- else
- return this.priv;
- };
- KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
- this.priv = new bn(key, enc || 16);
- // Ensure that the priv won't be bigger than n, otherwise we may fail
- // in fixed multiplication method
- this.priv = this.priv.umod(this.ec.curve.n);
- };
- KeyPair.prototype._importPublic = function _importPublic(key, enc) {
- if (key.x || key.y) {
- // Montgomery points only have an `x` coordinate.
- // Weierstrass/Edwards points on the other hand have both `x` and
- // `y` coordinates.
- if (this.ec.curve.type === 'mont') {
- assert$3(key.x, 'Need x coordinate');
- } else if (this.ec.curve.type === 'short' ||
- this.ec.curve.type === 'edwards') {
- assert$3(key.x && key.y, 'Need both x and y coordinate');
- }
- this.pub = this.ec.curve.point(key.x, key.y);
- return;
- }
- this.pub = this.ec.curve.decodePoint(key, enc);
- };
- // ECDH
- KeyPair.prototype.derive = function derive(pub) {
- if(!pub.validate()) {
- assert$3(pub.validate(), 'public point not validated');
- }
- return pub.mul(this.priv).getX();
- };
- // ECDSA
- KeyPair.prototype.sign = function sign(msg, enc, options) {
- return this.ec.sign(msg, this, enc, options);
- };
- KeyPair.prototype.verify = function verify(msg, signature) {
- return this.ec.verify(msg, signature, this);
- };
- KeyPair.prototype.inspect = function inspect() {
- return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
- ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
- };
- 'use strict';
- var assert$4 = utils_1$1.assert;
- function Signature(options, enc) {
- if (options instanceof Signature)
- return options;
- if (this._importDER(options, enc))
- return;
- assert$4(options.r && options.s, 'Signature without r or s');
- this.r = new bn(options.r, 16);
- this.s = new bn(options.s, 16);
- if (options.recoveryParam === undefined)
- this.recoveryParam = null;
- else
- this.recoveryParam = options.recoveryParam;
- }
- var signature = Signature;
- function Position() {
- this.place = 0;
- }
- function getLength(buf, p) {
- var initial = buf[p.place++];
- if (!(initial & 0x80)) {
- return initial;
- }
- var octetLen = initial & 0xf;
- // Indefinite length or overflow
- if (octetLen === 0 || octetLen > 4) {
- return false;
- }
- var val = 0;
- for (var i = 0, off = p.place; i < octetLen; i++, off++) {
- val <<= 8;
- val |= buf[off];
- val >>>= 0;
- }
- // Leading zeroes
- if (val <= 0x7f) {
- return false;
- }
- p.place = off;
- return val;
- }
- function rmPadding(buf) {
- var i = 0;
- var len = buf.length - 1;
- while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
- i++;
- }
- if (i === 0) {
- return buf;
- }
- return buf.slice(i);
- }
- Signature.prototype._importDER = function _importDER(data, enc) {
- data = utils_1$1.toArray(data, enc);
- var p = new Position();
- if (data[p.place++] !== 0x30) {
- return false;
- }
- var len = getLength(data, p);
- if (len === false) {
- return false;
- }
- if ((len + p.place) !== data.length) {
- return false;
- }
- if (data[p.place++] !== 0x02) {
- return false;
- }
- var rlen = getLength(data, p);
- if (rlen === false) {
- return false;
- }
- var r = data.slice(p.place, rlen + p.place);
- p.place += rlen;
- if (data[p.place++] !== 0x02) {
- return false;
- }
- var slen = getLength(data, p);
- if (slen === false) {
- return false;
- }
- if (data.length !== slen + p.place) {
- return false;
- }
- var s = data.slice(p.place, slen + p.place);
- if (r[0] === 0) {
- if (r[1] & 0x80) {
- r = r.slice(1);
- } else {
- // Leading zeroes
- return false;
- }
- }
- if (s[0] === 0) {
- if (s[1] & 0x80) {
- s = s.slice(1);
- } else {
- // Leading zeroes
- return false;
- }
- }
- this.r = new bn(r);
- this.s = new bn(s);
- this.recoveryParam = null;
- return true;
- };
- function constructLength(arr, len) {
- if (len < 0x80) {
- arr.push(len);
- return;
- }
- var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
- arr.push(octets | 0x80);
- while (--octets) {
- arr.push((len >>> (octets << 3)) & 0xff);
- }
- arr.push(len);
- }
- Signature.prototype.toDER = function toDER(enc) {
- var r = this.r.toArray();
- var s = this.s.toArray();
- // Pad values
- if (r[0] & 0x80)
- r = [ 0 ].concat(r);
- // Pad values
- if (s[0] & 0x80)
- s = [ 0 ].concat(s);
- r = rmPadding(r);
- s = rmPadding(s);
- while (!s[0] && !(s[1] & 0x80)) {
- s = s.slice(1);
- }
- var arr = [ 0x02 ];
- constructLength(arr, r.length);
- arr = arr.concat(r);
- arr.push(0x02);
- constructLength(arr, s.length);
- var backHalf = arr.concat(s);
- var res = [ 0x30 ];
- constructLength(res, backHalf.length);
- res = res.concat(backHalf);
- return utils_1$1.encode(res, enc);
- };
- 'use strict';
- var rand = /*RicMoo:ethers:require(brorand)*/(function() { throw new Error('unsupported'); });
- var assert$5 = utils_1$1.assert;
- function EC(options) {
- if (!(this instanceof EC))
- return new EC(options);
- // Shortcut `elliptic.ec(curve-name)`
- if (typeof options === 'string') {
- assert$5(Object.prototype.hasOwnProperty.call(curves_1, options),
- 'Unknown curve ' + options);
- options = curves_1[options];
- }
- // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
- if (options instanceof curves_1.PresetCurve)
- options = { curve: options };
- this.curve = options.curve.curve;
- this.n = this.curve.n;
- this.nh = this.n.ushrn(1);
- this.g = this.curve.g;
- // Point on curve
- this.g = options.curve.g;
- this.g.precompute(options.curve.n.bitLength() + 1);
- // Hash for function for DRBG
- this.hash = options.hash || options.curve.hash;
- }
- var ec = EC;
- EC.prototype.keyPair = function keyPair(options) {
- return new key(this, options);
- };
- EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
- return key.fromPrivate(this, priv, enc);
- };
- EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
- return key.fromPublic(this, pub, enc);
- };
- EC.prototype.genKeyPair = function genKeyPair(options) {
- if (!options)
- options = {};
- // Instantiate Hmac_DRBG
- var drbg = new hmacDrbg({
- hash: this.hash,
- pers: options.pers,
- persEnc: options.persEnc || 'utf8',
- entropy: options.entropy || rand(this.hash.hmacStrength),
- entropyEnc: options.entropy && options.entropyEnc || 'utf8',
- nonce: this.n.toArray(),
- });
- var bytes = this.n.byteLength();
- var ns2 = this.n.sub(new bn(2));
- for (;;) {
- var priv = new bn(drbg.generate(bytes));
- if (priv.cmp(ns2) > 0)
- continue;
- priv.iaddn(1);
- return this.keyFromPrivate(priv);
- }
- };
- EC.prototype._truncateToN = function _truncateToN(msg, truncOnly) {
- var delta = msg.byteLength() * 8 - this.n.bitLength();
- if (delta > 0)
- msg = msg.ushrn(delta);
- if (!truncOnly && msg.cmp(this.n) >= 0)
- return msg.sub(this.n);
- else
- return msg;
- };
- EC.prototype.sign = function sign(msg, key, enc, options) {
- if (typeof enc === 'object') {
- options = enc;
- enc = null;
- }
- if (!options)
- options = {};
- key = this.keyFromPrivate(key, enc);
- msg = this._truncateToN(new bn(msg, 16));
- // Zero-extend key to provide enough entropy
- var bytes = this.n.byteLength();
- var bkey = key.getPrivate().toArray('be', bytes);
- // Zero-extend nonce to have the same byte size as N
- var nonce = msg.toArray('be', bytes);
- // Instantiate Hmac_DRBG
- var drbg = new hmacDrbg({
- hash: this.hash,
- entropy: bkey,
- nonce: nonce,
- pers: options.pers,
- persEnc: options.persEnc || 'utf8',
- });
- // Number of bytes to generate
- var ns1 = this.n.sub(new bn(1));
- for (var iter = 0; ; iter++) {
- var k = options.k ?
- options.k(iter) :
- new bn(drbg.generate(this.n.byteLength()));
- k = this._truncateToN(k, true);
- if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
- continue;
- var kp = this.g.mul(k);
- if (kp.isInfinity())
- continue;
- var kpX = kp.getX();
- var r = kpX.umod(this.n);
- if (r.cmpn(0) === 0)
- continue;
- var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
- s = s.umod(this.n);
- if (s.cmpn(0) === 0)
- continue;
- var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
- (kpX.cmp(r) !== 0 ? 2 : 0);
- // Use complement of `s`, if it is > `n / 2`
- if (options.canonical && s.cmp(this.nh) > 0) {
- s = this.n.sub(s);
- recoveryParam ^= 1;
- }
- return new signature({ r: r, s: s, recoveryParam: recoveryParam });
- }
- };
- EC.prototype.verify = function verify(msg, signature$1, key, enc) {
- msg = this._truncateToN(new bn(msg, 16));
- key = this.keyFromPublic(key, enc);
- signature$1 = new signature(signature$1, 'hex');
- // Perform primitive values validation
- var r = signature$1.r;
- var s = signature$1.s;
- if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
- return false;
- if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
- return false;
- // Validate signature
- var sinv = s.invm(this.n);
- var u1 = sinv.mul(msg).umod(this.n);
- var u2 = sinv.mul(r).umod(this.n);
- var p;
- if (!this.curve._maxwellTrick) {
- p = this.g.mulAdd(u1, key.getPublic(), u2);
- if (p.isInfinity())
- return false;
- return p.getX().umod(this.n).cmp(r) === 0;
- }
- // NOTE: Greg Maxwell's trick, inspired by:
- // https://git.io/vad3K
- p = this.g.jmulAdd(u1, key.getPublic(), u2);
- if (p.isInfinity())
- return false;
- // Compare `p.x` of Jacobian point with `r`,
- // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
- // inverse of `p.z^2`
- return p.eqXToP(r);
- };
- EC.prototype.recoverPubKey = function(msg, signature$1, j, enc) {
- assert$5((3 & j) === j, 'The recovery param is more than two bits');
- signature$1 = new signature(signature$1, enc);
- var n = this.n;
- var e = new bn(msg);
- var r = signature$1.r;
- var s = signature$1.s;
- // A set LSB signifies that the y-coordinate is odd
- var isYOdd = j & 1;
- var isSecondKey = j >> 1;
- if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
- throw new Error('Unable to find sencond key candinate');
- // 1.1. Let x = r + jn.
- if (isSecondKey)
- r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);
- else
- r = this.curve.pointFromX(r, isYOdd);
- var rInv = signature$1.r.invm(n);
- var s1 = n.sub(e).mul(rInv).umod(n);
- var s2 = s.mul(rInv).umod(n);
- // 1.6.1 Compute Q = r^-1 (sR - eG)
- // Q = r^-1 (sR + -eG)
- return this.g.mulAdd(s1, r, s2);
- };
- EC.prototype.getKeyRecoveryParam = function(e, signature$1, Q, enc) {
- signature$1 = new signature(signature$1, enc);
- if (signature$1.recoveryParam !== null)
- return signature$1.recoveryParam;
- for (var i = 0; i < 4; i++) {
- var Qprime;
- try {
- Qprime = this.recoverPubKey(e, signature$1, i);
- } catch (e) {
- continue;
- }
- if (Qprime.eq(Q))
- return i;
- }
- throw new Error('Unable to find valid recovery factor');
- };
- var elliptic_1 = createCommonjsModule(function (module, exports) {
- 'use strict';
- var elliptic = exports;
- elliptic.version = /*RicMoo:ethers*/{ version: "6.5.4" }.version;
- elliptic.utils = utils_1$1;
- elliptic.rand = /*RicMoo:ethers:require(brorand)*/(function() { throw new Error('unsupported'); });
- elliptic.curve = curve_1;
- elliptic.curves = curves_1;
- // Protocols
- elliptic.ec = ec;
- elliptic.eddsa = /*RicMoo:ethers:require(./elliptic/eddsa)*/(null);
- });
- var elliptic = createCommonjsModule(function (module, exports) {
- "use strict";
- var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.EC = void 0;
- var elliptic_1$1 = __importDefault(elliptic_1);
- var EC = elliptic_1$1.default.ec;
- exports.EC = EC;
- });
- var elliptic$1 = /*@__PURE__*/getDefaultExportFromCjs(elliptic);
- var _version$m = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "signing-key/5.6.0";
- });
- var _version$n = /*@__PURE__*/getDefaultExportFromCjs(_version$m);
- var lib$d = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.computePublicKey = exports.recoverPublicKey = exports.SigningKey = void 0;
- var logger = new lib.Logger(_version$m.version);
- var _curve = null;
- function getCurve() {
- if (!_curve) {
- _curve = new elliptic.EC("secp256k1");
- }
- return _curve;
- }
- var SigningKey = /** @class */ (function () {
- function SigningKey(privateKey) {
- (0, lib$3.defineReadOnly)(this, "curve", "secp256k1");
- (0, lib$3.defineReadOnly)(this, "privateKey", (0, lib$1.hexlify)(privateKey));
- var keyPair = getCurve().keyFromPrivate((0, lib$1.arrayify)(this.privateKey));
- (0, lib$3.defineReadOnly)(this, "publicKey", "0x" + keyPair.getPublic(false, "hex"));
- (0, lib$3.defineReadOnly)(this, "compressedPublicKey", "0x" + keyPair.getPublic(true, "hex"));
- (0, lib$3.defineReadOnly)(this, "_isSigningKey", true);
- }
- SigningKey.prototype._addPoint = function (other) {
- var p0 = getCurve().keyFromPublic((0, lib$1.arrayify)(this.publicKey));
- var p1 = getCurve().keyFromPublic((0, lib$1.arrayify)(other));
- return "0x" + p0.pub.add(p1.pub).encodeCompressed("hex");
- };
- SigningKey.prototype.signDigest = function (digest) {
- var keyPair = getCurve().keyFromPrivate((0, lib$1.arrayify)(this.privateKey));
- var digestBytes = (0, lib$1.arrayify)(digest);
- if (digestBytes.length !== 32) {
- logger.throwArgumentError("bad digest length", "digest", digest);
- }
- var signature = keyPair.sign(digestBytes, { canonical: true });
- return (0, lib$1.splitSignature)({
- recoveryParam: signature.recoveryParam,
- r: (0, lib$1.hexZeroPad)("0x" + signature.r.toString(16), 32),
- s: (0, lib$1.hexZeroPad)("0x" + signature.s.toString(16), 32),
- });
- };
- SigningKey.prototype.computeSharedSecret = function (otherKey) {
- var keyPair = getCurve().keyFromPrivate((0, lib$1.arrayify)(this.privateKey));
- var otherKeyPair = getCurve().keyFromPublic((0, lib$1.arrayify)(computePublicKey(otherKey)));
- return (0, lib$1.hexZeroPad)("0x" + keyPair.derive(otherKeyPair.getPublic()).toString(16), 32);
- };
- SigningKey.isSigningKey = function (value) {
- return !!(value && value._isSigningKey);
- };
- return SigningKey;
- }());
- exports.SigningKey = SigningKey;
- function recoverPublicKey(digest, signature) {
- var sig = (0, lib$1.splitSignature)(signature);
- var rs = { r: (0, lib$1.arrayify)(sig.r), s: (0, lib$1.arrayify)(sig.s) };
- return "0x" + getCurve().recoverPubKey((0, lib$1.arrayify)(digest), rs, sig.recoveryParam).encode("hex", false);
- }
- exports.recoverPublicKey = recoverPublicKey;
- function computePublicKey(key, compressed) {
- var bytes = (0, lib$1.arrayify)(key);
- if (bytes.length === 32) {
- var signingKey = new SigningKey(bytes);
- if (compressed) {
- return "0x" + getCurve().keyFromPrivate(bytes).getPublic(true, "hex");
- }
- return signingKey.publicKey;
- }
- else if (bytes.length === 33) {
- if (compressed) {
- return (0, lib$1.hexlify)(bytes);
- }
- return "0x" + getCurve().keyFromPublic(bytes).getPublic(false, "hex");
- }
- else if (bytes.length === 65) {
- if (!compressed) {
- return (0, lib$1.hexlify)(bytes);
- }
- return "0x" + getCurve().keyFromPublic(bytes).getPublic(true, "hex");
- }
- return logger.throwArgumentError("invalid public or private key", "key", "[REDACTED]");
- }
- exports.computePublicKey = computePublicKey;
- });
- var index$d = /*@__PURE__*/getDefaultExportFromCjs(lib$d);
- var _version$o = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "transactions/5.6.0";
- });
- var _version$p = /*@__PURE__*/getDefaultExportFromCjs(_version$o);
- var lib$e = createCommonjsModule(function (module, exports) {
- "use strict";
- var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.parse = exports.serialize = exports.accessListify = exports.recoverAddress = exports.computeAddress = exports.TransactionTypes = void 0;
- var RLP = __importStar(lib$5);
- var logger = new lib.Logger(_version$o.version);
- var TransactionTypes;
- (function (TransactionTypes) {
- TransactionTypes[TransactionTypes["legacy"] = 0] = "legacy";
- TransactionTypes[TransactionTypes["eip2930"] = 1] = "eip2930";
- TransactionTypes[TransactionTypes["eip1559"] = 2] = "eip1559";
- })(TransactionTypes = exports.TransactionTypes || (exports.TransactionTypes = {}));
- ;
- ///////////////////////////////
- function handleAddress(value) {
- if (value === "0x") {
- return null;
- }
- return (0, lib$6.getAddress)(value);
- }
- function handleNumber(value) {
- if (value === "0x") {
- return lib$7.Zero;
- }
- return lib$2.BigNumber.from(value);
- }
- // Legacy Transaction Fields
- var transactionFields = [
- { name: "nonce", maxLength: 32, numeric: true },
- { name: "gasPrice", maxLength: 32, numeric: true },
- { name: "gasLimit", maxLength: 32, numeric: true },
- { name: "to", length: 20 },
- { name: "value", maxLength: 32, numeric: true },
- { name: "data" },
- ];
- var allowedTransactionKeys = {
- chainId: true, data: true, gasLimit: true, gasPrice: true, nonce: true, to: true, type: true, value: true
- };
- function computeAddress(key) {
- var publicKey = (0, lib$d.computePublicKey)(key);
- return (0, lib$6.getAddress)((0, lib$1.hexDataSlice)((0, lib$4.keccak256)((0, lib$1.hexDataSlice)(publicKey, 1)), 12));
- }
- exports.computeAddress = computeAddress;
- function recoverAddress(digest, signature) {
- return computeAddress((0, lib$d.recoverPublicKey)((0, lib$1.arrayify)(digest), signature));
- }
- exports.recoverAddress = recoverAddress;
- function formatNumber(value, name) {
- var result = (0, lib$1.stripZeros)(lib$2.BigNumber.from(value).toHexString());
- if (result.length > 32) {
- logger.throwArgumentError("invalid length for " + name, ("transaction:" + name), value);
- }
- return result;
- }
- function accessSetify(addr, storageKeys) {
- return {
- address: (0, lib$6.getAddress)(addr),
- storageKeys: (storageKeys || []).map(function (storageKey, index) {
- if ((0, lib$1.hexDataLength)(storageKey) !== 32) {
- logger.throwArgumentError("invalid access list storageKey", "accessList[" + addr + ":" + index + "]", storageKey);
- }
- return storageKey.toLowerCase();
- })
- };
- }
- function accessListify(value) {
- if (Array.isArray(value)) {
- return value.map(function (set, index) {
- if (Array.isArray(set)) {
- if (set.length > 2) {
- logger.throwArgumentError("access list expected to be [ address, storageKeys[] ]", "value[" + index + "]", set);
- }
- return accessSetify(set[0], set[1]);
- }
- return accessSetify(set.address, set.storageKeys);
- });
- }
- var result = Object.keys(value).map(function (addr) {
- var storageKeys = value[addr].reduce(function (accum, storageKey) {
- accum[storageKey] = true;
- return accum;
- }, {});
- return accessSetify(addr, Object.keys(storageKeys).sort());
- });
- result.sort(function (a, b) { return (a.address.localeCompare(b.address)); });
- return result;
- }
- exports.accessListify = accessListify;
- function formatAccessList(value) {
- return accessListify(value).map(function (set) { return [set.address, set.storageKeys]; });
- }
- function _serializeEip1559(transaction, signature) {
- // If there is an explicit gasPrice, make sure it matches the
- // EIP-1559 fees; otherwise they may not understand what they
- // think they are setting in terms of fee.
- if (transaction.gasPrice != null) {
- var gasPrice = lib$2.BigNumber.from(transaction.gasPrice);
- var maxFeePerGas = lib$2.BigNumber.from(transaction.maxFeePerGas || 0);
- if (!gasPrice.eq(maxFeePerGas)) {
- logger.throwArgumentError("mismatch EIP-1559 gasPrice != maxFeePerGas", "tx", {
- gasPrice: gasPrice,
- maxFeePerGas: maxFeePerGas
- });
- }
- }
- var fields = [
- formatNumber(transaction.chainId || 0, "chainId"),
- formatNumber(transaction.nonce || 0, "nonce"),
- formatNumber(transaction.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"),
- formatNumber(transaction.maxFeePerGas || 0, "maxFeePerGas"),
- formatNumber(transaction.gasLimit || 0, "gasLimit"),
- ((transaction.to != null) ? (0, lib$6.getAddress)(transaction.to) : "0x"),
- formatNumber(transaction.value || 0, "value"),
- (transaction.data || "0x"),
- (formatAccessList(transaction.accessList || []))
- ];
- if (signature) {
- var sig = (0, lib$1.splitSignature)(signature);
- fields.push(formatNumber(sig.recoveryParam, "recoveryParam"));
- fields.push((0, lib$1.stripZeros)(sig.r));
- fields.push((0, lib$1.stripZeros)(sig.s));
- }
- return (0, lib$1.hexConcat)(["0x02", RLP.encode(fields)]);
- }
- function _serializeEip2930(transaction, signature) {
- var fields = [
- formatNumber(transaction.chainId || 0, "chainId"),
- formatNumber(transaction.nonce || 0, "nonce"),
- formatNumber(transaction.gasPrice || 0, "gasPrice"),
- formatNumber(transaction.gasLimit || 0, "gasLimit"),
- ((transaction.to != null) ? (0, lib$6.getAddress)(transaction.to) : "0x"),
- formatNumber(transaction.value || 0, "value"),
- (transaction.data || "0x"),
- (formatAccessList(transaction.accessList || []))
- ];
- if (signature) {
- var sig = (0, lib$1.splitSignature)(signature);
- fields.push(formatNumber(sig.recoveryParam, "recoveryParam"));
- fields.push((0, lib$1.stripZeros)(sig.r));
- fields.push((0, lib$1.stripZeros)(sig.s));
- }
- return (0, lib$1.hexConcat)(["0x01", RLP.encode(fields)]);
- }
- // Legacy Transactions and EIP-155
- function _serialize(transaction, signature) {
- (0, lib$3.checkProperties)(transaction, allowedTransactionKeys);
- var raw = [];
- transactionFields.forEach(function (fieldInfo) {
- var value = transaction[fieldInfo.name] || ([]);
- var options = {};
- if (fieldInfo.numeric) {
- options.hexPad = "left";
- }
- value = (0, lib$1.arrayify)((0, lib$1.hexlify)(value, options));
- // Fixed-width field
- if (fieldInfo.length && value.length !== fieldInfo.length && value.length > 0) {
- logger.throwArgumentError("invalid length for " + fieldInfo.name, ("transaction:" + fieldInfo.name), value);
- }
- // Variable-width (with a maximum)
- if (fieldInfo.maxLength) {
- value = (0, lib$1.stripZeros)(value);
- if (value.length > fieldInfo.maxLength) {
- logger.throwArgumentError("invalid length for " + fieldInfo.name, ("transaction:" + fieldInfo.name), value);
- }
- }
- raw.push((0, lib$1.hexlify)(value));
- });
- var chainId = 0;
- if (transaction.chainId != null) {
- // A chainId was provided; if non-zero we'll use EIP-155
- chainId = transaction.chainId;
- if (typeof (chainId) !== "number") {
- logger.throwArgumentError("invalid transaction.chainId", "transaction", transaction);
- }
- }
- else if (signature && !(0, lib$1.isBytesLike)(signature) && signature.v > 28) {
- // No chainId provided, but the signature is signing with EIP-155; derive chainId
- chainId = Math.floor((signature.v - 35) / 2);
- }
- // We have an EIP-155 transaction (chainId was specified and non-zero)
- if (chainId !== 0) {
- raw.push((0, lib$1.hexlify)(chainId)); // @TODO: hexValue?
- raw.push("0x");
- raw.push("0x");
- }
- // Requesting an unsigned transaction
- if (!signature) {
- return RLP.encode(raw);
- }
- // The splitSignature will ensure the transaction has a recoveryParam in the
- // case that the signTransaction function only adds a v.
- var sig = (0, lib$1.splitSignature)(signature);
- // We pushed a chainId and null r, s on for hashing only; remove those
- var v = 27 + sig.recoveryParam;
- if (chainId !== 0) {
- raw.pop();
- raw.pop();
- raw.pop();
- v += chainId * 2 + 8;
- // If an EIP-155 v (directly or indirectly; maybe _vs) was provided, check it!
- if (sig.v > 28 && sig.v !== v) {
- logger.throwArgumentError("transaction.chainId/signature.v mismatch", "signature", signature);
- }
- }
- else if (sig.v !== v) {
- logger.throwArgumentError("transaction.chainId/signature.v mismatch", "signature", signature);
- }
- raw.push((0, lib$1.hexlify)(v));
- raw.push((0, lib$1.stripZeros)((0, lib$1.arrayify)(sig.r)));
- raw.push((0, lib$1.stripZeros)((0, lib$1.arrayify)(sig.s)));
- return RLP.encode(raw);
- }
- function serialize(transaction, signature) {
- // Legacy and EIP-155 Transactions
- if (transaction.type == null || transaction.type === 0) {
- if (transaction.accessList != null) {
- logger.throwArgumentError("untyped transactions do not support accessList; include type: 1", "transaction", transaction);
- }
- return _serialize(transaction, signature);
- }
- // Typed Transactions (EIP-2718)
- switch (transaction.type) {
- case 1:
- return _serializeEip2930(transaction, signature);
- case 2:
- return _serializeEip1559(transaction, signature);
- default:
- break;
- }
- return logger.throwError("unsupported transaction type: " + transaction.type, lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "serializeTransaction",
- transactionType: transaction.type
- });
- }
- exports.serialize = serialize;
- function _parseEipSignature(tx, fields, serialize) {
- try {
- var recid = handleNumber(fields[0]).toNumber();
- if (recid !== 0 && recid !== 1) {
- throw new Error("bad recid");
- }
- tx.v = recid;
- }
- catch (error) {
- logger.throwArgumentError("invalid v for transaction type: 1", "v", fields[0]);
- }
- tx.r = (0, lib$1.hexZeroPad)(fields[1], 32);
- tx.s = (0, lib$1.hexZeroPad)(fields[2], 32);
- try {
- var digest = (0, lib$4.keccak256)(serialize(tx));
- tx.from = recoverAddress(digest, { r: tx.r, s: tx.s, recoveryParam: tx.v });
- }
- catch (error) {
- console.log(error);
- }
- }
- function _parseEip1559(payload) {
- var transaction = RLP.decode(payload.slice(1));
- if (transaction.length !== 9 && transaction.length !== 12) {
- logger.throwArgumentError("invalid component count for transaction type: 2", "payload", (0, lib$1.hexlify)(payload));
- }
- var maxPriorityFeePerGas = handleNumber(transaction[2]);
- var maxFeePerGas = handleNumber(transaction[3]);
- var tx = {
- type: 2,
- chainId: handleNumber(transaction[0]).toNumber(),
- nonce: handleNumber(transaction[1]).toNumber(),
- maxPriorityFeePerGas: maxPriorityFeePerGas,
- maxFeePerGas: maxFeePerGas,
- gasPrice: null,
- gasLimit: handleNumber(transaction[4]),
- to: handleAddress(transaction[5]),
- value: handleNumber(transaction[6]),
- data: transaction[7],
- accessList: accessListify(transaction[8]),
- };
- // Unsigned EIP-1559 Transaction
- if (transaction.length === 9) {
- return tx;
- }
- tx.hash = (0, lib$4.keccak256)(payload);
- _parseEipSignature(tx, transaction.slice(9), _serializeEip1559);
- return tx;
- }
- function _parseEip2930(payload) {
- var transaction = RLP.decode(payload.slice(1));
- if (transaction.length !== 8 && transaction.length !== 11) {
- logger.throwArgumentError("invalid component count for transaction type: 1", "payload", (0, lib$1.hexlify)(payload));
- }
- var tx = {
- type: 1,
- chainId: handleNumber(transaction[0]).toNumber(),
- nonce: handleNumber(transaction[1]).toNumber(),
- gasPrice: handleNumber(transaction[2]),
- gasLimit: handleNumber(transaction[3]),
- to: handleAddress(transaction[4]),
- value: handleNumber(transaction[5]),
- data: transaction[6],
- accessList: accessListify(transaction[7])
- };
- // Unsigned EIP-2930 Transaction
- if (transaction.length === 8) {
- return tx;
- }
- tx.hash = (0, lib$4.keccak256)(payload);
- _parseEipSignature(tx, transaction.slice(8), _serializeEip2930);
- return tx;
- }
- // Legacy Transactions and EIP-155
- function _parse(rawTransaction) {
- var transaction = RLP.decode(rawTransaction);
- if (transaction.length !== 9 && transaction.length !== 6) {
- logger.throwArgumentError("invalid raw transaction", "rawTransaction", rawTransaction);
- }
- var tx = {
- nonce: handleNumber(transaction[0]).toNumber(),
- gasPrice: handleNumber(transaction[1]),
- gasLimit: handleNumber(transaction[2]),
- to: handleAddress(transaction[3]),
- value: handleNumber(transaction[4]),
- data: transaction[5],
- chainId: 0
- };
- // Legacy unsigned transaction
- if (transaction.length === 6) {
- return tx;
- }
- try {
- tx.v = lib$2.BigNumber.from(transaction[6]).toNumber();
- }
- catch (error) {
- console.log(error);
- return tx;
- }
- tx.r = (0, lib$1.hexZeroPad)(transaction[7], 32);
- tx.s = (0, lib$1.hexZeroPad)(transaction[8], 32);
- if (lib$2.BigNumber.from(tx.r).isZero() && lib$2.BigNumber.from(tx.s).isZero()) {
- // EIP-155 unsigned transaction
- tx.chainId = tx.v;
- tx.v = 0;
- }
- else {
- // Signed Transaction
- tx.chainId = Math.floor((tx.v - 35) / 2);
- if (tx.chainId < 0) {
- tx.chainId = 0;
- }
- var recoveryParam = tx.v - 27;
- var raw = transaction.slice(0, 6);
- if (tx.chainId !== 0) {
- raw.push((0, lib$1.hexlify)(tx.chainId));
- raw.push("0x");
- raw.push("0x");
- recoveryParam -= tx.chainId * 2 + 8;
- }
- var digest = (0, lib$4.keccak256)(RLP.encode(raw));
- try {
- tx.from = recoverAddress(digest, { r: (0, lib$1.hexlify)(tx.r), s: (0, lib$1.hexlify)(tx.s), recoveryParam: recoveryParam });
- }
- catch (error) {
- console.log(error);
- }
- tx.hash = (0, lib$4.keccak256)(rawTransaction);
- }
- tx.type = null;
- return tx;
- }
- function parse(rawTransaction) {
- var payload = (0, lib$1.arrayify)(rawTransaction);
- // Legacy and EIP-155 Transactions
- if (payload[0] > 0x7f) {
- return _parse(payload);
- }
- // Typed Transaction (EIP-2718)
- switch (payload[0]) {
- case 1:
- return _parseEip2930(payload);
- case 2:
- return _parseEip1559(payload);
- default:
- break;
- }
- return logger.throwError("unsupported transaction type: " + payload[0], lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "parseTransaction",
- transactionType: payload[0]
- });
- }
- exports.parse = parse;
- });
- var index$e = /*@__PURE__*/getDefaultExportFromCjs(lib$e);
- var _version$q = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "contracts/5.6.0";
- });
- var _version$r = /*@__PURE__*/getDefaultExportFromCjs(_version$q);
- var lib$f = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- };
- var __spreadArray = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from, pack) {
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
- if (ar || !(i in from)) {
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
- ar[i] = from[i];
- }
- }
- return to.concat(ar || Array.prototype.slice.call(from));
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ContractFactory = exports.Contract = exports.BaseContract = void 0;
- var logger = new lib.Logger(_version$q.version);
- ;
- ;
- ///////////////////////////////
- var allowedTransactionKeys = {
- chainId: true, data: true, from: true, gasLimit: true, gasPrice: true, nonce: true, to: true, value: true,
- type: true, accessList: true,
- maxFeePerGas: true, maxPriorityFeePerGas: true,
- customData: true,
- ccipReadEnabled: true
- };
- function resolveName(resolver, nameOrPromise) {
- return __awaiter(this, void 0, void 0, function () {
- var name, address;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, nameOrPromise];
- case 1:
- name = _a.sent();
- if (typeof (name) !== "string") {
- logger.throwArgumentError("invalid address or ENS name", "name", name);
- }
- // If it is already an address, just use it (after adding checksum)
- try {
- return [2 /*return*/, (0, lib$6.getAddress)(name)];
- }
- catch (error) { }
- if (!resolver) {
- logger.throwError("a provider or signer is needed to resolve ENS names", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "resolveName"
- });
- }
- return [4 /*yield*/, resolver.resolveName(name)];
- case 2:
- address = _a.sent();
- if (address == null) {
- logger.throwArgumentError("resolver or addr is not configured for ENS name", "name", name);
- }
- return [2 /*return*/, address];
- }
- });
- });
- }
- // Recursively replaces ENS names with promises to resolve the name and resolves all properties
- function resolveAddresses(resolver, value, paramType) {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (!Array.isArray(paramType)) return [3 /*break*/, 2];
- return [4 /*yield*/, Promise.all(paramType.map(function (paramType, index) {
- return resolveAddresses(resolver, ((Array.isArray(value)) ? value[index] : value[paramType.name]), paramType);
- }))];
- case 1: return [2 /*return*/, _a.sent()];
- case 2:
- if (!(paramType.type === "address")) return [3 /*break*/, 4];
- return [4 /*yield*/, resolveName(resolver, value)];
- case 3: return [2 /*return*/, _a.sent()];
- case 4:
- if (!(paramType.type === "tuple")) return [3 /*break*/, 6];
- return [4 /*yield*/, resolveAddresses(resolver, value, paramType.components)];
- case 5: return [2 /*return*/, _a.sent()];
- case 6:
- if (!(paramType.baseType === "array")) return [3 /*break*/, 8];
- if (!Array.isArray(value)) {
- return [2 /*return*/, Promise.reject(logger.makeError("invalid value for array", lib.Logger.errors.INVALID_ARGUMENT, {
- argument: "value",
- value: value
- }))];
- }
- return [4 /*yield*/, Promise.all(value.map(function (v) { return resolveAddresses(resolver, v, paramType.arrayChildren); }))];
- case 7: return [2 /*return*/, _a.sent()];
- case 8: return [2 /*return*/, value];
- }
- });
- });
- }
- function populateTransaction(contract, fragment, args) {
- return __awaiter(this, void 0, void 0, function () {
- var overrides, resolved, data, tx, ro, intrinsic, bytes, i, roValue, leftovers;
- var _this = this;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- overrides = {};
- if (args.length === fragment.inputs.length + 1 && typeof (args[args.length - 1]) === "object") {
- overrides = (0, lib$3.shallowCopy)(args.pop());
- }
- // Make sure the parameter count matches
- logger.checkArgumentCount(args.length, fragment.inputs.length, "passed to contract");
- // Populate "from" override (allow promises)
- if (contract.signer) {
- if (overrides.from) {
- // Contracts with a Signer are from the Signer's frame-of-reference;
- // but we allow overriding "from" if it matches the signer
- overrides.from = (0, lib$3.resolveProperties)({
- override: resolveName(contract.signer, overrides.from),
- signer: contract.signer.getAddress()
- }).then(function (check) { return __awaiter(_this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- if ((0, lib$6.getAddress)(check.signer) !== check.override) {
- logger.throwError("Contract with a Signer cannot override from", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "overrides.from"
- });
- }
- return [2 /*return*/, check.override];
- });
- }); });
- }
- else {
- overrides.from = contract.signer.getAddress();
- }
- }
- else if (overrides.from) {
- overrides.from = resolveName(contract.provider, overrides.from);
- //} else {
- // Contracts without a signer can override "from", and if
- // unspecified the zero address is used
- //overrides.from = AddressZero;
- }
- return [4 /*yield*/, (0, lib$3.resolveProperties)({
- args: resolveAddresses(contract.signer || contract.provider, args, fragment.inputs),
- address: contract.resolvedAddress,
- overrides: ((0, lib$3.resolveProperties)(overrides) || {})
- })];
- case 1:
- resolved = _a.sent();
- data = contract.interface.encodeFunctionData(fragment, resolved.args);
- tx = {
- data: data,
- to: resolved.address
- };
- ro = resolved.overrides;
- // Populate simple overrides
- if (ro.nonce != null) {
- tx.nonce = lib$2.BigNumber.from(ro.nonce).toNumber();
- }
- if (ro.gasLimit != null) {
- tx.gasLimit = lib$2.BigNumber.from(ro.gasLimit);
- }
- if (ro.gasPrice != null) {
- tx.gasPrice = lib$2.BigNumber.from(ro.gasPrice);
- }
- if (ro.maxFeePerGas != null) {
- tx.maxFeePerGas = lib$2.BigNumber.from(ro.maxFeePerGas);
- }
- if (ro.maxPriorityFeePerGas != null) {
- tx.maxPriorityFeePerGas = lib$2.BigNumber.from(ro.maxPriorityFeePerGas);
- }
- if (ro.from != null) {
- tx.from = ro.from;
- }
- if (ro.type != null) {
- tx.type = ro.type;
- }
- if (ro.accessList != null) {
- tx.accessList = (0, lib$e.accessListify)(ro.accessList);
- }
- // If there was no "gasLimit" override, but the ABI specifies a default, use it
- if (tx.gasLimit == null && fragment.gas != null) {
- intrinsic = 21000;
- bytes = (0, lib$1.arrayify)(data);
- for (i = 0; i < bytes.length; i++) {
- intrinsic += 4;
- if (bytes[i]) {
- intrinsic += 64;
- }
- }
- tx.gasLimit = lib$2.BigNumber.from(fragment.gas).add(intrinsic);
- }
- // Populate "value" override
- if (ro.value) {
- roValue = lib$2.BigNumber.from(ro.value);
- if (!roValue.isZero() && !fragment.payable) {
- logger.throwError("non-payable method cannot override value", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "overrides.value",
- value: overrides.value
- });
- }
- tx.value = roValue;
- }
- if (ro.customData) {
- tx.customData = (0, lib$3.shallowCopy)(ro.customData);
- }
- if (ro.ccipReadEnabled) {
- tx.ccipReadEnabled = !!ro.ccipReadEnabled;
- }
- // Remove the overrides
- delete overrides.nonce;
- delete overrides.gasLimit;
- delete overrides.gasPrice;
- delete overrides.from;
- delete overrides.value;
- delete overrides.type;
- delete overrides.accessList;
- delete overrides.maxFeePerGas;
- delete overrides.maxPriorityFeePerGas;
- delete overrides.customData;
- delete overrides.ccipReadEnabled;
- leftovers = Object.keys(overrides).filter(function (key) { return (overrides[key] != null); });
- if (leftovers.length) {
- logger.throwError("cannot override " + leftovers.map(function (l) { return JSON.stringify(l); }).join(","), lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "overrides",
- overrides: leftovers
- });
- }
- return [2 /*return*/, tx];
- }
- });
- });
- }
- function buildPopulate(contract, fragment) {
- return function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- return populateTransaction(contract, fragment, args);
- };
- }
- function buildEstimate(contract, fragment) {
- var signerOrProvider = (contract.signer || contract.provider);
- return function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- return __awaiter(this, void 0, void 0, function () {
- var tx;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (!signerOrProvider) {
- logger.throwError("estimate require a provider or signer", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "estimateGas"
- });
- }
- return [4 /*yield*/, populateTransaction(contract, fragment, args)];
- case 1:
- tx = _a.sent();
- return [4 /*yield*/, signerOrProvider.estimateGas(tx)];
- case 2: return [2 /*return*/, _a.sent()];
- }
- });
- });
- };
- }
- function addContractWait(contract, tx) {
- var wait = tx.wait.bind(tx);
- tx.wait = function (confirmations) {
- return wait(confirmations).then(function (receipt) {
- receipt.events = receipt.logs.map(function (log) {
- var event = (0, lib$3.deepCopy)(log);
- var parsed = null;
- try {
- parsed = contract.interface.parseLog(log);
- }
- catch (e) { }
- // Successfully parsed the event log; include it
- if (parsed) {
- event.args = parsed.args;
- event.decode = function (data, topics) {
- return contract.interface.decodeEventLog(parsed.eventFragment, data, topics);
- };
- event.event = parsed.name;
- event.eventSignature = parsed.signature;
- }
- // Useful operations
- event.removeListener = function () { return contract.provider; };
- event.getBlock = function () {
- return contract.provider.getBlock(receipt.blockHash);
- };
- event.getTransaction = function () {
- return contract.provider.getTransaction(receipt.transactionHash);
- };
- event.getTransactionReceipt = function () {
- return Promise.resolve(receipt);
- };
- return event;
- });
- return receipt;
- });
- };
- }
- function buildCall(contract, fragment, collapseSimple) {
- var signerOrProvider = (contract.signer || contract.provider);
- return function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- return __awaiter(this, void 0, void 0, function () {
- var blockTag, overrides, tx, result, value;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- blockTag = undefined;
- if (!(args.length === fragment.inputs.length + 1 && typeof (args[args.length - 1]) === "object")) return [3 /*break*/, 3];
- overrides = (0, lib$3.shallowCopy)(args.pop());
- if (!(overrides.blockTag != null)) return [3 /*break*/, 2];
- return [4 /*yield*/, overrides.blockTag];
- case 1:
- blockTag = _a.sent();
- _a.label = 2;
- case 2:
- delete overrides.blockTag;
- args.push(overrides);
- _a.label = 3;
- case 3:
- if (!(contract.deployTransaction != null)) return [3 /*break*/, 5];
- return [4 /*yield*/, contract._deployed(blockTag)];
- case 4:
- _a.sent();
- _a.label = 5;
- case 5: return [4 /*yield*/, populateTransaction(contract, fragment, args)];
- case 6:
- tx = _a.sent();
- return [4 /*yield*/, signerOrProvider.call(tx, blockTag)];
- case 7:
- result = _a.sent();
- try {
- value = contract.interface.decodeFunctionResult(fragment, result);
- if (collapseSimple && fragment.outputs.length === 1) {
- value = value[0];
- }
- return [2 /*return*/, value];
- }
- catch (error) {
- if (error.code === lib.Logger.errors.CALL_EXCEPTION) {
- error.address = contract.address;
- error.args = args;
- error.transaction = tx;
- }
- throw error;
- }
- return [2 /*return*/];
- }
- });
- });
- };
- }
- function buildSend(contract, fragment) {
- return function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- return __awaiter(this, void 0, void 0, function () {
- var txRequest, tx;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (!contract.signer) {
- logger.throwError("sending a transaction requires a signer", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "sendTransaction"
- });
- }
- if (!(contract.deployTransaction != null)) return [3 /*break*/, 2];
- return [4 /*yield*/, contract._deployed()];
- case 1:
- _a.sent();
- _a.label = 2;
- case 2: return [4 /*yield*/, populateTransaction(contract, fragment, args)];
- case 3:
- txRequest = _a.sent();
- return [4 /*yield*/, contract.signer.sendTransaction(txRequest)];
- case 4:
- tx = _a.sent();
- // Tweak the tx.wait so the receipt has extra properties
- addContractWait(contract, tx);
- return [2 /*return*/, tx];
- }
- });
- });
- };
- }
- function buildDefault(contract, fragment, collapseSimple) {
- if (fragment.constant) {
- return buildCall(contract, fragment, collapseSimple);
- }
- return buildSend(contract, fragment);
- }
- function getEventTag(filter) {
- if (filter.address && (filter.topics == null || filter.topics.length === 0)) {
- return "*";
- }
- return (filter.address || "*") + "@" + (filter.topics ? filter.topics.map(function (topic) {
- if (Array.isArray(topic)) {
- return topic.join("|");
- }
- return topic;
- }).join(":") : "");
- }
- var RunningEvent = /** @class */ (function () {
- function RunningEvent(tag, filter) {
- (0, lib$3.defineReadOnly)(this, "tag", tag);
- (0, lib$3.defineReadOnly)(this, "filter", filter);
- this._listeners = [];
- }
- RunningEvent.prototype.addListener = function (listener, once) {
- this._listeners.push({ listener: listener, once: once });
- };
- RunningEvent.prototype.removeListener = function (listener) {
- var done = false;
- this._listeners = this._listeners.filter(function (item) {
- if (done || item.listener !== listener) {
- return true;
- }
- done = true;
- return false;
- });
- };
- RunningEvent.prototype.removeAllListeners = function () {
- this._listeners = [];
- };
- RunningEvent.prototype.listeners = function () {
- return this._listeners.map(function (i) { return i.listener; });
- };
- RunningEvent.prototype.listenerCount = function () {
- return this._listeners.length;
- };
- RunningEvent.prototype.run = function (args) {
- var _this = this;
- var listenerCount = this.listenerCount();
- this._listeners = this._listeners.filter(function (item) {
- var argsCopy = args.slice();
- // Call the callback in the next event loop
- setTimeout(function () {
- item.listener.apply(_this, argsCopy);
- }, 0);
- // Reschedule it if it not "once"
- return !(item.once);
- });
- return listenerCount;
- };
- RunningEvent.prototype.prepareEvent = function (event) {
- };
- // Returns the array that will be applied to an emit
- RunningEvent.prototype.getEmit = function (event) {
- return [event];
- };
- return RunningEvent;
- }());
- var ErrorRunningEvent = /** @class */ (function (_super) {
- __extends(ErrorRunningEvent, _super);
- function ErrorRunningEvent() {
- return _super.call(this, "error", null) || this;
- }
- return ErrorRunningEvent;
- }(RunningEvent));
- // @TODO Fragment should inherit Wildcard? and just override getEmit?
- // or have a common abstract super class, with enough constructor
- // options to configure both.
- // A Fragment Event will populate all the properties that Wildcard
- // will, and additionally dereference the arguments when emitting
- var FragmentRunningEvent = /** @class */ (function (_super) {
- __extends(FragmentRunningEvent, _super);
- function FragmentRunningEvent(address, contractInterface, fragment, topics) {
- var _this = this;
- var filter = {
- address: address
- };
- var topic = contractInterface.getEventTopic(fragment);
- if (topics) {
- if (topic !== topics[0]) {
- logger.throwArgumentError("topic mismatch", "topics", topics);
- }
- filter.topics = topics.slice();
- }
- else {
- filter.topics = [topic];
- }
- _this = _super.call(this, getEventTag(filter), filter) || this;
- (0, lib$3.defineReadOnly)(_this, "address", address);
- (0, lib$3.defineReadOnly)(_this, "interface", contractInterface);
- (0, lib$3.defineReadOnly)(_this, "fragment", fragment);
- return _this;
- }
- FragmentRunningEvent.prototype.prepareEvent = function (event) {
- var _this = this;
- _super.prototype.prepareEvent.call(this, event);
- event.event = this.fragment.name;
- event.eventSignature = this.fragment.format();
- event.decode = function (data, topics) {
- return _this.interface.decodeEventLog(_this.fragment, data, topics);
- };
- try {
- event.args = this.interface.decodeEventLog(this.fragment, event.data, event.topics);
- }
- catch (error) {
- event.args = null;
- event.decodeError = error;
- }
- };
- FragmentRunningEvent.prototype.getEmit = function (event) {
- var errors = (0, lib$a.checkResultErrors)(event.args);
- if (errors.length) {
- throw errors[0].error;
- }
- var args = (event.args || []).slice();
- args.push(event);
- return args;
- };
- return FragmentRunningEvent;
- }(RunningEvent));
- // A Wildcard Event will attempt to populate:
- // - event The name of the event name
- // - eventSignature The full signature of the event
- // - decode A function to decode data and topics
- // - args The decoded data and topics
- var WildcardRunningEvent = /** @class */ (function (_super) {
- __extends(WildcardRunningEvent, _super);
- function WildcardRunningEvent(address, contractInterface) {
- var _this = _super.call(this, "*", { address: address }) || this;
- (0, lib$3.defineReadOnly)(_this, "address", address);
- (0, lib$3.defineReadOnly)(_this, "interface", contractInterface);
- return _this;
- }
- WildcardRunningEvent.prototype.prepareEvent = function (event) {
- var _this = this;
- _super.prototype.prepareEvent.call(this, event);
- try {
- var parsed_1 = this.interface.parseLog(event);
- event.event = parsed_1.name;
- event.eventSignature = parsed_1.signature;
- event.decode = function (data, topics) {
- return _this.interface.decodeEventLog(parsed_1.eventFragment, data, topics);
- };
- event.args = parsed_1.args;
- }
- catch (error) {
- // No matching event
- }
- };
- return WildcardRunningEvent;
- }(RunningEvent));
- var BaseContract = /** @class */ (function () {
- function BaseContract(addressOrName, contractInterface, signerOrProvider) {
- var _newTarget = this.constructor;
- var _this = this;
- logger.checkNew(_newTarget, Contract);
- // @TODO: Maybe still check the addressOrName looks like a valid address or name?
- //address = getAddress(address);
- (0, lib$3.defineReadOnly)(this, "interface", (0, lib$3.getStatic)(_newTarget, "getInterface")(contractInterface));
- if (signerOrProvider == null) {
- (0, lib$3.defineReadOnly)(this, "provider", null);
- (0, lib$3.defineReadOnly)(this, "signer", null);
- }
- else if (lib$c.Signer.isSigner(signerOrProvider)) {
- (0, lib$3.defineReadOnly)(this, "provider", signerOrProvider.provider || null);
- (0, lib$3.defineReadOnly)(this, "signer", signerOrProvider);
- }
- else if (lib$b.Provider.isProvider(signerOrProvider)) {
- (0, lib$3.defineReadOnly)(this, "provider", signerOrProvider);
- (0, lib$3.defineReadOnly)(this, "signer", null);
- }
- else {
- logger.throwArgumentError("invalid signer or provider", "signerOrProvider", signerOrProvider);
- }
- (0, lib$3.defineReadOnly)(this, "callStatic", {});
- (0, lib$3.defineReadOnly)(this, "estimateGas", {});
- (0, lib$3.defineReadOnly)(this, "functions", {});
- (0, lib$3.defineReadOnly)(this, "populateTransaction", {});
- (0, lib$3.defineReadOnly)(this, "filters", {});
- {
- var uniqueFilters_1 = {};
- Object.keys(this.interface.events).forEach(function (eventSignature) {
- var event = _this.interface.events[eventSignature];
- (0, lib$3.defineReadOnly)(_this.filters, eventSignature, function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- return {
- address: _this.address,
- topics: _this.interface.encodeFilterTopics(event, args)
- };
- });
- if (!uniqueFilters_1[event.name]) {
- uniqueFilters_1[event.name] = [];
- }
- uniqueFilters_1[event.name].push(eventSignature);
- });
- Object.keys(uniqueFilters_1).forEach(function (name) {
- var filters = uniqueFilters_1[name];
- if (filters.length === 1) {
- (0, lib$3.defineReadOnly)(_this.filters, name, _this.filters[filters[0]]);
- }
- else {
- logger.warn("Duplicate definition of " + name + " (" + filters.join(", ") + ")");
- }
- });
- }
- (0, lib$3.defineReadOnly)(this, "_runningEvents", {});
- (0, lib$3.defineReadOnly)(this, "_wrappedEmits", {});
- if (addressOrName == null) {
- logger.throwArgumentError("invalid contract address or ENS name", "addressOrName", addressOrName);
- }
- (0, lib$3.defineReadOnly)(this, "address", addressOrName);
- if (this.provider) {
- (0, lib$3.defineReadOnly)(this, "resolvedAddress", resolveName(this.provider, addressOrName));
- }
- else {
- try {
- (0, lib$3.defineReadOnly)(this, "resolvedAddress", Promise.resolve((0, lib$6.getAddress)(addressOrName)));
- }
- catch (error) {
- // Without a provider, we cannot use ENS names
- logger.throwError("provider is required to use ENS name as contract address", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "new Contract"
- });
- }
- }
- // Swallow bad ENS names to prevent Unhandled Exceptions
- this.resolvedAddress.catch(function (e) { });
- var uniqueNames = {};
- var uniqueSignatures = {};
- Object.keys(this.interface.functions).forEach(function (signature) {
- var fragment = _this.interface.functions[signature];
- // Check that the signature is unique; if not the ABI generation has
- // not been cleaned or may be incorrectly generated
- if (uniqueSignatures[signature]) {
- logger.warn("Duplicate ABI entry for " + JSON.stringify(signature));
- return;
- }
- uniqueSignatures[signature] = true;
- // Track unique names; we only expose bare named functions if they
- // are ambiguous
- {
- var name_1 = fragment.name;
- if (!uniqueNames["%" + name_1]) {
- uniqueNames["%" + name_1] = [];
- }
- uniqueNames["%" + name_1].push(signature);
- }
- if (_this[signature] == null) {
- (0, lib$3.defineReadOnly)(_this, signature, buildDefault(_this, fragment, true));
- }
- // We do not collapse simple calls on this bucket, which allows
- // frameworks to safely use this without introspection as well as
- // allows decoding error recovery.
- if (_this.functions[signature] == null) {
- (0, lib$3.defineReadOnly)(_this.functions, signature, buildDefault(_this, fragment, false));
- }
- if (_this.callStatic[signature] == null) {
- (0, lib$3.defineReadOnly)(_this.callStatic, signature, buildCall(_this, fragment, true));
- }
- if (_this.populateTransaction[signature] == null) {
- (0, lib$3.defineReadOnly)(_this.populateTransaction, signature, buildPopulate(_this, fragment));
- }
- if (_this.estimateGas[signature] == null) {
- (0, lib$3.defineReadOnly)(_this.estimateGas, signature, buildEstimate(_this, fragment));
- }
- });
- Object.keys(uniqueNames).forEach(function (name) {
- // Ambiguous names to not get attached as bare names
- var signatures = uniqueNames[name];
- if (signatures.length > 1) {
- return;
- }
- // Strip off the leading "%" used for prototype protection
- name = name.substring(1);
- var signature = signatures[0];
- // If overwriting a member property that is null, swallow the error
- try {
- if (_this[name] == null) {
- (0, lib$3.defineReadOnly)(_this, name, _this[signature]);
- }
- }
- catch (e) { }
- if (_this.functions[name] == null) {
- (0, lib$3.defineReadOnly)(_this.functions, name, _this.functions[signature]);
- }
- if (_this.callStatic[name] == null) {
- (0, lib$3.defineReadOnly)(_this.callStatic, name, _this.callStatic[signature]);
- }
- if (_this.populateTransaction[name] == null) {
- (0, lib$3.defineReadOnly)(_this.populateTransaction, name, _this.populateTransaction[signature]);
- }
- if (_this.estimateGas[name] == null) {
- (0, lib$3.defineReadOnly)(_this.estimateGas, name, _this.estimateGas[signature]);
- }
- });
- }
- BaseContract.getContractAddress = function (transaction) {
- return (0, lib$6.getContractAddress)(transaction);
- };
- BaseContract.getInterface = function (contractInterface) {
- if (lib$a.Interface.isInterface(contractInterface)) {
- return contractInterface;
- }
- return new lib$a.Interface(contractInterface);
- };
- // @TODO: Allow timeout?
- BaseContract.prototype.deployed = function () {
- return this._deployed();
- };
- BaseContract.prototype._deployed = function (blockTag) {
- var _this = this;
- if (!this._deployedPromise) {
- // If we were just deployed, we know the transaction we should occur in
- if (this.deployTransaction) {
- this._deployedPromise = this.deployTransaction.wait().then(function () {
- return _this;
- });
- }
- else {
- // @TODO: Once we allow a timeout to be passed in, we will wait
- // up to that many blocks for getCode
- // Otherwise, poll for our code to be deployed
- this._deployedPromise = this.provider.getCode(this.address, blockTag).then(function (code) {
- if (code === "0x") {
- logger.throwError("contract not deployed", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- contractAddress: _this.address,
- operation: "getDeployed"
- });
- }
- return _this;
- });
- }
- }
- return this._deployedPromise;
- };
- // @TODO:
- // estimateFallback(overrides?: TransactionRequest): Promise<BigNumber>
- // @TODO:
- // estimateDeploy(bytecode: string, ...args): Promise<BigNumber>
- BaseContract.prototype.fallback = function (overrides) {
- var _this = this;
- if (!this.signer) {
- logger.throwError("sending a transactions require a signer", lib.Logger.errors.UNSUPPORTED_OPERATION, { operation: "sendTransaction(fallback)" });
- }
- var tx = (0, lib$3.shallowCopy)(overrides || {});
- ["from", "to"].forEach(function (key) {
- if (tx[key] == null) {
- return;
- }
- logger.throwError("cannot override " + key, lib.Logger.errors.UNSUPPORTED_OPERATION, { operation: key });
- });
- tx.to = this.resolvedAddress;
- return this.deployed().then(function () {
- return _this.signer.sendTransaction(tx);
- });
- };
- // Reconnect to a different signer or provider
- BaseContract.prototype.connect = function (signerOrProvider) {
- if (typeof (signerOrProvider) === "string") {
- signerOrProvider = new lib$c.VoidSigner(signerOrProvider, this.provider);
- }
- var contract = new (this.constructor)(this.address, this.interface, signerOrProvider);
- if (this.deployTransaction) {
- (0, lib$3.defineReadOnly)(contract, "deployTransaction", this.deployTransaction);
- }
- return contract;
- };
- // Re-attach to a different on-chain instance of this contract
- BaseContract.prototype.attach = function (addressOrName) {
- return new (this.constructor)(addressOrName, this.interface, this.signer || this.provider);
- };
- BaseContract.isIndexed = function (value) {
- return lib$a.Indexed.isIndexed(value);
- };
- BaseContract.prototype._normalizeRunningEvent = function (runningEvent) {
- // Already have an instance of this event running; we can re-use it
- if (this._runningEvents[runningEvent.tag]) {
- return this._runningEvents[runningEvent.tag];
- }
- return runningEvent;
- };
- BaseContract.prototype._getRunningEvent = function (eventName) {
- if (typeof (eventName) === "string") {
- // Listen for "error" events (if your contract has an error event, include
- // the full signature to bypass this special event keyword)
- if (eventName === "error") {
- return this._normalizeRunningEvent(new ErrorRunningEvent());
- }
- // Listen for any event that is registered
- if (eventName === "event") {
- return this._normalizeRunningEvent(new RunningEvent("event", null));
- }
- // Listen for any event
- if (eventName === "*") {
- return this._normalizeRunningEvent(new WildcardRunningEvent(this.address, this.interface));
- }
- // Get the event Fragment (throws if ambiguous/unknown event)
- var fragment = this.interface.getEvent(eventName);
- return this._normalizeRunningEvent(new FragmentRunningEvent(this.address, this.interface, fragment));
- }
- // We have topics to filter by...
- if (eventName.topics && eventName.topics.length > 0) {
- // Is it a known topichash? (throws if no matching topichash)
- try {
- var topic = eventName.topics[0];
- if (typeof (topic) !== "string") {
- throw new Error("invalid topic"); // @TODO: May happen for anonymous events
- }
- var fragment = this.interface.getEvent(topic);
- return this._normalizeRunningEvent(new FragmentRunningEvent(this.address, this.interface, fragment, eventName.topics));
- }
- catch (error) { }
- // Filter by the unknown topichash
- var filter = {
- address: this.address,
- topics: eventName.topics
- };
- return this._normalizeRunningEvent(new RunningEvent(getEventTag(filter), filter));
- }
- return this._normalizeRunningEvent(new WildcardRunningEvent(this.address, this.interface));
- };
- BaseContract.prototype._checkRunningEvents = function (runningEvent) {
- if (runningEvent.listenerCount() === 0) {
- delete this._runningEvents[runningEvent.tag];
- // If we have a poller for this, remove it
- var emit = this._wrappedEmits[runningEvent.tag];
- if (emit && runningEvent.filter) {
- this.provider.off(runningEvent.filter, emit);
- delete this._wrappedEmits[runningEvent.tag];
- }
- }
- };
- // Subclasses can override this to gracefully recover
- // from parse errors if they wish
- BaseContract.prototype._wrapEvent = function (runningEvent, log, listener) {
- var _this = this;
- var event = (0, lib$3.deepCopy)(log);
- event.removeListener = function () {
- if (!listener) {
- return;
- }
- runningEvent.removeListener(listener);
- _this._checkRunningEvents(runningEvent);
- };
- event.getBlock = function () { return _this.provider.getBlock(log.blockHash); };
- event.getTransaction = function () { return _this.provider.getTransaction(log.transactionHash); };
- event.getTransactionReceipt = function () { return _this.provider.getTransactionReceipt(log.transactionHash); };
- // This may throw if the topics and data mismatch the signature
- runningEvent.prepareEvent(event);
- return event;
- };
- BaseContract.prototype._addEventListener = function (runningEvent, listener, once) {
- var _this = this;
- if (!this.provider) {
- logger.throwError("events require a provider or a signer with a provider", lib.Logger.errors.UNSUPPORTED_OPERATION, { operation: "once" });
- }
- runningEvent.addListener(listener, once);
- // Track this running event and its listeners (may already be there; but no hard in updating)
- this._runningEvents[runningEvent.tag] = runningEvent;
- // If we are not polling the provider, start polling
- if (!this._wrappedEmits[runningEvent.tag]) {
- var wrappedEmit = function (log) {
- var event = _this._wrapEvent(runningEvent, log, listener);
- // Try to emit the result for the parameterized event...
- if (event.decodeError == null) {
- try {
- var args = runningEvent.getEmit(event);
- _this.emit.apply(_this, __spreadArray([runningEvent.filter], args, false));
- }
- catch (error) {
- event.decodeError = error.error;
- }
- }
- // Always emit "event" for fragment-base events
- if (runningEvent.filter != null) {
- _this.emit("event", event);
- }
- // Emit "error" if there was an error
- if (event.decodeError != null) {
- _this.emit("error", event.decodeError, event);
- }
- };
- this._wrappedEmits[runningEvent.tag] = wrappedEmit;
- // Special events, like "error" do not have a filter
- if (runningEvent.filter != null) {
- this.provider.on(runningEvent.filter, wrappedEmit);
- }
- }
- };
- BaseContract.prototype.queryFilter = function (event, fromBlockOrBlockhash, toBlock) {
- var _this = this;
- var runningEvent = this._getRunningEvent(event);
- var filter = (0, lib$3.shallowCopy)(runningEvent.filter);
- if (typeof (fromBlockOrBlockhash) === "string" && (0, lib$1.isHexString)(fromBlockOrBlockhash, 32)) {
- if (toBlock != null) {
- logger.throwArgumentError("cannot specify toBlock with blockhash", "toBlock", toBlock);
- }
- filter.blockHash = fromBlockOrBlockhash;
- }
- else {
- filter.fromBlock = ((fromBlockOrBlockhash != null) ? fromBlockOrBlockhash : 0);
- filter.toBlock = ((toBlock != null) ? toBlock : "latest");
- }
- return this.provider.getLogs(filter).then(function (logs) {
- return logs.map(function (log) { return _this._wrapEvent(runningEvent, log, null); });
- });
- };
- BaseContract.prototype.on = function (event, listener) {
- this._addEventListener(this._getRunningEvent(event), listener, false);
- return this;
- };
- BaseContract.prototype.once = function (event, listener) {
- this._addEventListener(this._getRunningEvent(event), listener, true);
- return this;
- };
- BaseContract.prototype.emit = function (eventName) {
- var args = [];
- for (var _i = 1; _i < arguments.length; _i++) {
- args[_i - 1] = arguments[_i];
- }
- if (!this.provider) {
- return false;
- }
- var runningEvent = this._getRunningEvent(eventName);
- var result = (runningEvent.run(args) > 0);
- // May have drained all the "once" events; check for living events
- this._checkRunningEvents(runningEvent);
- return result;
- };
- BaseContract.prototype.listenerCount = function (eventName) {
- var _this = this;
- if (!this.provider) {
- return 0;
- }
- if (eventName == null) {
- return Object.keys(this._runningEvents).reduce(function (accum, key) {
- return accum + _this._runningEvents[key].listenerCount();
- }, 0);
- }
- return this._getRunningEvent(eventName).listenerCount();
- };
- BaseContract.prototype.listeners = function (eventName) {
- if (!this.provider) {
- return [];
- }
- if (eventName == null) {
- var result_1 = [];
- for (var tag in this._runningEvents) {
- this._runningEvents[tag].listeners().forEach(function (listener) {
- result_1.push(listener);
- });
- }
- return result_1;
- }
- return this._getRunningEvent(eventName).listeners();
- };
- BaseContract.prototype.removeAllListeners = function (eventName) {
- if (!this.provider) {
- return this;
- }
- if (eventName == null) {
- for (var tag in this._runningEvents) {
- var runningEvent_1 = this._runningEvents[tag];
- runningEvent_1.removeAllListeners();
- this._checkRunningEvents(runningEvent_1);
- }
- return this;
- }
- // Delete any listeners
- var runningEvent = this._getRunningEvent(eventName);
- runningEvent.removeAllListeners();
- this._checkRunningEvents(runningEvent);
- return this;
- };
- BaseContract.prototype.off = function (eventName, listener) {
- if (!this.provider) {
- return this;
- }
- var runningEvent = this._getRunningEvent(eventName);
- runningEvent.removeListener(listener);
- this._checkRunningEvents(runningEvent);
- return this;
- };
- BaseContract.prototype.removeListener = function (eventName, listener) {
- return this.off(eventName, listener);
- };
- return BaseContract;
- }());
- exports.BaseContract = BaseContract;
- var Contract = /** @class */ (function (_super) {
- __extends(Contract, _super);
- function Contract() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- return Contract;
- }(BaseContract));
- exports.Contract = Contract;
- var ContractFactory = /** @class */ (function () {
- function ContractFactory(contractInterface, bytecode, signer) {
- var _newTarget = this.constructor;
- var bytecodeHex = null;
- if (typeof (bytecode) === "string") {
- bytecodeHex = bytecode;
- }
- else if ((0, lib$1.isBytes)(bytecode)) {
- bytecodeHex = (0, lib$1.hexlify)(bytecode);
- }
- else if (bytecode && typeof (bytecode.object) === "string") {
- // Allow the bytecode object from the Solidity compiler
- bytecodeHex = bytecode.object;
- }
- else {
- // Crash in the next verification step
- bytecodeHex = "!";
- }
- // Make sure it is 0x prefixed
- if (bytecodeHex.substring(0, 2) !== "0x") {
- bytecodeHex = "0x" + bytecodeHex;
- }
- // Make sure the final result is valid bytecode
- if (!(0, lib$1.isHexString)(bytecodeHex) || (bytecodeHex.length % 2)) {
- logger.throwArgumentError("invalid bytecode", "bytecode", bytecode);
- }
- // If we have a signer, make sure it is valid
- if (signer && !lib$c.Signer.isSigner(signer)) {
- logger.throwArgumentError("invalid signer", "signer", signer);
- }
- (0, lib$3.defineReadOnly)(this, "bytecode", bytecodeHex);
- (0, lib$3.defineReadOnly)(this, "interface", (0, lib$3.getStatic)(_newTarget, "getInterface")(contractInterface));
- (0, lib$3.defineReadOnly)(this, "signer", signer || null);
- }
- // @TODO: Future; rename to populateTransaction?
- ContractFactory.prototype.getDeployTransaction = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- var tx = {};
- // If we have 1 additional argument, we allow transaction overrides
- if (args.length === this.interface.deploy.inputs.length + 1 && typeof (args[args.length - 1]) === "object") {
- tx = (0, lib$3.shallowCopy)(args.pop());
- for (var key in tx) {
- if (!allowedTransactionKeys[key]) {
- throw new Error("unknown transaction override " + key);
- }
- }
- }
- // Do not allow these to be overridden in a deployment transaction
- ["data", "from", "to"].forEach(function (key) {
- if (tx[key] == null) {
- return;
- }
- logger.throwError("cannot override " + key, lib.Logger.errors.UNSUPPORTED_OPERATION, { operation: key });
- });
- if (tx.value) {
- var value = lib$2.BigNumber.from(tx.value);
- if (!value.isZero() && !this.interface.deploy.payable) {
- logger.throwError("non-payable constructor cannot override value", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "overrides.value",
- value: tx.value
- });
- }
- }
- // Make sure the call matches the constructor signature
- logger.checkArgumentCount(args.length, this.interface.deploy.inputs.length, " in Contract constructor");
- // Set the data to the bytecode + the encoded constructor arguments
- tx.data = (0, lib$1.hexlify)((0, lib$1.concat)([
- this.bytecode,
- this.interface.encodeDeploy(args)
- ]));
- return tx;
- };
- ContractFactory.prototype.deploy = function () {
- var args = [];
- for (var _i = 0; _i < arguments.length; _i++) {
- args[_i] = arguments[_i];
- }
- return __awaiter(this, void 0, void 0, function () {
- var overrides, params, unsignedTx, tx, address, contract;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- overrides = {};
- // If 1 extra parameter was passed in, it contains overrides
- if (args.length === this.interface.deploy.inputs.length + 1) {
- overrides = args.pop();
- }
- // Make sure the call matches the constructor signature
- logger.checkArgumentCount(args.length, this.interface.deploy.inputs.length, " in Contract constructor");
- return [4 /*yield*/, resolveAddresses(this.signer, args, this.interface.deploy.inputs)];
- case 1:
- params = _a.sent();
- params.push(overrides);
- unsignedTx = this.getDeployTransaction.apply(this, params);
- return [4 /*yield*/, this.signer.sendTransaction(unsignedTx)];
- case 2:
- tx = _a.sent();
- address = (0, lib$3.getStatic)(this.constructor, "getContractAddress")(tx);
- contract = (0, lib$3.getStatic)(this.constructor, "getContract")(address, this.interface, this.signer);
- // Add the modified wait that wraps events
- addContractWait(contract, tx);
- (0, lib$3.defineReadOnly)(contract, "deployTransaction", tx);
- return [2 /*return*/, contract];
- }
- });
- });
- };
- ContractFactory.prototype.attach = function (address) {
- return (this.constructor).getContract(address, this.interface, this.signer);
- };
- ContractFactory.prototype.connect = function (signer) {
- return new (this.constructor)(this.interface, this.bytecode, signer);
- };
- ContractFactory.fromSolidity = function (compilerOutput, signer) {
- if (compilerOutput == null) {
- logger.throwError("missing compiler output", lib.Logger.errors.MISSING_ARGUMENT, { argument: "compilerOutput" });
- }
- if (typeof (compilerOutput) === "string") {
- compilerOutput = JSON.parse(compilerOutput);
- }
- var abi = compilerOutput.abi;
- var bytecode = null;
- if (compilerOutput.bytecode) {
- bytecode = compilerOutput.bytecode;
- }
- else if (compilerOutput.evm && compilerOutput.evm.bytecode) {
- bytecode = compilerOutput.evm.bytecode;
- }
- return new this(abi, bytecode, signer);
- };
- ContractFactory.getInterface = function (contractInterface) {
- return Contract.getInterface(contractInterface);
- };
- ContractFactory.getContractAddress = function (tx) {
- return (0, lib$6.getContractAddress)(tx);
- };
- ContractFactory.getContract = function (address, contractInterface, signer) {
- return new Contract(address, contractInterface, signer);
- };
- return ContractFactory;
- }());
- exports.ContractFactory = ContractFactory;
- });
- var index$f = /*@__PURE__*/getDefaultExportFromCjs(lib$f);
- var lib$g = createCommonjsModule(function (module, exports) {
- "use strict";
- /**
- * var basex = require("base-x");
- *
- * This implementation is heavily based on base-x. The main reason to
- * deviate was to prevent the dependency of Buffer.
- *
- * Contributors:
- *
- * base-x encoding
- * Forked from https://github.com/cryptocoinjs/bs58
- * Originally written by Mike Hearn for BitcoinJ
- * Copyright (c) 2011 Google Inc
- * Ported to JavaScript by Stefan Thomas
- * Merged Buffer refactorings from base58-native by Stephen Pair
- * Copyright (c) 2013 BitPay Inc
- *
- * The MIT License (MIT)
- *
- * Copyright base-x contributors (c) 2016
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
- * IN THE SOFTWARE.
- *
- */
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Base58 = exports.Base32 = exports.BaseX = void 0;
- var BaseX = /** @class */ (function () {
- function BaseX(alphabet) {
- (0, lib$3.defineReadOnly)(this, "alphabet", alphabet);
- (0, lib$3.defineReadOnly)(this, "base", alphabet.length);
- (0, lib$3.defineReadOnly)(this, "_alphabetMap", {});
- (0, lib$3.defineReadOnly)(this, "_leader", alphabet.charAt(0));
- // pre-compute lookup table
- for (var i = 0; i < alphabet.length; i++) {
- this._alphabetMap[alphabet.charAt(i)] = i;
- }
- }
- BaseX.prototype.encode = function (value) {
- var source = (0, lib$1.arrayify)(value);
- if (source.length === 0) {
- return "";
- }
- var digits = [0];
- for (var i = 0; i < source.length; ++i) {
- var carry = source[i];
- for (var j = 0; j < digits.length; ++j) {
- carry += digits[j] << 8;
- digits[j] = carry % this.base;
- carry = (carry / this.base) | 0;
- }
- while (carry > 0) {
- digits.push(carry % this.base);
- carry = (carry / this.base) | 0;
- }
- }
- var string = "";
- // deal with leading zeros
- for (var k = 0; source[k] === 0 && k < source.length - 1; ++k) {
- string += this._leader;
- }
- // convert digits to a string
- for (var q = digits.length - 1; q >= 0; --q) {
- string += this.alphabet[digits[q]];
- }
- return string;
- };
- BaseX.prototype.decode = function (value) {
- if (typeof (value) !== "string") {
- throw new TypeError("Expected String");
- }
- var bytes = [];
- if (value.length === 0) {
- return new Uint8Array(bytes);
- }
- bytes.push(0);
- for (var i = 0; i < value.length; i++) {
- var byte = this._alphabetMap[value[i]];
- if (byte === undefined) {
- throw new Error("Non-base" + this.base + " character");
- }
- var carry = byte;
- for (var j = 0; j < bytes.length; ++j) {
- carry += bytes[j] * this.base;
- bytes[j] = carry & 0xff;
- carry >>= 8;
- }
- while (carry > 0) {
- bytes.push(carry & 0xff);
- carry >>= 8;
- }
- }
- // deal with leading zeros
- for (var k = 0; value[k] === this._leader && k < value.length - 1; ++k) {
- bytes.push(0);
- }
- return (0, lib$1.arrayify)(new Uint8Array(bytes.reverse()));
- };
- return BaseX;
- }());
- exports.BaseX = BaseX;
- var Base32 = new BaseX("abcdefghijklmnopqrstuvwxyz234567");
- exports.Base32 = Base32;
- var Base58 = new BaseX("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
- exports.Base58 = Base58;
- //console.log(Base58.decode("Qmd2V777o5XvJbYMeMb8k2nU5f8d3ciUQ5YpYuWhzv8iDj"))
- //console.log(Base58.encode(Base58.decode("Qmd2V777o5XvJbYMeMb8k2nU5f8d3ciUQ5YpYuWhzv8iDj")))
- });
- var index$g = /*@__PURE__*/getDefaultExportFromCjs(lib$g);
- var types = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.SupportedAlgorithm = void 0;
- var SupportedAlgorithm;
- (function (SupportedAlgorithm) {
- SupportedAlgorithm["sha256"] = "sha256";
- SupportedAlgorithm["sha512"] = "sha512";
- })(SupportedAlgorithm = exports.SupportedAlgorithm || (exports.SupportedAlgorithm = {}));
- ;
- });
- var types$1 = /*@__PURE__*/getDefaultExportFromCjs(types);
- var _version$s = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "sha2/5.6.0";
- });
- var _version$t = /*@__PURE__*/getDefaultExportFromCjs(_version$s);
- var browserSha2 = createCommonjsModule(function (module, exports) {
- "use strict";
- var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.computeHmac = exports.sha512 = exports.sha256 = exports.ripemd160 = void 0;
- var hash_js_1 = __importDefault(hash_1);
- //const _ripemd160 = _hash.ripemd160;
- var logger = new lib.Logger(_version$s.version);
- function ripemd160(data) {
- return "0x" + (hash_js_1.default.ripemd160().update((0, lib$1.arrayify)(data)).digest("hex"));
- }
- exports.ripemd160 = ripemd160;
- function sha256(data) {
- return "0x" + (hash_js_1.default.sha256().update((0, lib$1.arrayify)(data)).digest("hex"));
- }
- exports.sha256 = sha256;
- function sha512(data) {
- return "0x" + (hash_js_1.default.sha512().update((0, lib$1.arrayify)(data)).digest("hex"));
- }
- exports.sha512 = sha512;
- function computeHmac(algorithm, key, data) {
- if (!types.SupportedAlgorithm[algorithm]) {
- logger.throwError("unsupported algorithm " + algorithm, lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "hmac",
- algorithm: algorithm
- });
- }
- return "0x" + hash_js_1.default.hmac(hash_js_1.default[algorithm], (0, lib$1.arrayify)(key)).update((0, lib$1.arrayify)(data)).digest("hex");
- }
- exports.computeHmac = computeHmac;
- });
- var browserSha2$1 = /*@__PURE__*/getDefaultExportFromCjs(browserSha2);
- var lib$h = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.SupportedAlgorithm = exports.sha512 = exports.sha256 = exports.ripemd160 = exports.computeHmac = void 0;
- Object.defineProperty(exports, "computeHmac", { enumerable: true, get: function () { return browserSha2.computeHmac; } });
- Object.defineProperty(exports, "ripemd160", { enumerable: true, get: function () { return browserSha2.ripemd160; } });
- Object.defineProperty(exports, "sha256", { enumerable: true, get: function () { return browserSha2.sha256; } });
- Object.defineProperty(exports, "sha512", { enumerable: true, get: function () { return browserSha2.sha512; } });
- Object.defineProperty(exports, "SupportedAlgorithm", { enumerable: true, get: function () { return types.SupportedAlgorithm; } });
- });
- var index$h = /*@__PURE__*/getDefaultExportFromCjs(lib$h);
- var browserPbkdf2 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.pbkdf2 = void 0;
- function pbkdf2(password, salt, iterations, keylen, hashAlgorithm) {
- password = (0, lib$1.arrayify)(password);
- salt = (0, lib$1.arrayify)(salt);
- var hLen;
- var l = 1;
- var DK = new Uint8Array(keylen);
- var block1 = new Uint8Array(salt.length + 4);
- block1.set(salt);
- //salt.copy(block1, 0, 0, salt.length)
- var r;
- var T;
- for (var i = 1; i <= l; i++) {
- //block1.writeUInt32BE(i, salt.length)
- block1[salt.length] = (i >> 24) & 0xff;
- block1[salt.length + 1] = (i >> 16) & 0xff;
- block1[salt.length + 2] = (i >> 8) & 0xff;
- block1[salt.length + 3] = i & 0xff;
- //let U = createHmac(password).update(block1).digest();
- var U = (0, lib$1.arrayify)((0, lib$h.computeHmac)(hashAlgorithm, password, block1));
- if (!hLen) {
- hLen = U.length;
- T = new Uint8Array(hLen);
- l = Math.ceil(keylen / hLen);
- r = keylen - (l - 1) * hLen;
- }
- //U.copy(T, 0, 0, hLen)
- T.set(U);
- for (var j = 1; j < iterations; j++) {
- //U = createHmac(password).update(U).digest();
- U = (0, lib$1.arrayify)((0, lib$h.computeHmac)(hashAlgorithm, password, U));
- for (var k = 0; k < hLen; k++)
- T[k] ^= U[k];
- }
- var destPos = (i - 1) * hLen;
- var len = (i === l ? r : hLen);
- //T.copy(DK, destPos, 0, len)
- DK.set((0, lib$1.arrayify)(T).slice(0, len), destPos);
- }
- return (0, lib$1.hexlify)(DK);
- }
- exports.pbkdf2 = pbkdf2;
- });
- var browserPbkdf2$1 = /*@__PURE__*/getDefaultExportFromCjs(browserPbkdf2);
- var lib$i = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.pbkdf2 = void 0;
- Object.defineProperty(exports, "pbkdf2", { enumerable: true, get: function () { return browserPbkdf2.pbkdf2; } });
- });
- var index$i = /*@__PURE__*/getDefaultExportFromCjs(lib$i);
- var _version$u = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "wordlists/5.6.0";
- });
- var _version$v = /*@__PURE__*/getDefaultExportFromCjs(_version$u);
- var wordlist = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Wordlist = exports.logger = void 0;
- // This gets overridden by rollup
- var exportWordlist = false;
- exports.logger = new lib.Logger(_version$u.version);
- var Wordlist = /** @class */ (function () {
- function Wordlist(locale) {
- var _newTarget = this.constructor;
- exports.logger.checkAbstract(_newTarget, Wordlist);
- (0, lib$3.defineReadOnly)(this, "locale", locale);
- }
- // Subclasses may override this
- Wordlist.prototype.split = function (mnemonic) {
- return mnemonic.toLowerCase().split(/ +/g);
- };
- // Subclasses may override this
- Wordlist.prototype.join = function (words) {
- return words.join(" ");
- };
- Wordlist.check = function (wordlist) {
- var words = [];
- for (var i = 0; i < 2048; i++) {
- var word = wordlist.getWord(i);
- /* istanbul ignore if */
- if (i !== wordlist.getWordIndex(word)) {
- return "0x";
- }
- words.push(word);
- }
- return (0, lib$9.id)(words.join("\n") + "\n");
- };
- Wordlist.register = function (lang, name) {
- if (!name) {
- name = lang.locale;
- }
- /* istanbul ignore if */
- if (exportWordlist) {
- try {
- var anyGlobal = window;
- if (anyGlobal._ethers && anyGlobal._ethers.wordlists) {
- if (!anyGlobal._ethers.wordlists[name]) {
- (0, lib$3.defineReadOnly)(anyGlobal._ethers.wordlists, name, lang);
- }
- }
- }
- catch (error) { }
- }
- };
- return Wordlist;
- }());
- exports.Wordlist = Wordlist;
- });
- var wordlist$1 = /*@__PURE__*/getDefaultExportFromCjs(wordlist);
- var langEn_1 = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.langEn = void 0;
- var words = "AbandonAbilityAbleAboutAboveAbsentAbsorbAbstractAbsurdAbuseAccessAccidentAccountAccuseAchieveAcidAcousticAcquireAcrossActActionActorActressActualAdaptAddAddictAddressAdjustAdmitAdultAdvanceAdviceAerobicAffairAffordAfraidAgainAgeAgentAgreeAheadAimAirAirportAisleAlarmAlbumAlcoholAlertAlienAllAlleyAllowAlmostAloneAlphaAlreadyAlsoAlterAlwaysAmateurAmazingAmongAmountAmusedAnalystAnchorAncientAngerAngleAngryAnimalAnkleAnnounceAnnualAnotherAnswerAntennaAntiqueAnxietyAnyApartApologyAppearAppleApproveAprilArchArcticAreaArenaArgueArmArmedArmorArmyAroundArrangeArrestArriveArrowArtArtefactArtistArtworkAskAspectAssaultAssetAssistAssumeAsthmaAthleteAtomAttackAttendAttitudeAttractAuctionAuditAugustAuntAuthorAutoAutumnAverageAvocadoAvoidAwakeAwareAwayAwesomeAwfulAwkwardAxisBabyBachelorBaconBadgeBagBalanceBalconyBallBambooBananaBannerBarBarelyBargainBarrelBaseBasicBasketBattleBeachBeanBeautyBecauseBecomeBeefBeforeBeginBehaveBehindBelieveBelowBeltBenchBenefitBestBetrayBetterBetweenBeyondBicycleBidBikeBindBiologyBirdBirthBitterBlackBladeBlameBlanketBlastBleakBlessBlindBloodBlossomBlouseBlueBlurBlushBoardBoatBodyBoilBombBoneBonusBookBoostBorderBoringBorrowBossBottomBounceBoxBoyBracketBrainBrandBrassBraveBreadBreezeBrickBridgeBriefBrightBringBriskBroccoliBrokenBronzeBroomBrotherBrownBrushBubbleBuddyBudgetBuffaloBuildBulbBulkBulletBundleBunkerBurdenBurgerBurstBusBusinessBusyButterBuyerBuzzCabbageCabinCableCactusCageCakeCallCalmCameraCampCanCanalCancelCandyCannonCanoeCanvasCanyonCapableCapitalCaptainCarCarbonCardCargoCarpetCarryCartCaseCashCasinoCastleCasualCatCatalogCatchCategoryCattleCaughtCauseCautionCaveCeilingCeleryCementCensusCenturyCerealCertainChairChalkChampionChangeChaosChapterChargeChaseChatCheapCheckCheeseChefCherryChestChickenChiefChildChimneyChoiceChooseChronicChuckleChunkChurnCigarCinnamonCircleCitizenCityCivilClaimClapClarifyClawClayCleanClerkCleverClickClientCliffClimbClinicClipClockClogCloseClothCloudClownClubClumpClusterClutchCoachCoastCoconutCodeCoffeeCoilCoinCollectColorColumnCombineComeComfortComicCommonCompanyConcertConductConfirmCongressConnectConsiderControlConvinceCookCoolCopperCopyCoralCoreCornCorrectCostCottonCouchCountryCoupleCourseCousinCoverCoyoteCrackCradleCraftCramCraneCrashCraterCrawlCrazyCreamCreditCreekCrewCricketCrimeCrispCriticCropCrossCrouchCrowdCrucialCruelCruiseCrumbleCrunchCrushCryCrystalCubeCultureCupCupboardCuriousCurrentCurtainCurveCushionCustomCuteCycleDadDamageDampDanceDangerDaringDashDaughterDawnDayDealDebateDebrisDecadeDecemberDecideDeclineDecorateDecreaseDeerDefenseDefineDefyDegreeDelayDeliverDemandDemiseDenialDentistDenyDepartDependDepositDepthDeputyDeriveDescribeDesertDesignDeskDespairDestroyDetailDetectDevelopDeviceDevoteDiagramDialDiamondDiaryDiceDieselDietDifferDigitalDignityDilemmaDinnerDinosaurDirectDirtDisagreeDiscoverDiseaseDishDismissDisorderDisplayDistanceDivertDivideDivorceDizzyDoctorDocumentDogDollDolphinDomainDonateDonkeyDonorDoorDoseDoubleDoveDraftDragonDramaDrasticDrawDreamDressDriftDrillDrinkDripDriveDropDrumDryDuckDumbDuneDuringDustDutchDutyDwarfDynamicEagerEagleEarlyEarnEarthEasilyEastEasyEchoEcologyEconomyEdgeEditEducateEffortEggEightEitherElbowElderElectricElegantElementElephantElevatorEliteElseEmbarkEmbodyEmbraceEmergeEmotionEmployEmpowerEmptyEnableEnactEndEndlessEndorseEnemyEnergyEnforceEngageEngineEnhanceEnjoyEnlistEnoughEnrichEnrollEnsureEnterEntireEntryEnvelopeEpisodeEqualEquipEraEraseErodeErosionErrorEruptEscapeEssayEssenceEstateEternalEthicsEvidenceEvilEvokeEvolveExactExampleExcessExchangeExciteExcludeExcuseExecuteExerciseExhaustExhibitExileExistExitExoticExpandExpectExpireExplainExposeExpressExtendExtraEyeEyebrowFabricFaceFacultyFadeFaintFaithFallFalseFameFamilyFamousFanFancyFantasyFarmFashionFatFatalFatherFatigueFaultFavoriteFeatureFebruaryFederalFeeFeedFeelFemaleFenceFestivalFetchFeverFewFiberFictionFieldFigureFileFilmFilterFinalFindFineFingerFinishFireFirmFirstFiscalFishFitFitnessFixFlagFlameFlashFlatFlavorFleeFlightFlipFloatFlockFloorFlowerFluidFlushFlyFoamFocusFogFoilFoldFollowFoodFootForceForestForgetForkFortuneForumForwardFossilFosterFoundFoxFragileFrameFrequentFreshFriendFringeFrogFrontFrostFrownFrozenFruitFuelFunFunnyFurnaceFuryFutureGadgetGainGalaxyGalleryGameGapGarageGarbageGardenGarlicGarmentGasGaspGateGatherGaugeGazeGeneralGeniusGenreGentleGenuineGestureGhostGiantGiftGiggleGingerGiraffeGirlGiveGladGlanceGlareGlassGlideGlimpseGlobeGloomGloryGloveGlowGlueGoatGoddessGoldGoodGooseGorillaGospelGossipGovernGownGrabGraceGrainGrantGrapeGrassGravityGreatGreenGridGriefGritGroceryGroupGrowGruntGuardGuessGuideGuiltGuitarGunGymHabitHairHalfHammerHamsterHandHappyHarborHardHarshHarvestHatHaveHawkHazardHeadHealthHeartHeavyHedgehogHeightHelloHelmetHelpHenHeroHiddenHighHillHintHipHireHistoryHobbyHockeyHoldHoleHolidayHollowHomeHoneyHoodHopeHornHorrorHorseHospitalHostHotelHourHoverHubHugeHumanHumbleHumorHundredHungryHuntHurdleHurryHurtHusbandHybridIceIconIdeaIdentifyIdleIgnoreIllIllegalIllnessImageImitateImmenseImmuneImpactImposeImproveImpulseInchIncludeIncomeIncreaseIndexIndicateIndoorIndustryInfantInflictInformInhaleInheritInitialInjectInjuryInmateInnerInnocentInputInquiryInsaneInsectInsideInspireInstallIntactInterestIntoInvestInviteInvolveIronIslandIsolateIssueItemIvoryJacketJaguarJarJazzJealousJeansJellyJewelJobJoinJokeJourneyJoyJudgeJuiceJumpJungleJuniorJunkJustKangarooKeenKeepKetchupKeyKickKidKidneyKindKingdomKissKitKitchenKiteKittenKiwiKneeKnifeKnockKnowLabLabelLaborLadderLadyLakeLampLanguageLaptopLargeLaterLatinLaughLaundryLavaLawLawnLawsuitLayerLazyLeaderLeafLearnLeaveLectureLeftLegLegalLegendLeisureLemonLendLengthLensLeopardLessonLetterLevelLiarLibertyLibraryLicenseLifeLiftLightLikeLimbLimitLinkLionLiquidListLittleLiveLizardLoadLoanLobsterLocalLockLogicLonelyLongLoopLotteryLoudLoungeLoveLoyalLuckyLuggageLumberLunarLunchLuxuryLyricsMachineMadMagicMagnetMaidMailMainMajorMakeMammalManManageMandateMangoMansionManualMapleMarbleMarchMarginMarineMarketMarriageMaskMassMasterMatchMaterialMathMatrixMatterMaximumMazeMeadowMeanMeasureMeatMechanicMedalMediaMelodyMeltMemberMemoryMentionMenuMercyMergeMeritMerryMeshMessageMetalMethodMiddleMidnightMilkMillionMimicMindMinimumMinorMinuteMiracleMirrorMiseryMissMistakeMixMixedMixtureMobileModelModifyMomMomentMonitorMonkeyMonsterMonthMoonMoralMoreMorningMosquitoMotherMotionMotorMountainMouseMoveMovieMuchMuffinMuleMultiplyMuscleMuseumMushroomMusicMustMutualMyselfMysteryMythNaiveNameNapkinNarrowNastyNationNatureNearNeckNeedNegativeNeglectNeitherNephewNerveNestNetNetworkNeutralNeverNewsNextNiceNightNobleNoiseNomineeNoodleNormalNorthNoseNotableNoteNothingNoticeNovelNowNuclearNumberNurseNutOakObeyObjectObligeObscureObserveObtainObviousOccurOceanOctoberOdorOffOfferOfficeOftenOilOkayOldOliveOlympicOmitOnceOneOnionOnlineOnlyOpenOperaOpinionOpposeOptionOrangeOrbitOrchardOrderOrdinaryOrganOrientOriginalOrphanOstrichOtherOutdoorOuterOutputOutsideOvalOvenOverOwnOwnerOxygenOysterOzonePactPaddlePagePairPalacePalmPandaPanelPanicPantherPaperParadeParentParkParrotPartyPassPatchPathPatientPatrolPatternPausePavePaymentPeacePeanutPearPeasantPelicanPenPenaltyPencilPeoplePepperPerfectPermitPersonPetPhonePhotoPhrasePhysicalPianoPicnicPicturePiecePigPigeonPillPilotPinkPioneerPipePistolPitchPizzaPlacePlanetPlasticPlatePlayPleasePledgePluckPlugPlungePoemPoetPointPolarPolePolicePondPonyPoolPopularPortionPositionPossiblePostPotatoPotteryPovertyPowderPowerPracticePraisePredictPreferPreparePresentPrettyPreventPricePridePrimaryPrintPriorityPrisonPrivatePrizeProblemProcessProduceProfitProgramProjectPromoteProofPropertyProsperProtectProudProvidePublicPuddingPullPulpPulsePumpkinPunchPupilPuppyPurchasePurityPurposePursePushPutPuzzlePyramidQualityQuantumQuarterQuestionQuickQuitQuizQuoteRabbitRaccoonRaceRackRadarRadioRailRainRaiseRallyRampRanchRandomRangeRapidRareRateRatherRavenRawRazorReadyRealReasonRebelRebuildRecallReceiveRecipeRecordRecycleReduceReflectReformRefuseRegionRegretRegularRejectRelaxReleaseReliefRelyRemainRememberRemindRemoveRenderRenewRentReopenRepairRepeatReplaceReportRequireRescueResembleResistResourceResponseResultRetireRetreatReturnReunionRevealReviewRewardRhythmRibRibbonRiceRichRideRidgeRifleRightRigidRingRiotRippleRiskRitualRivalRiverRoadRoastRobotRobustRocketRomanceRoofRookieRoomRoseRotateRoughRoundRouteRoyalRubberRudeRugRuleRunRunwayRuralSadSaddleSadnessSafeSailSaladSalmonSalonSaltSaluteSameSampleSandSatisfySatoshiSauceSausageSaveSayScaleScanScareScatterSceneSchemeSchoolScienceScissorsScorpionScoutScrapScreenScriptScrubSeaSearchSeasonSeatSecondSecretSectionSecuritySeedSeekSegmentSelectSellSeminarSeniorSenseSentenceSeriesServiceSessionSettleSetupSevenShadowShaftShallowShareShedShellSheriffShieldShiftShineShipShiverShockShoeShootShopShortShoulderShoveShrimpShrugShuffleShySiblingSickSideSiegeSightSignSilentSilkSillySilverSimilarSimpleSinceSingSirenSisterSituateSixSizeSkateSketchSkiSkillSkinSkirtSkullSlabSlamSleepSlenderSliceSlideSlightSlimSloganSlotSlowSlushSmallSmartSmileSmokeSmoothSnackSnakeSnapSniffSnowSoapSoccerSocialSockSodaSoftSolarSoldierSolidSolutionSolveSomeoneSongSoonSorrySortSoulSoundSoupSourceSouthSpaceSpareSpatialSpawnSpeakSpecialSpeedSpellSpendSphereSpiceSpiderSpikeSpinSpiritSplitSpoilSponsorSpoonSportSpotSpraySpreadSpringSpySquareSqueezeSquirrelStableStadiumStaffStageStairsStampStandStartStateStaySteakSteelStemStepStereoStickStillStingStockStomachStoneStoolStoryStoveStrategyStreetStrikeStrongStruggleStudentStuffStumbleStyleSubjectSubmitSubwaySuccessSuchSuddenSufferSugarSuggestSuitSummerSunSunnySunsetSuperSupplySupremeSureSurfaceSurgeSurpriseSurroundSurveySuspectSustainSwallowSwampSwapSwarmSwearSweetSwiftSwimSwingSwitchSwordSymbolSymptomSyrupSystemTableTackleTagTailTalentTalkTankTapeTargetTaskTasteTattooTaxiTeachTeamTellTenTenantTennisTentTermTestTextThankThatThemeThenTheoryThereTheyThingThisThoughtThreeThriveThrowThumbThunderTicketTideTigerTiltTimberTimeTinyTipTiredTissueTitleToastTobaccoTodayToddlerToeTogetherToiletTokenTomatoTomorrowToneTongueTonightToolToothTopTopicToppleTorchTornadoTortoiseTossTotalTouristTowardTowerTownToyTrackTradeTrafficTragicTrainTransferTrapTrashTravelTrayTreatTreeTrendTrialTribeTrickTriggerTrimTripTrophyTroubleTruckTrueTrulyTrumpetTrustTruthTryTubeTuitionTumbleTunaTunnelTurkeyTurnTurtleTwelveTwentyTwiceTwinTwistTwoTypeTypicalUglyUmbrellaUnableUnawareUncleUncoverUnderUndoUnfairUnfoldUnhappyUniformUniqueUnitUniverseUnknownUnlockUntilUnusualUnveilUpdateUpgradeUpholdUponUpperUpsetUrbanUrgeUsageUseUsedUsefulUselessUsualUtilityVacantVacuumVagueValidValleyValveVanVanishVaporVariousVastVaultVehicleVelvetVendorVentureVenueVerbVerifyVersionVeryVesselVeteranViableVibrantViciousVictoryVideoViewVillageVintageViolinVirtualVirusVisaVisitVisualVitalVividVocalVoiceVoidVolcanoVolumeVoteVoyageWageWagonWaitWalkWallWalnutWantWarfareWarmWarriorWashWaspWasteWaterWaveWayWealthWeaponWearWeaselWeatherWebWeddingWeekendWeirdWelcomeWestWetWhaleWhatWheatWheelWhenWhereWhipWhisperWideWidthWifeWildWillWinWindowWineWingWinkWinnerWinterWireWisdomWiseWishWitnessWolfWomanWonderWoodWoolWordWorkWorldWorryWorthWrapWreckWrestleWristWriteWrongYardYearYellowYouYoungYouthZebraZeroZoneZoo";
- var wordlist$1 = null;
- function loadWords(lang) {
- if (wordlist$1 != null) {
- return;
- }
- wordlist$1 = words.replace(/([A-Z])/g, " $1").toLowerCase().substring(1).split(" ");
- // Verify the computed list matches the official list
- /* istanbul ignore if */
- if (wordlist.Wordlist.check(lang) !== "0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60") {
- wordlist$1 = null;
- throw new Error("BIP39 Wordlist for en (English) FAILED");
- }
- }
- var LangEn = /** @class */ (function (_super) {
- __extends(LangEn, _super);
- function LangEn() {
- return _super.call(this, "en") || this;
- }
- LangEn.prototype.getWord = function (index) {
- loadWords(this);
- return wordlist$1[index];
- };
- LangEn.prototype.getWordIndex = function (word) {
- loadWords(this);
- return wordlist$1.indexOf(word);
- };
- return LangEn;
- }(wordlist.Wordlist));
- var langEn = new LangEn();
- exports.langEn = langEn;
- wordlist.Wordlist.register(langEn);
- });
- var langEn = /*@__PURE__*/getDefaultExportFromCjs(langEn_1);
- var browserWordlists = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.wordlists = void 0;
- exports.wordlists = {
- en: langEn_1.langEn
- };
- });
- var browserWordlists$1 = /*@__PURE__*/getDefaultExportFromCjs(browserWordlists);
- var lib$j = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.wordlists = exports.Wordlist = exports.logger = void 0;
- // Wordlists
- // See: https://github.com/bitcoin/bips/blob/master/bip-0039/bip-0039-wordlists.md
- Object.defineProperty(exports, "logger", { enumerable: true, get: function () { return wordlist.logger; } });
- Object.defineProperty(exports, "Wordlist", { enumerable: true, get: function () { return wordlist.Wordlist; } });
- Object.defineProperty(exports, "wordlists", { enumerable: true, get: function () { return browserWordlists.wordlists; } });
- });
- var index$j = /*@__PURE__*/getDefaultExportFromCjs(lib$j);
- var _version$w = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "hdnode/5.6.0";
- });
- var _version$x = /*@__PURE__*/getDefaultExportFromCjs(_version$w);
- var lib$k = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getAccountPath = exports.isValidMnemonic = exports.entropyToMnemonic = exports.mnemonicToEntropy = exports.mnemonicToSeed = exports.HDNode = exports.defaultPath = void 0;
- var logger = new lib.Logger(_version$w.version);
- var N = lib$2.BigNumber.from("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");
- // "Bitcoin seed"
- var MasterSecret = (0, lib$8.toUtf8Bytes)("Bitcoin seed");
- var HardenedBit = 0x80000000;
- // Returns a byte with the MSB bits set
- function getUpperMask(bits) {
- return ((1 << bits) - 1) << (8 - bits);
- }
- // Returns a byte with the LSB bits set
- function getLowerMask(bits) {
- return (1 << bits) - 1;
- }
- function bytes32(value) {
- return (0, lib$1.hexZeroPad)((0, lib$1.hexlify)(value), 32);
- }
- function base58check(data) {
- return lib$g.Base58.encode((0, lib$1.concat)([data, (0, lib$1.hexDataSlice)((0, lib$h.sha256)((0, lib$h.sha256)(data)), 0, 4)]));
- }
- function getWordlist(wordlist) {
- if (wordlist == null) {
- return lib$j.wordlists["en"];
- }
- if (typeof (wordlist) === "string") {
- var words = lib$j.wordlists[wordlist];
- if (words == null) {
- logger.throwArgumentError("unknown locale", "wordlist", wordlist);
- }
- return words;
- }
- return wordlist;
- }
- var _constructorGuard = {};
- exports.defaultPath = "m/44'/60'/0'/0/0";
- ;
- var HDNode = /** @class */ (function () {
- /**
- * This constructor should not be called directly.
- *
- * Please use:
- * - fromMnemonic
- * - fromSeed
- */
- function HDNode(constructorGuard, privateKey, publicKey, parentFingerprint, chainCode, index, depth, mnemonicOrPath) {
- var _newTarget = this.constructor;
- logger.checkNew(_newTarget, HDNode);
- /* istanbul ignore if */
- if (constructorGuard !== _constructorGuard) {
- throw new Error("HDNode constructor cannot be called directly");
- }
- if (privateKey) {
- var signingKey = new lib$d.SigningKey(privateKey);
- (0, lib$3.defineReadOnly)(this, "privateKey", signingKey.privateKey);
- (0, lib$3.defineReadOnly)(this, "publicKey", signingKey.compressedPublicKey);
- }
- else {
- (0, lib$3.defineReadOnly)(this, "privateKey", null);
- (0, lib$3.defineReadOnly)(this, "publicKey", (0, lib$1.hexlify)(publicKey));
- }
- (0, lib$3.defineReadOnly)(this, "parentFingerprint", parentFingerprint);
- (0, lib$3.defineReadOnly)(this, "fingerprint", (0, lib$1.hexDataSlice)((0, lib$h.ripemd160)((0, lib$h.sha256)(this.publicKey)), 0, 4));
- (0, lib$3.defineReadOnly)(this, "address", (0, lib$e.computeAddress)(this.publicKey));
- (0, lib$3.defineReadOnly)(this, "chainCode", chainCode);
- (0, lib$3.defineReadOnly)(this, "index", index);
- (0, lib$3.defineReadOnly)(this, "depth", depth);
- if (mnemonicOrPath == null) {
- // From a source that does not preserve the path (e.g. extended keys)
- (0, lib$3.defineReadOnly)(this, "mnemonic", null);
- (0, lib$3.defineReadOnly)(this, "path", null);
- }
- else if (typeof (mnemonicOrPath) === "string") {
- // From a source that does not preserve the mnemonic (e.g. neutered)
- (0, lib$3.defineReadOnly)(this, "mnemonic", null);
- (0, lib$3.defineReadOnly)(this, "path", mnemonicOrPath);
- }
- else {
- // From a fully qualified source
- (0, lib$3.defineReadOnly)(this, "mnemonic", mnemonicOrPath);
- (0, lib$3.defineReadOnly)(this, "path", mnemonicOrPath.path);
- }
- }
- Object.defineProperty(HDNode.prototype, "extendedKey", {
- get: function () {
- // We only support the mainnet values for now, but if anyone needs
- // testnet values, let me know. I believe current sentiment is that
- // we should always use mainnet, and use BIP-44 to derive the network
- // - Mainnet: public=0x0488B21E, private=0x0488ADE4
- // - Testnet: public=0x043587CF, private=0x04358394
- if (this.depth >= 256) {
- throw new Error("Depth too large!");
- }
- return base58check((0, lib$1.concat)([
- ((this.privateKey != null) ? "0x0488ADE4" : "0x0488B21E"),
- (0, lib$1.hexlify)(this.depth),
- this.parentFingerprint,
- (0, lib$1.hexZeroPad)((0, lib$1.hexlify)(this.index), 4),
- this.chainCode,
- ((this.privateKey != null) ? (0, lib$1.concat)(["0x00", this.privateKey]) : this.publicKey),
- ]));
- },
- enumerable: false,
- configurable: true
- });
- HDNode.prototype.neuter = function () {
- return new HDNode(_constructorGuard, null, this.publicKey, this.parentFingerprint, this.chainCode, this.index, this.depth, this.path);
- };
- HDNode.prototype._derive = function (index) {
- if (index > 0xffffffff) {
- throw new Error("invalid index - " + String(index));
- }
- // Base path
- var path = this.path;
- if (path) {
- path += "/" + (index & ~HardenedBit);
- }
- var data = new Uint8Array(37);
- if (index & HardenedBit) {
- if (!this.privateKey) {
- throw new Error("cannot derive child of neutered node");
- }
- // Data = 0x00 || ser_256(k_par)
- data.set((0, lib$1.arrayify)(this.privateKey), 1);
- // Hardened path
- if (path) {
- path += "'";
- }
- }
- else {
- // Data = ser_p(point(k_par))
- data.set((0, lib$1.arrayify)(this.publicKey));
- }
- // Data += ser_32(i)
- for (var i = 24; i >= 0; i -= 8) {
- data[33 + (i >> 3)] = ((index >> (24 - i)) & 0xff);
- }
- var I = (0, lib$1.arrayify)((0, lib$h.computeHmac)(lib$h.SupportedAlgorithm.sha512, this.chainCode, data));
- var IL = I.slice(0, 32);
- var IR = I.slice(32);
- // The private key
- var ki = null;
- // The public key
- var Ki = null;
- if (this.privateKey) {
- ki = bytes32(lib$2.BigNumber.from(IL).add(this.privateKey).mod(N));
- }
- else {
- var ek = new lib$d.SigningKey((0, lib$1.hexlify)(IL));
- Ki = ek._addPoint(this.publicKey);
- }
- var mnemonicOrPath = path;
- var srcMnemonic = this.mnemonic;
- if (srcMnemonic) {
- mnemonicOrPath = Object.freeze({
- phrase: srcMnemonic.phrase,
- path: path,
- locale: (srcMnemonic.locale || "en")
- });
- }
- return new HDNode(_constructorGuard, ki, Ki, this.fingerprint, bytes32(IR), index, this.depth + 1, mnemonicOrPath);
- };
- HDNode.prototype.derivePath = function (path) {
- var components = path.split("/");
- if (components.length === 0 || (components[0] === "m" && this.depth !== 0)) {
- throw new Error("invalid path - " + path);
- }
- if (components[0] === "m") {
- components.shift();
- }
- var result = this;
- for (var i = 0; i < components.length; i++) {
- var component = components[i];
- if (component.match(/^[0-9]+'$/)) {
- var index = parseInt(component.substring(0, component.length - 1));
- if (index >= HardenedBit) {
- throw new Error("invalid path index - " + component);
- }
- result = result._derive(HardenedBit + index);
- }
- else if (component.match(/^[0-9]+$/)) {
- var index = parseInt(component);
- if (index >= HardenedBit) {
- throw new Error("invalid path index - " + component);
- }
- result = result._derive(index);
- }
- else {
- throw new Error("invalid path component - " + component);
- }
- }
- return result;
- };
- HDNode._fromSeed = function (seed, mnemonic) {
- var seedArray = (0, lib$1.arrayify)(seed);
- if (seedArray.length < 16 || seedArray.length > 64) {
- throw new Error("invalid seed");
- }
- var I = (0, lib$1.arrayify)((0, lib$h.computeHmac)(lib$h.SupportedAlgorithm.sha512, MasterSecret, seedArray));
- return new HDNode(_constructorGuard, bytes32(I.slice(0, 32)), null, "0x00000000", bytes32(I.slice(32)), 0, 0, mnemonic);
- };
- HDNode.fromMnemonic = function (mnemonic, password, wordlist) {
- // If a locale name was passed in, find the associated wordlist
- wordlist = getWordlist(wordlist);
- // Normalize the case and spacing in the mnemonic (throws if the mnemonic is invalid)
- mnemonic = entropyToMnemonic(mnemonicToEntropy(mnemonic, wordlist), wordlist);
- return HDNode._fromSeed(mnemonicToSeed(mnemonic, password), {
- phrase: mnemonic,
- path: "m",
- locale: wordlist.locale
- });
- };
- HDNode.fromSeed = function (seed) {
- return HDNode._fromSeed(seed, null);
- };
- HDNode.fromExtendedKey = function (extendedKey) {
- var bytes = lib$g.Base58.decode(extendedKey);
- if (bytes.length !== 82 || base58check(bytes.slice(0, 78)) !== extendedKey) {
- logger.throwArgumentError("invalid extended key", "extendedKey", "[REDACTED]");
- }
- var depth = bytes[4];
- var parentFingerprint = (0, lib$1.hexlify)(bytes.slice(5, 9));
- var index = parseInt((0, lib$1.hexlify)(bytes.slice(9, 13)).substring(2), 16);
- var chainCode = (0, lib$1.hexlify)(bytes.slice(13, 45));
- var key = bytes.slice(45, 78);
- switch ((0, lib$1.hexlify)(bytes.slice(0, 4))) {
- // Public Key
- case "0x0488b21e":
- case "0x043587cf":
- return new HDNode(_constructorGuard, null, (0, lib$1.hexlify)(key), parentFingerprint, chainCode, index, depth, null);
- // Private Key
- case "0x0488ade4":
- case "0x04358394 ":
- if (key[0] !== 0) {
- break;
- }
- return new HDNode(_constructorGuard, (0, lib$1.hexlify)(key.slice(1)), null, parentFingerprint, chainCode, index, depth, null);
- }
- return logger.throwArgumentError("invalid extended key", "extendedKey", "[REDACTED]");
- };
- return HDNode;
- }());
- exports.HDNode = HDNode;
- function mnemonicToSeed(mnemonic, password) {
- if (!password) {
- password = "";
- }
- var salt = (0, lib$8.toUtf8Bytes)("mnemonic" + password, lib$8.UnicodeNormalizationForm.NFKD);
- return (0, lib$i.pbkdf2)((0, lib$8.toUtf8Bytes)(mnemonic, lib$8.UnicodeNormalizationForm.NFKD), salt, 2048, 64, "sha512");
- }
- exports.mnemonicToSeed = mnemonicToSeed;
- function mnemonicToEntropy(mnemonic, wordlist) {
- wordlist = getWordlist(wordlist);
- logger.checkNormalize();
- var words = wordlist.split(mnemonic);
- if ((words.length % 3) !== 0) {
- throw new Error("invalid mnemonic");
- }
- var entropy = (0, lib$1.arrayify)(new Uint8Array(Math.ceil(11 * words.length / 8)));
- var offset = 0;
- for (var i = 0; i < words.length; i++) {
- var index = wordlist.getWordIndex(words[i].normalize("NFKD"));
- if (index === -1) {
- throw new Error("invalid mnemonic");
- }
- for (var bit = 0; bit < 11; bit++) {
- if (index & (1 << (10 - bit))) {
- entropy[offset >> 3] |= (1 << (7 - (offset % 8)));
- }
- offset++;
- }
- }
- var entropyBits = 32 * words.length / 3;
- var checksumBits = words.length / 3;
- var checksumMask = getUpperMask(checksumBits);
- var checksum = (0, lib$1.arrayify)((0, lib$h.sha256)(entropy.slice(0, entropyBits / 8)))[0] & checksumMask;
- if (checksum !== (entropy[entropy.length - 1] & checksumMask)) {
- throw new Error("invalid checksum");
- }
- return (0, lib$1.hexlify)(entropy.slice(0, entropyBits / 8));
- }
- exports.mnemonicToEntropy = mnemonicToEntropy;
- function entropyToMnemonic(entropy, wordlist) {
- wordlist = getWordlist(wordlist);
- entropy = (0, lib$1.arrayify)(entropy);
- if ((entropy.length % 4) !== 0 || entropy.length < 16 || entropy.length > 32) {
- throw new Error("invalid entropy");
- }
- var indices = [0];
- var remainingBits = 11;
- for (var i = 0; i < entropy.length; i++) {
- // Consume the whole byte (with still more to go)
- if (remainingBits > 8) {
- indices[indices.length - 1] <<= 8;
- indices[indices.length - 1] |= entropy[i];
- remainingBits -= 8;
- // This byte will complete an 11-bit index
- }
- else {
- indices[indices.length - 1] <<= remainingBits;
- indices[indices.length - 1] |= entropy[i] >> (8 - remainingBits);
- // Start the next word
- indices.push(entropy[i] & getLowerMask(8 - remainingBits));
- remainingBits += 3;
- }
- }
- // Compute the checksum bits
- var checksumBits = entropy.length / 4;
- var checksum = (0, lib$1.arrayify)((0, lib$h.sha256)(entropy))[0] & getUpperMask(checksumBits);
- // Shift the checksum into the word indices
- indices[indices.length - 1] <<= checksumBits;
- indices[indices.length - 1] |= (checksum >> (8 - checksumBits));
- return wordlist.join(indices.map(function (index) { return wordlist.getWord(index); }));
- }
- exports.entropyToMnemonic = entropyToMnemonic;
- function isValidMnemonic(mnemonic, wordlist) {
- try {
- mnemonicToEntropy(mnemonic, wordlist);
- return true;
- }
- catch (error) { }
- return false;
- }
- exports.isValidMnemonic = isValidMnemonic;
- function getAccountPath(index) {
- if (typeof (index) !== "number" || index < 0 || index >= HardenedBit || index % 1) {
- logger.throwArgumentError("invalid account index", "index", index);
- }
- return "m/44'/60'/" + index + "'/0/0";
- }
- exports.getAccountPath = getAccountPath;
- });
- var index$k = /*@__PURE__*/getDefaultExportFromCjs(lib$k);
- var _version$y = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "random/5.6.0";
- });
- var _version$z = /*@__PURE__*/getDefaultExportFromCjs(_version$y);
- var browserRandom = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.randomBytes = void 0;
- var logger = new lib.Logger(_version$y.version);
- // Debugging line for testing browser lib in node
- //const window = { crypto: { getRandomValues: () => { } } };
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis
- function getGlobal() {
- if (typeof self !== 'undefined') {
- return self;
- }
- if (typeof window !== 'undefined') {
- return window;
- }
- if (typeof commonjsGlobal !== 'undefined') {
- return commonjsGlobal;
- }
- throw new Error('unable to locate global object');
- }
- ;
- var anyGlobal = getGlobal();
- var crypto = anyGlobal.crypto || anyGlobal.msCrypto;
- if (!crypto || !crypto.getRandomValues) {
- logger.warn("WARNING: Missing strong random number source");
- crypto = {
- getRandomValues: function (buffer) {
- return logger.throwError("no secure random source avaialble", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "crypto.getRandomValues"
- });
- }
- };
- }
- function randomBytes(length) {
- if (length <= 0 || length > 1024 || (length % 1) || length != length) {
- logger.throwArgumentError("invalid length", "length", length);
- }
- var result = new Uint8Array(length);
- crypto.getRandomValues(result);
- return (0, lib$1.arrayify)(result);
- }
- exports.randomBytes = randomBytes;
- ;
- });
- var browserRandom$1 = /*@__PURE__*/getDefaultExportFromCjs(browserRandom);
- var shuffle = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.shuffled = void 0;
- function shuffled(array) {
- array = array.slice();
- for (var i = array.length - 1; i > 0; i--) {
- var j = Math.floor(Math.random() * (i + 1));
- var tmp = array[i];
- array[i] = array[j];
- array[j] = tmp;
- }
- return array;
- }
- exports.shuffled = shuffled;
- });
- var shuffle$1 = /*@__PURE__*/getDefaultExportFromCjs(shuffle);
- var lib$l = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.shuffled = exports.randomBytes = void 0;
- Object.defineProperty(exports, "randomBytes", { enumerable: true, get: function () { return browserRandom.randomBytes; } });
- Object.defineProperty(exports, "shuffled", { enumerable: true, get: function () { return shuffle.shuffled; } });
- });
- var index$l = /*@__PURE__*/getDefaultExportFromCjs(lib$l);
- var aesJs = createCommonjsModule(function (module, exports) {
- "use strict";
- (function(root) {
- function checkInt(value) {
- return (parseInt(value) === value);
- }
- function checkInts(arrayish) {
- if (!checkInt(arrayish.length)) { return false; }
- for (var i = 0; i < arrayish.length; i++) {
- if (!checkInt(arrayish[i]) || arrayish[i] < 0 || arrayish[i] > 255) {
- return false;
- }
- }
- return true;
- }
- function coerceArray(arg, copy) {
- // ArrayBuffer view
- if (arg.buffer && ArrayBuffer.isView(arg) && arg.name === 'Uint8Array') {
- if (copy) {
- if (arg.slice) {
- arg = arg.slice();
- } else {
- arg = Array.prototype.slice.call(arg);
- }
- }
- return arg;
- }
- // It's an array; check it is a valid representation of a byte
- if (Array.isArray(arg)) {
- if (!checkInts(arg)) {
- throw new Error('Array contains invalid value: ' + arg);
- }
- return new Uint8Array(arg);
- }
- // Something else, but behaves like an array (maybe a Buffer? Arguments?)
- if (checkInt(arg.length) && checkInts(arg)) {
- return new Uint8Array(arg);
- }
- throw new Error('unsupported array-like object');
- }
- function createArray(length) {
- return new Uint8Array(length);
- }
- function copyArray(sourceArray, targetArray, targetStart, sourceStart, sourceEnd) {
- if (sourceStart != null || sourceEnd != null) {
- if (sourceArray.slice) {
- sourceArray = sourceArray.slice(sourceStart, sourceEnd);
- } else {
- sourceArray = Array.prototype.slice.call(sourceArray, sourceStart, sourceEnd);
- }
- }
- targetArray.set(sourceArray, targetStart);
- }
- var convertUtf8 = (function() {
- function toBytes(text) {
- var result = [], i = 0;
- text = encodeURI(text);
- while (i < text.length) {
- var c = text.charCodeAt(i++);
- // if it is a % sign, encode the following 2 bytes as a hex value
- if (c === 37) {
- result.push(parseInt(text.substr(i, 2), 16));
- i += 2;
- // otherwise, just the actual byte
- } else {
- result.push(c);
- }
- }
- return coerceArray(result);
- }
- function fromBytes(bytes) {
- var result = [], i = 0;
- while (i < bytes.length) {
- var c = bytes[i];
- if (c < 128) {
- result.push(String.fromCharCode(c));
- i++;
- } else if (c > 191 && c < 224) {
- result.push(String.fromCharCode(((c & 0x1f) << 6) | (bytes[i + 1] & 0x3f)));
- i += 2;
- } else {
- result.push(String.fromCharCode(((c & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f)));
- i += 3;
- }
- }
- return result.join('');
- }
- return {
- toBytes: toBytes,
- fromBytes: fromBytes,
- }
- })();
- var convertHex = (function() {
- function toBytes(text) {
- var result = [];
- for (var i = 0; i < text.length; i += 2) {
- result.push(parseInt(text.substr(i, 2), 16));
- }
- return result;
- }
- // http://ixti.net/development/javascript/2011/11/11/base64-encodedecode-of-utf8-in-browser-with-js.html
- var Hex = '0123456789abcdef';
- function fromBytes(bytes) {
- var result = [];
- for (var i = 0; i < bytes.length; i++) {
- var v = bytes[i];
- result.push(Hex[(v & 0xf0) >> 4] + Hex[v & 0x0f]);
- }
- return result.join('');
- }
- return {
- toBytes: toBytes,
- fromBytes: fromBytes,
- }
- })();
- // Number of rounds by keysize
- var numberOfRounds = {16: 10, 24: 12, 32: 14};
- // Round constant words
- var 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];
- // S-box and Inverse S-box (S is for Substitution)
- var 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];
- var 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];
- // Transformations for encryption
- var 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];
- var 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];
- var 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];
- var 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];
- // Transformations for decryption
- var 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];
- var 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];
- var 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];
- var 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];
- // Transformations for decryption key expansion
- var 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];
- var 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];
- var 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];
- var 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];
- function convertToInt32(bytes) {
- var result = [];
- for (var i = 0; i < bytes.length; i += 4) {
- result.push(
- (bytes[i ] << 24) |
- (bytes[i + 1] << 16) |
- (bytes[i + 2] << 8) |
- bytes[i + 3]
- );
- }
- return result;
- }
- var AES = function(key) {
- if (!(this instanceof AES)) {
- throw Error('AES must be instanitated with `new`');
- }
- Object.defineProperty(this, 'key', {
- value: coerceArray(key, true)
- });
- this._prepare();
- };
- AES.prototype._prepare = function() {
- var rounds = numberOfRounds[this.key.length];
- if (rounds == null) {
- throw new Error('invalid key size (must be 16, 24 or 32 bytes)');
- }
- // encryption round keys
- this._Ke = [];
- // decryption round keys
- this._Kd = [];
- for (var i = 0; i <= rounds; i++) {
- this._Ke.push([0, 0, 0, 0]);
- this._Kd.push([0, 0, 0, 0]);
- }
- var roundKeyCount = (rounds + 1) * 4;
- var KC = this.key.length / 4;
- // convert the key into ints
- var tk = convertToInt32(this.key);
- // copy values into round key arrays
- var index;
- for (var i = 0; i < KC; i++) {
- index = i >> 2;
- this._Ke[index][i % 4] = tk[i];
- this._Kd[rounds - index][i % 4] = tk[i];
- }
- // key expansion (fips-197 section 5.2)
- var rconpointer = 0;
- var t = KC, tt;
- while (t < roundKeyCount) {
- tt = tk[KC - 1];
- tk[0] ^= ((S[(tt >> 16) & 0xFF] << 24) ^
- (S[(tt >> 8) & 0xFF] << 16) ^
- (S[ tt & 0xFF] << 8) ^
- S[(tt >> 24) & 0xFF] ^
- (rcon[rconpointer] << 24));
- rconpointer += 1;
- // key expansion (for non-256 bit)
- if (KC != 8) {
- for (var i = 1; i < KC; i++) {
- tk[i] ^= tk[i - 1];
- }
- // key expansion for 256-bit keys is "slightly different" (fips-197)
- } else {
- for (var i = 1; i < (KC / 2); i++) {
- tk[i] ^= tk[i - 1];
- }
- tt = tk[(KC / 2) - 1];
- tk[KC / 2] ^= (S[ tt & 0xFF] ^
- (S[(tt >> 8) & 0xFF] << 8) ^
- (S[(tt >> 16) & 0xFF] << 16) ^
- (S[(tt >> 24) & 0xFF] << 24));
- for (var i = (KC / 2) + 1; i < KC; i++) {
- tk[i] ^= tk[i - 1];
- }
- }
- // copy values into round key arrays
- var i = 0, r, c;
- while (i < KC && t < roundKeyCount) {
- r = t >> 2;
- c = t % 4;
- this._Ke[r][c] = tk[i];
- this._Kd[rounds - r][c] = tk[i++];
- t++;
- }
- }
- // inverse-cipher-ify the decryption round key (fips-197 section 5.3)
- for (var r = 1; r < rounds; r++) {
- for (var c = 0; c < 4; c++) {
- tt = this._Kd[r][c];
- this._Kd[r][c] = (U1[(tt >> 24) & 0xFF] ^
- U2[(tt >> 16) & 0xFF] ^
- U3[(tt >> 8) & 0xFF] ^
- U4[ tt & 0xFF]);
- }
- }
- };
- AES.prototype.encrypt = function(plaintext) {
- if (plaintext.length != 16) {
- throw new Error('invalid plaintext size (must be 16 bytes)');
- }
- var rounds = this._Ke.length - 1;
- var a = [0, 0, 0, 0];
- // convert plaintext to (ints ^ key)
- var t = convertToInt32(plaintext);
- for (var i = 0; i < 4; i++) {
- t[i] ^= this._Ke[0][i];
- }
- // apply round transforms
- for (var r = 1; r < rounds; r++) {
- for (var i = 0; i < 4; i++) {
- a[i] = (T1[(t[ i ] >> 24) & 0xff] ^
- T2[(t[(i + 1) % 4] >> 16) & 0xff] ^
- T3[(t[(i + 2) % 4] >> 8) & 0xff] ^
- T4[ t[(i + 3) % 4] & 0xff] ^
- this._Ke[r][i]);
- }
- t = a.slice();
- }
- // the last round is special
- var result = createArray(16), tt;
- for (var i = 0; i < 4; i++) {
- tt = this._Ke[rounds][i];
- result[4 * i ] = (S[(t[ i ] >> 24) & 0xff] ^ (tt >> 24)) & 0xff;
- result[4 * i + 1] = (S[(t[(i + 1) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff;
- result[4 * i + 2] = (S[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff;
- result[4 * i + 3] = (S[ t[(i + 3) % 4] & 0xff] ^ tt ) & 0xff;
- }
- return result;
- };
- AES.prototype.decrypt = function(ciphertext) {
- if (ciphertext.length != 16) {
- throw new Error('invalid ciphertext size (must be 16 bytes)');
- }
- var rounds = this._Kd.length - 1;
- var a = [0, 0, 0, 0];
- // convert plaintext to (ints ^ key)
- var t = convertToInt32(ciphertext);
- for (var i = 0; i < 4; i++) {
- t[i] ^= this._Kd[0][i];
- }
- // apply round transforms
- for (var r = 1; r < rounds; r++) {
- for (var i = 0; i < 4; i++) {
- a[i] = (T5[(t[ i ] >> 24) & 0xff] ^
- T6[(t[(i + 3) % 4] >> 16) & 0xff] ^
- T7[(t[(i + 2) % 4] >> 8) & 0xff] ^
- T8[ t[(i + 1) % 4] & 0xff] ^
- this._Kd[r][i]);
- }
- t = a.slice();
- }
- // the last round is special
- var result = createArray(16), tt;
- for (var i = 0; i < 4; i++) {
- tt = this._Kd[rounds][i];
- result[4 * i ] = (Si[(t[ i ] >> 24) & 0xff] ^ (tt >> 24)) & 0xff;
- result[4 * i + 1] = (Si[(t[(i + 3) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff;
- result[4 * i + 2] = (Si[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff;
- result[4 * i + 3] = (Si[ t[(i + 1) % 4] & 0xff] ^ tt ) & 0xff;
- }
- return result;
- };
- /**
- * Mode Of Operation - Electonic Codebook (ECB)
- */
- var ModeOfOperationECB = function(key) {
- if (!(this instanceof ModeOfOperationECB)) {
- throw Error('AES must be instanitated with `new`');
- }
- this.description = "Electronic Code Block";
- this.name = "ecb";
- this._aes = new AES(key);
- };
- ModeOfOperationECB.prototype.encrypt = function(plaintext) {
- plaintext = coerceArray(plaintext);
- if ((plaintext.length % 16) !== 0) {
- throw new Error('invalid plaintext size (must be multiple of 16 bytes)');
- }
- var ciphertext = createArray(plaintext.length);
- var block = createArray(16);
- for (var i = 0; i < plaintext.length; i += 16) {
- copyArray(plaintext, block, 0, i, i + 16);
- block = this._aes.encrypt(block);
- copyArray(block, ciphertext, i);
- }
- return ciphertext;
- };
- ModeOfOperationECB.prototype.decrypt = function(ciphertext) {
- ciphertext = coerceArray(ciphertext);
- if ((ciphertext.length % 16) !== 0) {
- throw new Error('invalid ciphertext size (must be multiple of 16 bytes)');
- }
- var plaintext = createArray(ciphertext.length);
- var block = createArray(16);
- for (var i = 0; i < ciphertext.length; i += 16) {
- copyArray(ciphertext, block, 0, i, i + 16);
- block = this._aes.decrypt(block);
- copyArray(block, plaintext, i);
- }
- return plaintext;
- };
- /**
- * Mode Of Operation - Cipher Block Chaining (CBC)
- */
- var ModeOfOperationCBC = function(key, iv) {
- if (!(this instanceof ModeOfOperationCBC)) {
- throw Error('AES must be instanitated with `new`');
- }
- this.description = "Cipher Block Chaining";
- this.name = "cbc";
- if (!iv) {
- iv = createArray(16);
- } else if (iv.length != 16) {
- throw new Error('invalid initialation vector size (must be 16 bytes)');
- }
- this._lastCipherblock = coerceArray(iv, true);
- this._aes = new AES(key);
- };
- ModeOfOperationCBC.prototype.encrypt = function(plaintext) {
- plaintext = coerceArray(plaintext);
- if ((plaintext.length % 16) !== 0) {
- throw new Error('invalid plaintext size (must be multiple of 16 bytes)');
- }
- var ciphertext = createArray(plaintext.length);
- var block = createArray(16);
- for (var i = 0; i < plaintext.length; i += 16) {
- copyArray(plaintext, block, 0, i, i + 16);
- for (var j = 0; j < 16; j++) {
- block[j] ^= this._lastCipherblock[j];
- }
- this._lastCipherblock = this._aes.encrypt(block);
- copyArray(this._lastCipherblock, ciphertext, i);
- }
- return ciphertext;
- };
- ModeOfOperationCBC.prototype.decrypt = function(ciphertext) {
- ciphertext = coerceArray(ciphertext);
- if ((ciphertext.length % 16) !== 0) {
- throw new Error('invalid ciphertext size (must be multiple of 16 bytes)');
- }
- var plaintext = createArray(ciphertext.length);
- var block = createArray(16);
- for (var i = 0; i < ciphertext.length; i += 16) {
- copyArray(ciphertext, block, 0, i, i + 16);
- block = this._aes.decrypt(block);
- for (var j = 0; j < 16; j++) {
- plaintext[i + j] = block[j] ^ this._lastCipherblock[j];
- }
- copyArray(ciphertext, this._lastCipherblock, 0, i, i + 16);
- }
- return plaintext;
- };
- /**
- * Mode Of Operation - Cipher Feedback (CFB)
- */
- var ModeOfOperationCFB = function(key, iv, segmentSize) {
- if (!(this instanceof ModeOfOperationCFB)) {
- throw Error('AES must be instanitated with `new`');
- }
- this.description = "Cipher Feedback";
- this.name = "cfb";
- if (!iv) {
- iv = createArray(16);
- } else if (iv.length != 16) {
- throw new Error('invalid initialation vector size (must be 16 size)');
- }
- if (!segmentSize) { segmentSize = 1; }
- this.segmentSize = segmentSize;
- this._shiftRegister = coerceArray(iv, true);
- this._aes = new AES(key);
- };
- ModeOfOperationCFB.prototype.encrypt = function(plaintext) {
- if ((plaintext.length % this.segmentSize) != 0) {
- throw new Error('invalid plaintext size (must be segmentSize bytes)');
- }
- var encrypted = coerceArray(plaintext, true);
- var xorSegment;
- for (var i = 0; i < encrypted.length; i += this.segmentSize) {
- xorSegment = this._aes.encrypt(this._shiftRegister);
- for (var j = 0; j < this.segmentSize; j++) {
- encrypted[i + j] ^= xorSegment[j];
- }
- // Shift the register
- copyArray(this._shiftRegister, this._shiftRegister, 0, this.segmentSize);
- copyArray(encrypted, this._shiftRegister, 16 - this.segmentSize, i, i + this.segmentSize);
- }
- return encrypted;
- };
- ModeOfOperationCFB.prototype.decrypt = function(ciphertext) {
- if ((ciphertext.length % this.segmentSize) != 0) {
- throw new Error('invalid ciphertext size (must be segmentSize bytes)');
- }
- var plaintext = coerceArray(ciphertext, true);
- var xorSegment;
- for (var i = 0; i < plaintext.length; i += this.segmentSize) {
- xorSegment = this._aes.encrypt(this._shiftRegister);
- for (var j = 0; j < this.segmentSize; j++) {
- plaintext[i + j] ^= xorSegment[j];
- }
- // Shift the register
- copyArray(this._shiftRegister, this._shiftRegister, 0, this.segmentSize);
- copyArray(ciphertext, this._shiftRegister, 16 - this.segmentSize, i, i + this.segmentSize);
- }
- return plaintext;
- };
- /**
- * Mode Of Operation - Output Feedback (OFB)
- */
- var ModeOfOperationOFB = function(key, iv) {
- if (!(this instanceof ModeOfOperationOFB)) {
- throw Error('AES must be instanitated with `new`');
- }
- this.description = "Output Feedback";
- this.name = "ofb";
- if (!iv) {
- iv = createArray(16);
- } else if (iv.length != 16) {
- throw new Error('invalid initialation vector size (must be 16 bytes)');
- }
- this._lastPrecipher = coerceArray(iv, true);
- this._lastPrecipherIndex = 16;
- this._aes = new AES(key);
- };
- ModeOfOperationOFB.prototype.encrypt = function(plaintext) {
- var encrypted = coerceArray(plaintext, true);
- for (var i = 0; i < encrypted.length; i++) {
- if (this._lastPrecipherIndex === 16) {
- this._lastPrecipher = this._aes.encrypt(this._lastPrecipher);
- this._lastPrecipherIndex = 0;
- }
- encrypted[i] ^= this._lastPrecipher[this._lastPrecipherIndex++];
- }
- return encrypted;
- };
- // Decryption is symetric
- ModeOfOperationOFB.prototype.decrypt = ModeOfOperationOFB.prototype.encrypt;
- /**
- * Counter object for CTR common mode of operation
- */
- var Counter = function(initialValue) {
- if (!(this instanceof Counter)) {
- throw Error('Counter must be instanitated with `new`');
- }
- // We allow 0, but anything false-ish uses the default 1
- if (initialValue !== 0 && !initialValue) { initialValue = 1; }
- if (typeof(initialValue) === 'number') {
- this._counter = createArray(16);
- this.setValue(initialValue);
- } else {
- this.setBytes(initialValue);
- }
- };
- Counter.prototype.setValue = function(value) {
- if (typeof(value) !== 'number' || parseInt(value) != value) {
- throw new Error('invalid counter value (must be an integer)');
- }
- for (var index = 15; index >= 0; --index) {
- this._counter[index] = value % 256;
- value = value >> 8;
- }
- };
- Counter.prototype.setBytes = function(bytes) {
- bytes = coerceArray(bytes, true);
- if (bytes.length != 16) {
- throw new Error('invalid counter bytes size (must be 16 bytes)');
- }
- this._counter = bytes;
- };
- Counter.prototype.increment = function() {
- for (var i = 15; i >= 0; i--) {
- if (this._counter[i] === 255) {
- this._counter[i] = 0;
- } else {
- this._counter[i]++;
- break;
- }
- }
- };
- /**
- * Mode Of Operation - Counter (CTR)
- */
- var ModeOfOperationCTR = function(key, counter) {
- if (!(this instanceof ModeOfOperationCTR)) {
- throw Error('AES must be instanitated with `new`');
- }
- this.description = "Counter";
- this.name = "ctr";
- if (!(counter instanceof Counter)) {
- counter = new Counter(counter);
- }
- this._counter = counter;
- this._remainingCounter = null;
- this._remainingCounterIndex = 16;
- this._aes = new AES(key);
- };
- ModeOfOperationCTR.prototype.encrypt = function(plaintext) {
- var encrypted = coerceArray(plaintext, true);
- for (var i = 0; i < encrypted.length; i++) {
- if (this._remainingCounterIndex === 16) {
- this._remainingCounter = this._aes.encrypt(this._counter._counter);
- this._remainingCounterIndex = 0;
- this._counter.increment();
- }
- encrypted[i] ^= this._remainingCounter[this._remainingCounterIndex++];
- }
- return encrypted;
- };
- // Decryption is symetric
- ModeOfOperationCTR.prototype.decrypt = ModeOfOperationCTR.prototype.encrypt;
- ///////////////////////
- // Padding
- // See:https://tools.ietf.org/html/rfc2315
- function pkcs7pad(data) {
- data = coerceArray(data, true);
- var padder = 16 - (data.length % 16);
- var result = createArray(data.length + padder);
- copyArray(data, result);
- for (var i = data.length; i < result.length; i++) {
- result[i] = padder;
- }
- return result;
- }
- function pkcs7strip(data) {
- data = coerceArray(data, true);
- if (data.length < 16) { throw new Error('PKCS#7 invalid length'); }
- var padder = data[data.length - 1];
- if (padder > 16) { throw new Error('PKCS#7 padding byte out of range'); }
- var length = data.length - padder;
- for (var i = 0; i < padder; i++) {
- if (data[length + i] !== padder) {
- throw new Error('PKCS#7 invalid padding byte');
- }
- }
- var result = createArray(length);
- copyArray(data, result, 0, 0, length);
- return result;
- }
- ///////////////////////
- // Exporting
- // The block cipher
- var aesjs = {
- AES: AES,
- Counter: Counter,
- ModeOfOperation: {
- ecb: ModeOfOperationECB,
- cbc: ModeOfOperationCBC,
- cfb: ModeOfOperationCFB,
- ofb: ModeOfOperationOFB,
- ctr: ModeOfOperationCTR
- },
- utils: {
- hex: convertHex,
- utf8: convertUtf8
- },
- padding: {
- pkcs7: {
- pad: pkcs7pad,
- strip: pkcs7strip
- }
- },
- _arrayTest: {
- coerceArray: coerceArray,
- createArray: createArray,
- copyArray: copyArray,
- }
- };
- // node.js
- if ('object' !== 'undefined') {
- module.exports = aesjs;
- // RequireJS/AMD
- // http://www.requirejs.org/docs/api.html
- // https://github.com/amdjs/amdjs-api/wiki/AMD
- } else if (typeof(undefined) === 'function' && undefined.amd) {
- undefined(aesjs);
- // Web Browsers
- } else {
- // If there was an existing library at "aesjs" make sure it's still available
- if (root.aesjs) {
- aesjs._aesjs = root.aesjs;
- }
- root.aesjs = aesjs;
- }
- })(commonjsGlobal);
- });
- var _version$A = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "json-wallets/5.6.0";
- });
- var _version$B = /*@__PURE__*/getDefaultExportFromCjs(_version$A);
- var utils$1 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.uuidV4 = exports.searchPath = exports.getPassword = exports.zpad = exports.looseArrayify = void 0;
- function looseArrayify(hexString) {
- if (typeof (hexString) === 'string' && hexString.substring(0, 2) !== '0x') {
- hexString = '0x' + hexString;
- }
- return (0, lib$1.arrayify)(hexString);
- }
- exports.looseArrayify = looseArrayify;
- function zpad(value, length) {
- value = String(value);
- while (value.length < length) {
- value = '0' + value;
- }
- return value;
- }
- exports.zpad = zpad;
- function getPassword(password) {
- if (typeof (password) === 'string') {
- return (0, lib$8.toUtf8Bytes)(password, lib$8.UnicodeNormalizationForm.NFKC);
- }
- return (0, lib$1.arrayify)(password);
- }
- exports.getPassword = getPassword;
- function searchPath(object, path) {
- var currentChild = object;
- var comps = path.toLowerCase().split('/');
- for (var i = 0; i < comps.length; i++) {
- // Search for a child object with a case-insensitive matching key
- var matchingChild = null;
- for (var key in currentChild) {
- if (key.toLowerCase() === comps[i]) {
- matchingChild = currentChild[key];
- break;
- }
- }
- // Didn't find one. :'(
- if (matchingChild === null) {
- return null;
- }
- // Now check this child...
- currentChild = matchingChild;
- }
- return currentChild;
- }
- exports.searchPath = searchPath;
- // See: https://www.ietf.org/rfc/rfc4122.txt (Section 4.4)
- function uuidV4(randomBytes) {
- var bytes = (0, lib$1.arrayify)(randomBytes);
- // Section: 4.1.3:
- // - time_hi_and_version[12:16] = 0b0100
- bytes[6] = (bytes[6] & 0x0f) | 0x40;
- // Section 4.4
- // - clock_seq_hi_and_reserved[6] = 0b0
- // - clock_seq_hi_and_reserved[7] = 0b1
- bytes[8] = (bytes[8] & 0x3f) | 0x80;
- var value = (0, lib$1.hexlify)(bytes);
- return [
- value.substring(2, 10),
- value.substring(10, 14),
- value.substring(14, 18),
- value.substring(18, 22),
- value.substring(22, 34),
- ].join("-");
- }
- exports.uuidV4 = uuidV4;
- });
- var utils$2 = /*@__PURE__*/getDefaultExportFromCjs(utils$1);
- var crowdsale = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.decrypt = exports.CrowdsaleAccount = void 0;
- var aes_js_1 = __importDefault(aesJs);
- var logger = new lib.Logger(_version$A.version);
- var CrowdsaleAccount = /** @class */ (function (_super) {
- __extends(CrowdsaleAccount, _super);
- function CrowdsaleAccount() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- CrowdsaleAccount.prototype.isCrowdsaleAccount = function (value) {
- return !!(value && value._isCrowdsaleAccount);
- };
- return CrowdsaleAccount;
- }(lib$3.Description));
- exports.CrowdsaleAccount = CrowdsaleAccount;
- // See: https://github.com/ethereum/pyethsaletool
- function decrypt(json, password) {
- var data = JSON.parse(json);
- password = (0, utils$1.getPassword)(password);
- // Ethereum Address
- var ethaddr = (0, lib$6.getAddress)((0, utils$1.searchPath)(data, "ethaddr"));
- // Encrypted Seed
- var encseed = (0, utils$1.looseArrayify)((0, utils$1.searchPath)(data, "encseed"));
- if (!encseed || (encseed.length % 16) !== 0) {
- logger.throwArgumentError("invalid encseed", "json", json);
- }
- var key = (0, lib$1.arrayify)((0, lib$i.pbkdf2)(password, password, 2000, 32, "sha256")).slice(0, 16);
- var iv = encseed.slice(0, 16);
- var encryptedSeed = encseed.slice(16);
- // Decrypt the seed
- var aesCbc = new aes_js_1.default.ModeOfOperation.cbc(key, iv);
- var seed = aes_js_1.default.padding.pkcs7.strip((0, lib$1.arrayify)(aesCbc.decrypt(encryptedSeed)));
- // This wallet format is weird... Convert the binary encoded hex to a string.
- var seedHex = "";
- for (var i = 0; i < seed.length; i++) {
- seedHex += String.fromCharCode(seed[i]);
- }
- var seedHexBytes = (0, lib$8.toUtf8Bytes)(seedHex);
- var privateKey = (0, lib$4.keccak256)(seedHexBytes);
- return new CrowdsaleAccount({
- _isCrowdsaleAccount: true,
- address: ethaddr,
- privateKey: privateKey
- });
- }
- exports.decrypt = decrypt;
- });
- var crowdsale$1 = /*@__PURE__*/getDefaultExportFromCjs(crowdsale);
- var inspect = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getJsonWalletAddress = exports.isKeystoreWallet = exports.isCrowdsaleWallet = void 0;
- function isCrowdsaleWallet(json) {
- var data = null;
- try {
- data = JSON.parse(json);
- }
- catch (error) {
- return false;
- }
- return (data.encseed && data.ethaddr);
- }
- exports.isCrowdsaleWallet = isCrowdsaleWallet;
- function isKeystoreWallet(json) {
- var data = null;
- try {
- data = JSON.parse(json);
- }
- catch (error) {
- return false;
- }
- if (!data.version || parseInt(data.version) !== data.version || parseInt(data.version) !== 3) {
- return false;
- }
- // @TODO: Put more checks to make sure it has kdf, iv and all that good stuff
- return true;
- }
- exports.isKeystoreWallet = isKeystoreWallet;
- //export function isJsonWallet(json: string): boolean {
- // return (isSecretStorageWallet(json) || isCrowdsaleWallet(json));
- //}
- function getJsonWalletAddress(json) {
- if (isCrowdsaleWallet(json)) {
- try {
- return (0, lib$6.getAddress)(JSON.parse(json).ethaddr);
- }
- catch (error) {
- return null;
- }
- }
- if (isKeystoreWallet(json)) {
- try {
- return (0, lib$6.getAddress)(JSON.parse(json).address);
- }
- catch (error) {
- return null;
- }
- }
- return null;
- }
- exports.getJsonWalletAddress = getJsonWalletAddress;
- });
- var inspect$1 = /*@__PURE__*/getDefaultExportFromCjs(inspect);
- var scrypt = createCommonjsModule(function (module, exports) {
- "use strict";
- (function(root) {
- const MAX_VALUE = 0x7fffffff;
- // The SHA256 and PBKDF2 implementation are from scrypt-async-js:
- // See: https://github.com/dchest/scrypt-async-js
- function SHA256(m) {
- const K = new Uint32Array([
- 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b,
- 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,
- 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7,
- 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
- 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152,
- 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
- 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
- 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
- 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,
- 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,
- 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,
- 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
- 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
- ]);
- let h0 = 0x6a09e667, h1 = 0xbb67ae85, h2 = 0x3c6ef372, h3 = 0xa54ff53a;
- let h4 = 0x510e527f, h5 = 0x9b05688c, h6 = 0x1f83d9ab, h7 = 0x5be0cd19;
- const w = new Uint32Array(64);
- function blocks(p) {
- let off = 0, len = p.length;
- while (len >= 64) {
- let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7, u, i, j, t1, t2;
- for (i = 0; i < 16; i++) {
- j = off + i*4;
- w[i] = ((p[j] & 0xff)<<24) | ((p[j+1] & 0xff)<<16) |
- ((p[j+2] & 0xff)<<8) | (p[j+3] & 0xff);
- }
- for (i = 16; i < 64; i++) {
- u = w[i-2];
- t1 = ((u>>>17) | (u<<(32-17))) ^ ((u>>>19) | (u<<(32-19))) ^ (u>>>10);
- u = w[i-15];
- t2 = ((u>>>7) | (u<<(32-7))) ^ ((u>>>18) | (u<<(32-18))) ^ (u>>>3);
- w[i] = (((t1 + w[i-7]) | 0) + ((t2 + w[i-16]) | 0)) | 0;
- }
- for (i = 0; i < 64; i++) {
- t1 = ((((((e>>>6) | (e<<(32-6))) ^ ((e>>>11) | (e<<(32-11))) ^
- ((e>>>25) | (e<<(32-25)))) + ((e & f) ^ (~e & g))) | 0) +
- ((h + ((K[i] + w[i]) | 0)) | 0)) | 0;
- t2 = ((((a>>>2) | (a<<(32-2))) ^ ((a>>>13) | (a<<(32-13))) ^
- ((a>>>22) | (a<<(32-22)))) + ((a & b) ^ (a & c) ^ (b & c))) | 0;
- h = g;
- g = f;
- f = e;
- e = (d + t1) | 0;
- d = c;
- c = b;
- b = a;
- a = (t1 + t2) | 0;
- }
- h0 = (h0 + a) | 0;
- h1 = (h1 + b) | 0;
- h2 = (h2 + c) | 0;
- h3 = (h3 + d) | 0;
- h4 = (h4 + e) | 0;
- h5 = (h5 + f) | 0;
- h6 = (h6 + g) | 0;
- h7 = (h7 + h) | 0;
- off += 64;
- len -= 64;
- }
- }
- blocks(m);
- let i, bytesLeft = m.length % 64,
- bitLenHi = (m.length / 0x20000000) | 0,
- bitLenLo = m.length << 3,
- numZeros = (bytesLeft < 56) ? 56 : 120,
- p = m.slice(m.length - bytesLeft, m.length);
- p.push(0x80);
- for (i = bytesLeft + 1; i < numZeros; i++) { p.push(0); }
- p.push((bitLenHi >>> 24) & 0xff);
- p.push((bitLenHi >>> 16) & 0xff);
- p.push((bitLenHi >>> 8) & 0xff);
- p.push((bitLenHi >>> 0) & 0xff);
- p.push((bitLenLo >>> 24) & 0xff);
- p.push((bitLenLo >>> 16) & 0xff);
- p.push((bitLenLo >>> 8) & 0xff);
- p.push((bitLenLo >>> 0) & 0xff);
- blocks(p);
- return [
- (h0 >>> 24) & 0xff, (h0 >>> 16) & 0xff, (h0 >>> 8) & 0xff, (h0 >>> 0) & 0xff,
- (h1 >>> 24) & 0xff, (h1 >>> 16) & 0xff, (h1 >>> 8) & 0xff, (h1 >>> 0) & 0xff,
- (h2 >>> 24) & 0xff, (h2 >>> 16) & 0xff, (h2 >>> 8) & 0xff, (h2 >>> 0) & 0xff,
- (h3 >>> 24) & 0xff, (h3 >>> 16) & 0xff, (h3 >>> 8) & 0xff, (h3 >>> 0) & 0xff,
- (h4 >>> 24) & 0xff, (h4 >>> 16) & 0xff, (h4 >>> 8) & 0xff, (h4 >>> 0) & 0xff,
- (h5 >>> 24) & 0xff, (h5 >>> 16) & 0xff, (h5 >>> 8) & 0xff, (h5 >>> 0) & 0xff,
- (h6 >>> 24) & 0xff, (h6 >>> 16) & 0xff, (h6 >>> 8) & 0xff, (h6 >>> 0) & 0xff,
- (h7 >>> 24) & 0xff, (h7 >>> 16) & 0xff, (h7 >>> 8) & 0xff, (h7 >>> 0) & 0xff
- ];
- }
- function PBKDF2_HMAC_SHA256_OneIter(password, salt, dkLen) {
- // compress password if it's longer than hash block length
- password = (password.length <= 64) ? password : SHA256(password);
- const innerLen = 64 + salt.length + 4;
- const inner = new Array(innerLen);
- const outerKey = new Array(64);
- let i;
- let dk = [];
- // inner = (password ^ ipad) || salt || counter
- for (i = 0; i < 64; i++) { inner[i] = 0x36; }
- for (i = 0; i < password.length; i++) { inner[i] ^= password[i]; }
- for (i = 0; i < salt.length; i++) { inner[64 + i] = salt[i]; }
- for (i = innerLen - 4; i < innerLen; i++) { inner[i] = 0; }
- // outerKey = password ^ opad
- for (i = 0; i < 64; i++) outerKey[i] = 0x5c;
- for (i = 0; i < password.length; i++) outerKey[i] ^= password[i];
- // increments counter inside inner
- function incrementCounter() {
- for (let i = innerLen - 1; i >= innerLen - 4; i--) {
- inner[i]++;
- if (inner[i] <= 0xff) return;
- inner[i] = 0;
- }
- }
- // output blocks = SHA256(outerKey || SHA256(inner)) ...
- while (dkLen >= 32) {
- incrementCounter();
- dk = dk.concat(SHA256(outerKey.concat(SHA256(inner))));
- dkLen -= 32;
- }
- if (dkLen > 0) {
- incrementCounter();
- dk = dk.concat(SHA256(outerKey.concat(SHA256(inner))).slice(0, dkLen));
- }
- return dk;
- }
- // The following is an adaptation of scryptsy
- // See: https://www.npmjs.com/package/scryptsy
- function blockmix_salsa8(BY, Yi, r, x, _X) {
- let i;
- arraycopy(BY, (2 * r - 1) * 16, _X, 0, 16);
- for (i = 0; i < 2 * r; i++) {
- blockxor(BY, i * 16, _X, 16);
- salsa20_8(_X, x);
- arraycopy(_X, 0, BY, Yi + (i * 16), 16);
- }
- for (i = 0; i < r; i++) {
- arraycopy(BY, Yi + (i * 2) * 16, BY, (i * 16), 16);
- }
- for (i = 0; i < r; i++) {
- arraycopy(BY, Yi + (i * 2 + 1) * 16, BY, (i + r) * 16, 16);
- }
- }
- function R(a, b) {
- return (a << b) | (a >>> (32 - b));
- }
- function salsa20_8(B, x) {
- arraycopy(B, 0, x, 0, 16);
- for (let i = 8; i > 0; i -= 2) {
- x[ 4] ^= R(x[ 0] + x[12], 7);
- x[ 8] ^= R(x[ 4] + x[ 0], 9);
- x[12] ^= R(x[ 8] + x[ 4], 13);
- x[ 0] ^= R(x[12] + x[ 8], 18);
- x[ 9] ^= R(x[ 5] + x[ 1], 7);
- x[13] ^= R(x[ 9] + x[ 5], 9);
- x[ 1] ^= R(x[13] + x[ 9], 13);
- x[ 5] ^= R(x[ 1] + x[13], 18);
- x[14] ^= R(x[10] + x[ 6], 7);
- x[ 2] ^= R(x[14] + x[10], 9);
- x[ 6] ^= R(x[ 2] + x[14], 13);
- x[10] ^= R(x[ 6] + x[ 2], 18);
- x[ 3] ^= R(x[15] + x[11], 7);
- x[ 7] ^= R(x[ 3] + x[15], 9);
- x[11] ^= R(x[ 7] + x[ 3], 13);
- x[15] ^= R(x[11] + x[ 7], 18);
- x[ 1] ^= R(x[ 0] + x[ 3], 7);
- x[ 2] ^= R(x[ 1] + x[ 0], 9);
- x[ 3] ^= R(x[ 2] + x[ 1], 13);
- x[ 0] ^= R(x[ 3] + x[ 2], 18);
- x[ 6] ^= R(x[ 5] + x[ 4], 7);
- x[ 7] ^= R(x[ 6] + x[ 5], 9);
- x[ 4] ^= R(x[ 7] + x[ 6], 13);
- x[ 5] ^= R(x[ 4] + x[ 7], 18);
- x[11] ^= R(x[10] + x[ 9], 7);
- x[ 8] ^= R(x[11] + x[10], 9);
- x[ 9] ^= R(x[ 8] + x[11], 13);
- x[10] ^= R(x[ 9] + x[ 8], 18);
- x[12] ^= R(x[15] + x[14], 7);
- x[13] ^= R(x[12] + x[15], 9);
- x[14] ^= R(x[13] + x[12], 13);
- x[15] ^= R(x[14] + x[13], 18);
- }
- for (let i = 0; i < 16; ++i) {
- B[i] += x[i];
- }
- }
- // naive approach... going back to loop unrolling may yield additional performance
- function blockxor(S, Si, D, len) {
- for (let i = 0; i < len; i++) {
- D[i] ^= S[Si + i];
- }
- }
- function arraycopy(src, srcPos, dest, destPos, length) {
- while (length--) {
- dest[destPos++] = src[srcPos++];
- }
- }
- function checkBufferish(o) {
- if (!o || typeof(o.length) !== 'number') { return false; }
- for (let i = 0; i < o.length; i++) {
- const v = o[i];
- if (typeof(v) !== 'number' || v % 1 || v < 0 || v >= 256) {
- return false;
- }
- }
- return true;
- }
- function ensureInteger(value, name) {
- if (typeof(value) !== "number" || (value % 1)) { throw new Error('invalid ' + name); }
- return value;
- }
- // N = Cpu cost, r = Memory cost, p = parallelization cost
- // callback(error, progress, key)
- function _scrypt(password, salt, N, r, p, dkLen, callback) {
- N = ensureInteger(N, 'N');
- r = ensureInteger(r, 'r');
- p = ensureInteger(p, 'p');
- dkLen = ensureInteger(dkLen, 'dkLen');
- if (N === 0 || (N & (N - 1)) !== 0) { throw new Error('N must be power of 2'); }
- if (N > MAX_VALUE / 128 / r) { throw new Error('N too large'); }
- if (r > MAX_VALUE / 128 / p) { throw new Error('r too large'); }
- if (!checkBufferish(password)) {
- throw new Error('password must be an array or buffer');
- }
- password = Array.prototype.slice.call(password);
- if (!checkBufferish(salt)) {
- throw new Error('salt must be an array or buffer');
- }
- salt = Array.prototype.slice.call(salt);
- let b = PBKDF2_HMAC_SHA256_OneIter(password, salt, p * 128 * r);
- const B = new Uint32Array(p * 32 * r);
- for (let i = 0; i < B.length; i++) {
- const j = i * 4;
- B[i] = ((b[j + 3] & 0xff) << 24) |
- ((b[j + 2] & 0xff) << 16) |
- ((b[j + 1] & 0xff) << 8) |
- ((b[j + 0] & 0xff) << 0);
- }
- const XY = new Uint32Array(64 * r);
- const V = new Uint32Array(32 * r * N);
- const Yi = 32 * r;
- // scratch space
- const x = new Uint32Array(16); // salsa20_8
- const _X = new Uint32Array(16); // blockmix_salsa8
- const totalOps = p * N * 2;
- let currentOp = 0;
- let lastPercent10 = null;
- // Set this to true to abandon the scrypt on the next step
- let stop = false;
- // State information
- let state = 0;
- let i0 = 0, i1;
- let Bi;
- // How many blockmix_salsa8 can we do per step?
- const limit = callback ? parseInt(1000 / r): 0xffffffff;
- // Trick from scrypt-async; if there is a setImmediate shim in place, use it
- const nextTick = (typeof(setImmediate) !== 'undefined') ? setImmediate : setTimeout;
- // This is really all I changed; making scryptsy a state machine so we occasionally
- // stop and give other evnts on the evnt loop a chance to run. ~RicMoo
- const incrementalSMix = function() {
- if (stop) {
- return callback(new Error('cancelled'), currentOp / totalOps);
- }
- let steps;
- switch (state) {
- case 0:
- // for (var i = 0; i < p; i++)...
- Bi = i0 * 32 * r;
- arraycopy(B, Bi, XY, 0, Yi); // ROMix - 1
- state = 1; // Move to ROMix 2
- i1 = 0;
- // Fall through
- case 1:
- // Run up to 1000 steps of the first inner smix loop
- steps = N - i1;
- if (steps > limit) { steps = limit; }
- for (let i = 0; i < steps; i++) { // ROMix - 2
- arraycopy(XY, 0, V, (i1 + i) * Yi, Yi); // ROMix - 3
- blockmix_salsa8(XY, Yi, r, x, _X); // ROMix - 4
- }
- // for (var i = 0; i < N; i++)
- i1 += steps;
- currentOp += steps;
- if (callback) {
- // Call the callback with the progress (optionally stopping us)
- const percent10 = parseInt(1000 * currentOp / totalOps);
- if (percent10 !== lastPercent10) {
- stop = callback(null, currentOp / totalOps);
- if (stop) { break; }
- lastPercent10 = percent10;
- }
- }
- if (i1 < N) { break; }
- i1 = 0; // Move to ROMix 6
- state = 2;
- // Fall through
- case 2:
- // Run up to 1000 steps of the second inner smix loop
- steps = N - i1;
- if (steps > limit) { steps = limit; }
- for (let i = 0; i < steps; i++) { // ROMix - 6
- const offset = (2 * r - 1) * 16; // ROMix - 7
- const j = XY[offset] & (N - 1);
- blockxor(V, j * Yi, XY, Yi); // ROMix - 8 (inner)
- blockmix_salsa8(XY, Yi, r, x, _X); // ROMix - 9 (outer)
- }
- // for (var i = 0; i < N; i++)...
- i1 += steps;
- currentOp += steps;
- // Call the callback with the progress (optionally stopping us)
- if (callback) {
- const percent10 = parseInt(1000 * currentOp / totalOps);
- if (percent10 !== lastPercent10) {
- stop = callback(null, currentOp / totalOps);
- if (stop) { break; }
- lastPercent10 = percent10;
- }
- }
- if (i1 < N) { break; }
- arraycopy(XY, 0, B, Bi, Yi); // ROMix - 10
- // for (var i = 0; i < p; i++)...
- i0++;
- if (i0 < p) {
- state = 0;
- break;
- }
- b = [];
- for (let i = 0; i < B.length; i++) {
- b.push((B[i] >> 0) & 0xff);
- b.push((B[i] >> 8) & 0xff);
- b.push((B[i] >> 16) & 0xff);
- b.push((B[i] >> 24) & 0xff);
- }
- const derivedKey = PBKDF2_HMAC_SHA256_OneIter(password, b, dkLen);
- // Send the result to the callback
- if (callback) { callback(null, 1.0, derivedKey); }
- // Done; don't break (which would reschedule)
- return derivedKey;
- }
- // Schedule the next steps
- if (callback) { nextTick(incrementalSMix); }
- };
- // Run the smix state machine until completion
- if (!callback) {
- while (true) {
- const derivedKey = incrementalSMix();
- if (derivedKey != undefined) { return derivedKey; }
- }
- }
- // Bootstrap the async incremental smix
- incrementalSMix();
- }
- const lib = {
- scrypt: function(password, salt, N, r, p, dkLen, progressCallback) {
- return new Promise(function(resolve, reject) {
- let lastProgress = 0;
- if (progressCallback) { progressCallback(0); }
- _scrypt(password, salt, N, r, p, dkLen, function(error, progress, key) {
- if (error) {
- reject(error);
- } else if (key) {
- if (progressCallback && lastProgress !== 1) {
- progressCallback(1);
- }
- resolve(new Uint8Array(key));
- } else if (progressCallback && progress !== lastProgress) {
- lastProgress = progress;
- return progressCallback(progress);
- }
- });
- });
- },
- syncScrypt: function(password, salt, N, r, p, dkLen) {
- return new Uint8Array(_scrypt(password, salt, N, r, p, dkLen));
- }
- };
- // node.js
- if ('object' !== 'undefined') {
- module.exports = lib;
- // RequireJS/AMD
- // http://www.requirejs.org/docs/api.html
- // https://github.com/amdjs/amdjs-api/wiki/AMD
- } else if (typeof(undefined) === 'function' && undefined.amd) {
- undefined(lib);
- // Web Browsers
- } else if (root) {
- // If there was an existing library "scrypt", make sure it is still available
- if (root.scrypt) {
- root._scrypt = root.scrypt;
- }
- root.scrypt = lib;
- }
- })(commonjsGlobal);
- });
- var keystore = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- };
- var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.encrypt = exports.decrypt = exports.decryptSync = exports.KeystoreAccount = void 0;
- var aes_js_1 = __importDefault(aesJs);
- var scrypt_js_1 = __importDefault(scrypt);
- var logger = new lib.Logger(_version$A.version);
- // Exported Types
- function hasMnemonic(value) {
- return (value != null && value.mnemonic && value.mnemonic.phrase);
- }
- var KeystoreAccount = /** @class */ (function (_super) {
- __extends(KeystoreAccount, _super);
- function KeystoreAccount() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- KeystoreAccount.prototype.isKeystoreAccount = function (value) {
- return !!(value && value._isKeystoreAccount);
- };
- return KeystoreAccount;
- }(lib$3.Description));
- exports.KeystoreAccount = KeystoreAccount;
- function _decrypt(data, key, ciphertext) {
- var cipher = (0, utils$1.searchPath)(data, "crypto/cipher");
- if (cipher === "aes-128-ctr") {
- var iv = (0, utils$1.looseArrayify)((0, utils$1.searchPath)(data, "crypto/cipherparams/iv"));
- var counter = new aes_js_1.default.Counter(iv);
- var aesCtr = new aes_js_1.default.ModeOfOperation.ctr(key, counter);
- return (0, lib$1.arrayify)(aesCtr.decrypt(ciphertext));
- }
- return null;
- }
- function _getAccount(data, key) {
- var ciphertext = (0, utils$1.looseArrayify)((0, utils$1.searchPath)(data, "crypto/ciphertext"));
- var computedMAC = (0, lib$1.hexlify)((0, lib$4.keccak256)((0, lib$1.concat)([key.slice(16, 32), ciphertext]))).substring(2);
- if (computedMAC !== (0, utils$1.searchPath)(data, "crypto/mac").toLowerCase()) {
- throw new Error("invalid password");
- }
- var privateKey = _decrypt(data, key.slice(0, 16), ciphertext);
- if (!privateKey) {
- logger.throwError("unsupported cipher", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "decrypt"
- });
- }
- var mnemonicKey = key.slice(32, 64);
- var address = (0, lib$e.computeAddress)(privateKey);
- if (data.address) {
- var check = data.address.toLowerCase();
- if (check.substring(0, 2) !== "0x") {
- check = "0x" + check;
- }
- if ((0, lib$6.getAddress)(check) !== address) {
- throw new Error("address mismatch");
- }
- }
- var account = {
- _isKeystoreAccount: true,
- address: address,
- privateKey: (0, lib$1.hexlify)(privateKey)
- };
- // Version 0.1 x-ethers metadata must contain an encrypted mnemonic phrase
- if ((0, utils$1.searchPath)(data, "x-ethers/version") === "0.1") {
- var mnemonicCiphertext = (0, utils$1.looseArrayify)((0, utils$1.searchPath)(data, "x-ethers/mnemonicCiphertext"));
- var mnemonicIv = (0, utils$1.looseArrayify)((0, utils$1.searchPath)(data, "x-ethers/mnemonicCounter"));
- var mnemonicCounter = new aes_js_1.default.Counter(mnemonicIv);
- var mnemonicAesCtr = new aes_js_1.default.ModeOfOperation.ctr(mnemonicKey, mnemonicCounter);
- var path = (0, utils$1.searchPath)(data, "x-ethers/path") || lib$k.defaultPath;
- var locale = (0, utils$1.searchPath)(data, "x-ethers/locale") || "en";
- var entropy = (0, lib$1.arrayify)(mnemonicAesCtr.decrypt(mnemonicCiphertext));
- try {
- var mnemonic = (0, lib$k.entropyToMnemonic)(entropy, locale);
- var node = lib$k.HDNode.fromMnemonic(mnemonic, null, locale).derivePath(path);
- if (node.privateKey != account.privateKey) {
- throw new Error("mnemonic mismatch");
- }
- account.mnemonic = node.mnemonic;
- }
- catch (error) {
- // If we don't have the locale wordlist installed to
- // read this mnemonic, just bail and don't set the
- // mnemonic
- if (error.code !== lib.Logger.errors.INVALID_ARGUMENT || error.argument !== "wordlist") {
- throw error;
- }
- }
- }
- return new KeystoreAccount(account);
- }
- function pbkdf2Sync(passwordBytes, salt, count, dkLen, prfFunc) {
- return (0, lib$1.arrayify)((0, lib$i.pbkdf2)(passwordBytes, salt, count, dkLen, prfFunc));
- }
- function pbkdf2(passwordBytes, salt, count, dkLen, prfFunc) {
- return Promise.resolve(pbkdf2Sync(passwordBytes, salt, count, dkLen, prfFunc));
- }
- function _computeKdfKey(data, password, pbkdf2Func, scryptFunc, progressCallback) {
- var passwordBytes = (0, utils$1.getPassword)(password);
- var kdf = (0, utils$1.searchPath)(data, "crypto/kdf");
- if (kdf && typeof (kdf) === "string") {
- var throwError = function (name, value) {
- return logger.throwArgumentError("invalid key-derivation function parameters", name, value);
- };
- if (kdf.toLowerCase() === "scrypt") {
- var salt = (0, utils$1.looseArrayify)((0, utils$1.searchPath)(data, "crypto/kdfparams/salt"));
- var N = parseInt((0, utils$1.searchPath)(data, "crypto/kdfparams/n"));
- var r = parseInt((0, utils$1.searchPath)(data, "crypto/kdfparams/r"));
- var p = parseInt((0, utils$1.searchPath)(data, "crypto/kdfparams/p"));
- // Check for all required parameters
- if (!N || !r || !p) {
- throwError("kdf", kdf);
- }
- // Make sure N is a power of 2
- if ((N & (N - 1)) !== 0) {
- throwError("N", N);
- }
- var dkLen = parseInt((0, utils$1.searchPath)(data, "crypto/kdfparams/dklen"));
- if (dkLen !== 32) {
- throwError("dklen", dkLen);
- }
- return scryptFunc(passwordBytes, salt, N, r, p, 64, progressCallback);
- }
- else if (kdf.toLowerCase() === "pbkdf2") {
- var salt = (0, utils$1.looseArrayify)((0, utils$1.searchPath)(data, "crypto/kdfparams/salt"));
- var prfFunc = null;
- var prf = (0, utils$1.searchPath)(data, "crypto/kdfparams/prf");
- if (prf === "hmac-sha256") {
- prfFunc = "sha256";
- }
- else if (prf === "hmac-sha512") {
- prfFunc = "sha512";
- }
- else {
- throwError("prf", prf);
- }
- var count = parseInt((0, utils$1.searchPath)(data, "crypto/kdfparams/c"));
- var dkLen = parseInt((0, utils$1.searchPath)(data, "crypto/kdfparams/dklen"));
- if (dkLen !== 32) {
- throwError("dklen", dkLen);
- }
- return pbkdf2Func(passwordBytes, salt, count, dkLen, prfFunc);
- }
- }
- return logger.throwArgumentError("unsupported key-derivation function", "kdf", kdf);
- }
- function decryptSync(json, password) {
- var data = JSON.parse(json);
- var key = _computeKdfKey(data, password, pbkdf2Sync, scrypt_js_1.default.syncScrypt);
- return _getAccount(data, key);
- }
- exports.decryptSync = decryptSync;
- function decrypt(json, password, progressCallback) {
- return __awaiter(this, void 0, void 0, function () {
- var data, key;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- data = JSON.parse(json);
- return [4 /*yield*/, _computeKdfKey(data, password, pbkdf2, scrypt_js_1.default.scrypt, progressCallback)];
- case 1:
- key = _a.sent();
- return [2 /*return*/, _getAccount(data, key)];
- }
- });
- });
- }
- exports.decrypt = decrypt;
- function encrypt(account, password, options, progressCallback) {
- try {
- // Check the address matches the private key
- if ((0, lib$6.getAddress)(account.address) !== (0, lib$e.computeAddress)(account.privateKey)) {
- throw new Error("address/privateKey mismatch");
- }
- // Check the mnemonic (if any) matches the private key
- if (hasMnemonic(account)) {
- var mnemonic = account.mnemonic;
- var node = lib$k.HDNode.fromMnemonic(mnemonic.phrase, null, mnemonic.locale).derivePath(mnemonic.path || lib$k.defaultPath);
- if (node.privateKey != account.privateKey) {
- throw new Error("mnemonic mismatch");
- }
- }
- }
- catch (e) {
- return Promise.reject(e);
- }
- // The options are optional, so adjust the call as needed
- if (typeof (options) === "function" && !progressCallback) {
- progressCallback = options;
- options = {};
- }
- if (!options) {
- options = {};
- }
- var privateKey = (0, lib$1.arrayify)(account.privateKey);
- var passwordBytes = (0, utils$1.getPassword)(password);
- var entropy = null;
- var path = null;
- var locale = null;
- if (hasMnemonic(account)) {
- var srcMnemonic = account.mnemonic;
- entropy = (0, lib$1.arrayify)((0, lib$k.mnemonicToEntropy)(srcMnemonic.phrase, srcMnemonic.locale || "en"));
- path = srcMnemonic.path || lib$k.defaultPath;
- locale = srcMnemonic.locale || "en";
- }
- var client = options.client;
- if (!client) {
- client = "ethers.js";
- }
- // Check/generate the salt
- var salt = null;
- if (options.salt) {
- salt = (0, lib$1.arrayify)(options.salt);
- }
- else {
- salt = (0, lib$l.randomBytes)(32);
- ;
- }
- // Override initialization vector
- var iv = null;
- if (options.iv) {
- iv = (0, lib$1.arrayify)(options.iv);
- if (iv.length !== 16) {
- throw new Error("invalid iv");
- }
- }
- else {
- iv = (0, lib$l.randomBytes)(16);
- }
- // Override the uuid
- var uuidRandom = null;
- if (options.uuid) {
- uuidRandom = (0, lib$1.arrayify)(options.uuid);
- if (uuidRandom.length !== 16) {
- throw new Error("invalid uuid");
- }
- }
- else {
- uuidRandom = (0, lib$l.randomBytes)(16);
- }
- // Override the scrypt password-based key derivation function parameters
- var N = (1 << 17), r = 8, p = 1;
- if (options.scrypt) {
- if (options.scrypt.N) {
- N = options.scrypt.N;
- }
- if (options.scrypt.r) {
- r = options.scrypt.r;
- }
- if (options.scrypt.p) {
- p = options.scrypt.p;
- }
- }
- // We take 64 bytes:
- // - 32 bytes As normal for the Web3 secret storage (derivedKey, macPrefix)
- // - 32 bytes AES key to encrypt mnemonic with (required here to be Ethers Wallet)
- return scrypt_js_1.default.scrypt(passwordBytes, salt, N, r, p, 64, progressCallback).then(function (key) {
- key = (0, lib$1.arrayify)(key);
- // This will be used to encrypt the wallet (as per Web3 secret storage)
- var derivedKey = key.slice(0, 16);
- var macPrefix = key.slice(16, 32);
- // This will be used to encrypt the mnemonic phrase (if any)
- var mnemonicKey = key.slice(32, 64);
- // Encrypt the private key
- var counter = new aes_js_1.default.Counter(iv);
- var aesCtr = new aes_js_1.default.ModeOfOperation.ctr(derivedKey, counter);
- var ciphertext = (0, lib$1.arrayify)(aesCtr.encrypt(privateKey));
- // Compute the message authentication code, used to check the password
- var mac = (0, lib$4.keccak256)((0, lib$1.concat)([macPrefix, ciphertext]));
- // See: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition
- var data = {
- address: account.address.substring(2).toLowerCase(),
- id: (0, utils$1.uuidV4)(uuidRandom),
- version: 3,
- Crypto: {
- cipher: "aes-128-ctr",
- cipherparams: {
- iv: (0, lib$1.hexlify)(iv).substring(2),
- },
- ciphertext: (0, lib$1.hexlify)(ciphertext).substring(2),
- kdf: "scrypt",
- kdfparams: {
- salt: (0, lib$1.hexlify)(salt).substring(2),
- n: N,
- dklen: 32,
- p: p,
- r: r
- },
- mac: mac.substring(2)
- }
- };
- // If we have a mnemonic, encrypt it into the JSON wallet
- if (entropy) {
- var mnemonicIv = (0, lib$l.randomBytes)(16);
- var mnemonicCounter = new aes_js_1.default.Counter(mnemonicIv);
- var mnemonicAesCtr = new aes_js_1.default.ModeOfOperation.ctr(mnemonicKey, mnemonicCounter);
- var mnemonicCiphertext = (0, lib$1.arrayify)(mnemonicAesCtr.encrypt(entropy));
- var now = new Date();
- var timestamp = (now.getUTCFullYear() + "-" +
- (0, utils$1.zpad)(now.getUTCMonth() + 1, 2) + "-" +
- (0, utils$1.zpad)(now.getUTCDate(), 2) + "T" +
- (0, utils$1.zpad)(now.getUTCHours(), 2) + "-" +
- (0, utils$1.zpad)(now.getUTCMinutes(), 2) + "-" +
- (0, utils$1.zpad)(now.getUTCSeconds(), 2) + ".0Z");
- data["x-ethers"] = {
- client: client,
- gethFilename: ("UTC--" + timestamp + "--" + data.address),
- mnemonicCounter: (0, lib$1.hexlify)(mnemonicIv).substring(2),
- mnemonicCiphertext: (0, lib$1.hexlify)(mnemonicCiphertext).substring(2),
- path: path,
- locale: locale,
- version: "0.1"
- };
- }
- return JSON.stringify(data);
- });
- }
- exports.encrypt = encrypt;
- });
- var keystore$1 = /*@__PURE__*/getDefaultExportFromCjs(keystore);
- var lib$m = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.decryptJsonWalletSync = exports.decryptJsonWallet = exports.getJsonWalletAddress = exports.isKeystoreWallet = exports.isCrowdsaleWallet = exports.encryptKeystore = exports.decryptKeystoreSync = exports.decryptKeystore = exports.decryptCrowdsale = void 0;
- Object.defineProperty(exports, "decryptCrowdsale", { enumerable: true, get: function () { return crowdsale.decrypt; } });
- Object.defineProperty(exports, "getJsonWalletAddress", { enumerable: true, get: function () { return inspect.getJsonWalletAddress; } });
- Object.defineProperty(exports, "isCrowdsaleWallet", { enumerable: true, get: function () { return inspect.isCrowdsaleWallet; } });
- Object.defineProperty(exports, "isKeystoreWallet", { enumerable: true, get: function () { return inspect.isKeystoreWallet; } });
- Object.defineProperty(exports, "decryptKeystore", { enumerable: true, get: function () { return keystore.decrypt; } });
- Object.defineProperty(exports, "decryptKeystoreSync", { enumerable: true, get: function () { return keystore.decryptSync; } });
- Object.defineProperty(exports, "encryptKeystore", { enumerable: true, get: function () { return keystore.encrypt; } });
- function decryptJsonWallet(json, password, progressCallback) {
- if ((0, inspect.isCrowdsaleWallet)(json)) {
- if (progressCallback) {
- progressCallback(0);
- }
- var account = (0, crowdsale.decrypt)(json, password);
- if (progressCallback) {
- progressCallback(1);
- }
- return Promise.resolve(account);
- }
- if ((0, inspect.isKeystoreWallet)(json)) {
- return (0, keystore.decrypt)(json, password, progressCallback);
- }
- return Promise.reject(new Error("invalid JSON wallet"));
- }
- exports.decryptJsonWallet = decryptJsonWallet;
- function decryptJsonWalletSync(json, password) {
- if ((0, inspect.isCrowdsaleWallet)(json)) {
- return (0, crowdsale.decrypt)(json, password);
- }
- if ((0, inspect.isKeystoreWallet)(json)) {
- return (0, keystore.decryptSync)(json, password);
- }
- throw new Error("invalid JSON wallet");
- }
- exports.decryptJsonWalletSync = decryptJsonWalletSync;
- });
- var index$m = /*@__PURE__*/getDefaultExportFromCjs(lib$m);
- var _version$C = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "wallet/5.6.0";
- });
- var _version$D = /*@__PURE__*/getDefaultExportFromCjs(_version$C);
- var lib$n = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.verifyTypedData = exports.verifyMessage = exports.Wallet = void 0;
- var logger = new lib.Logger(_version$C.version);
- function isAccount(value) {
- return (value != null && (0, lib$1.isHexString)(value.privateKey, 32) && value.address != null);
- }
- function hasMnemonic(value) {
- var mnemonic = value.mnemonic;
- return (mnemonic && mnemonic.phrase);
- }
- var Wallet = /** @class */ (function (_super) {
- __extends(Wallet, _super);
- function Wallet(privateKey, provider) {
- var _newTarget = this.constructor;
- var _this = this;
- logger.checkNew(_newTarget, Wallet);
- _this = _super.call(this) || this;
- if (isAccount(privateKey)) {
- var signingKey_1 = new lib$d.SigningKey(privateKey.privateKey);
- (0, lib$3.defineReadOnly)(_this, "_signingKey", function () { return signingKey_1; });
- (0, lib$3.defineReadOnly)(_this, "address", (0, lib$e.computeAddress)(_this.publicKey));
- if (_this.address !== (0, lib$6.getAddress)(privateKey.address)) {
- logger.throwArgumentError("privateKey/address mismatch", "privateKey", "[REDACTED]");
- }
- if (hasMnemonic(privateKey)) {
- var srcMnemonic_1 = privateKey.mnemonic;
- (0, lib$3.defineReadOnly)(_this, "_mnemonic", function () { return ({
- phrase: srcMnemonic_1.phrase,
- path: srcMnemonic_1.path || lib$k.defaultPath,
- locale: srcMnemonic_1.locale || "en"
- }); });
- var mnemonic = _this.mnemonic;
- var node = lib$k.HDNode.fromMnemonic(mnemonic.phrase, null, mnemonic.locale).derivePath(mnemonic.path);
- if ((0, lib$e.computeAddress)(node.privateKey) !== _this.address) {
- logger.throwArgumentError("mnemonic/address mismatch", "privateKey", "[REDACTED]");
- }
- }
- else {
- (0, lib$3.defineReadOnly)(_this, "_mnemonic", function () { return null; });
- }
- }
- else {
- if (lib$d.SigningKey.isSigningKey(privateKey)) {
- /* istanbul ignore if */
- if (privateKey.curve !== "secp256k1") {
- logger.throwArgumentError("unsupported curve; must be secp256k1", "privateKey", "[REDACTED]");
- }
- (0, lib$3.defineReadOnly)(_this, "_signingKey", function () { return privateKey; });
- }
- else {
- // A lot of common tools do not prefix private keys with a 0x (see: #1166)
- if (typeof (privateKey) === "string") {
- if (privateKey.match(/^[0-9a-f]*$/i) && privateKey.length === 64) {
- privateKey = "0x" + privateKey;
- }
- }
- var signingKey_2 = new lib$d.SigningKey(privateKey);
- (0, lib$3.defineReadOnly)(_this, "_signingKey", function () { return signingKey_2; });
- }
- (0, lib$3.defineReadOnly)(_this, "_mnemonic", function () { return null; });
- (0, lib$3.defineReadOnly)(_this, "address", (0, lib$e.computeAddress)(_this.publicKey));
- }
- /* istanbul ignore if */
- if (provider && !lib$b.Provider.isProvider(provider)) {
- logger.throwArgumentError("invalid provider", "provider", provider);
- }
- (0, lib$3.defineReadOnly)(_this, "provider", provider || null);
- return _this;
- }
- Object.defineProperty(Wallet.prototype, "mnemonic", {
- get: function () { return this._mnemonic(); },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(Wallet.prototype, "privateKey", {
- get: function () { return this._signingKey().privateKey; },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(Wallet.prototype, "publicKey", {
- get: function () { return this._signingKey().publicKey; },
- enumerable: false,
- configurable: true
- });
- Wallet.prototype.getAddress = function () {
- return Promise.resolve(this.address);
- };
- Wallet.prototype.connect = function (provider) {
- return new Wallet(this, provider);
- };
- Wallet.prototype.signTransaction = function (transaction) {
- var _this = this;
- return (0, lib$3.resolveProperties)(transaction).then(function (tx) {
- if (tx.from != null) {
- if ((0, lib$6.getAddress)(tx.from) !== _this.address) {
- logger.throwArgumentError("transaction from address mismatch", "transaction.from", transaction.from);
- }
- delete tx.from;
- }
- var signature = _this._signingKey().signDigest((0, lib$4.keccak256)((0, lib$e.serialize)(tx)));
- return (0, lib$e.serialize)(tx, signature);
- });
- };
- Wallet.prototype.signMessage = function (message) {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- return [2 /*return*/, (0, lib$1.joinSignature)(this._signingKey().signDigest((0, lib$9.hashMessage)(message)))];
- });
- });
- };
- Wallet.prototype._signTypedData = function (domain, types, value) {
- return __awaiter(this, void 0, void 0, function () {
- var populated;
- var _this = this;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, lib$9._TypedDataEncoder.resolveNames(domain, types, value, function (name) {
- if (_this.provider == null) {
- logger.throwError("cannot resolve ENS names without a provider", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "resolveName",
- value: name
- });
- }
- return _this.provider.resolveName(name);
- })];
- case 1:
- populated = _a.sent();
- return [2 /*return*/, (0, lib$1.joinSignature)(this._signingKey().signDigest(lib$9._TypedDataEncoder.hash(populated.domain, types, populated.value)))];
- }
- });
- });
- };
- Wallet.prototype.encrypt = function (password, options, progressCallback) {
- if (typeof (options) === "function" && !progressCallback) {
- progressCallback = options;
- options = {};
- }
- if (progressCallback && typeof (progressCallback) !== "function") {
- throw new Error("invalid callback");
- }
- if (!options) {
- options = {};
- }
- return (0, lib$m.encryptKeystore)(this, password, options, progressCallback);
- };
- /**
- * Static methods to create Wallet instances.
- */
- Wallet.createRandom = function (options) {
- var entropy = (0, lib$l.randomBytes)(16);
- if (!options) {
- options = {};
- }
- if (options.extraEntropy) {
- entropy = (0, lib$1.arrayify)((0, lib$1.hexDataSlice)((0, lib$4.keccak256)((0, lib$1.concat)([entropy, options.extraEntropy])), 0, 16));
- }
- var mnemonic = (0, lib$k.entropyToMnemonic)(entropy, options.locale);
- return Wallet.fromMnemonic(mnemonic, options.path, options.locale);
- };
- Wallet.fromEncryptedJson = function (json, password, progressCallback) {
- return (0, lib$m.decryptJsonWallet)(json, password, progressCallback).then(function (account) {
- return new Wallet(account);
- });
- };
- Wallet.fromEncryptedJsonSync = function (json, password) {
- return new Wallet((0, lib$m.decryptJsonWalletSync)(json, password));
- };
- Wallet.fromMnemonic = function (mnemonic, path, wordlist) {
- if (!path) {
- path = lib$k.defaultPath;
- }
- return new Wallet(lib$k.HDNode.fromMnemonic(mnemonic, null, wordlist).derivePath(path));
- };
- return Wallet;
- }(lib$c.Signer));
- exports.Wallet = Wallet;
- function verifyMessage(message, signature) {
- return (0, lib$e.recoverAddress)((0, lib$9.hashMessage)(message), signature);
- }
- exports.verifyMessage = verifyMessage;
- function verifyTypedData(domain, types, value, signature) {
- return (0, lib$e.recoverAddress)(lib$9._TypedDataEncoder.hash(domain, types, value), signature);
- }
- exports.verifyTypedData = verifyTypedData;
- });
- var index$n = /*@__PURE__*/getDefaultExportFromCjs(lib$n);
- var _version$E = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "networks/5.6.0";
- });
- var _version$F = /*@__PURE__*/getDefaultExportFromCjs(_version$E);
- var lib$o = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getNetwork = void 0;
- var logger = new lib.Logger(_version$E.version);
- ;
- function isRenetworkable(value) {
- return (value && typeof (value.renetwork) === "function");
- }
- function ethDefaultProvider(network) {
- var func = function (providers, options) {
- if (options == null) {
- options = {};
- }
- var providerList = [];
- if (providers.InfuraProvider && options.infura !== "-") {
- try {
- providerList.push(new providers.InfuraProvider(network, options.infura));
- }
- catch (error) { }
- }
- if (providers.EtherscanProvider && options.etherscan !== "-") {
- try {
- providerList.push(new providers.EtherscanProvider(network, options.etherscan));
- }
- catch (error) { }
- }
- if (providers.AlchemyProvider && options.alchemy !== "-") {
- try {
- providerList.push(new providers.AlchemyProvider(network, options.alchemy));
- }
- catch (error) { }
- }
- if (providers.PocketProvider && options.pocket !== "-") {
- // These networks are currently faulty on Pocket as their
- // network does not handle the Berlin hardfork, which is
- // live on these ones.
- // @TODO: This goes away once Pocket has upgraded their nodes
- var skip = ["goerli", "ropsten", "rinkeby"];
- try {
- var provider = new providers.PocketProvider(network);
- if (provider.network && skip.indexOf(provider.network.name) === -1) {
- providerList.push(provider);
- }
- }
- catch (error) { }
- }
- if (providers.CloudflareProvider && options.cloudflare !== "-") {
- try {
- providerList.push(new providers.CloudflareProvider(network));
- }
- catch (error) { }
- }
- if (providerList.length === 0) {
- return null;
- }
- if (providers.FallbackProvider) {
- var quorum = 1;
- if (options.quorum != null) {
- quorum = options.quorum;
- }
- else if (network === "homestead") {
- quorum = 2;
- }
- return new providers.FallbackProvider(providerList, quorum);
- }
- return providerList[0];
- };
- func.renetwork = function (network) {
- return ethDefaultProvider(network);
- };
- return func;
- }
- function etcDefaultProvider(url, network) {
- var func = function (providers, options) {
- if (providers.JsonRpcProvider) {
- return new providers.JsonRpcProvider(url, network);
- }
- return null;
- };
- func.renetwork = function (network) {
- return etcDefaultProvider(url, network);
- };
- return func;
- }
- var homestead = {
- chainId: 1,
- ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",
- name: "homestead",
- _defaultProvider: ethDefaultProvider("homestead")
- };
- var ropsten = {
- chainId: 3,
- ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",
- name: "ropsten",
- _defaultProvider: ethDefaultProvider("ropsten")
- };
- var classicMordor = {
- chainId: 63,
- name: "classicMordor",
- _defaultProvider: etcDefaultProvider("https://www.ethercluster.com/mordor", "classicMordor")
- };
- // See: https://chainlist.org
- var networks = {
- unspecified: { chainId: 0, name: "unspecified" },
- homestead: homestead,
- mainnet: homestead,
- morden: { chainId: 2, name: "morden" },
- ropsten: ropsten,
- testnet: ropsten,
- rinkeby: {
- chainId: 4,
- ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",
- name: "rinkeby",
- _defaultProvider: ethDefaultProvider("rinkeby")
- },
- kovan: {
- chainId: 42,
- name: "kovan",
- _defaultProvider: ethDefaultProvider("kovan")
- },
- goerli: {
- chainId: 5,
- ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e",
- name: "goerli",
- _defaultProvider: ethDefaultProvider("goerli")
- },
- kintsugi: { chainId: 1337702, name: "kintsugi" },
- // ETC (See: #351)
- classic: {
- chainId: 61,
- name: "classic",
- _defaultProvider: etcDefaultProvider("https:/\/www.ethercluster.com/etc", "classic")
- },
- classicMorden: { chainId: 62, name: "classicMorden" },
- classicMordor: classicMordor,
- classicTestnet: classicMordor,
- classicKotti: {
- chainId: 6,
- name: "classicKotti",
- _defaultProvider: etcDefaultProvider("https:/\/www.ethercluster.com/kotti", "classicKotti")
- },
- xdai: { chainId: 100, name: "xdai" },
- matic: { chainId: 137, name: "matic" },
- maticmum: { chainId: 80001, name: "maticmum" },
- optimism: { chainId: 10, name: "optimism" },
- "optimism-kovan": { chainId: 69, name: "optimism-kovan" },
- "optimism-goerli": { chainId: 420, name: "optimism-goerli" },
- arbitrum: { chainId: 42161, name: "arbitrum" },
- "arbitrum-rinkeby": { chainId: 421611, name: "arbitrum-rinkeby" },
- bnb: { chainId: 56, name: "bnb" },
- bnbt: { chainId: 97, name: "bnbt" },
- };
- /**
- * getNetwork
- *
- * Converts a named common networks or chain ID (network ID) to a Network
- * and verifies a network is a valid Network..
- */
- function getNetwork(network) {
- // No network (null)
- if (network == null) {
- return null;
- }
- if (typeof (network) === "number") {
- for (var name_1 in networks) {
- var standard_1 = networks[name_1];
- if (standard_1.chainId === network) {
- return {
- name: standard_1.name,
- chainId: standard_1.chainId,
- ensAddress: (standard_1.ensAddress || null),
- _defaultProvider: (standard_1._defaultProvider || null)
- };
- }
- }
- return {
- chainId: network,
- name: "unknown"
- };
- }
- if (typeof (network) === "string") {
- var standard_2 = networks[network];
- if (standard_2 == null) {
- return null;
- }
- return {
- name: standard_2.name,
- chainId: standard_2.chainId,
- ensAddress: standard_2.ensAddress,
- _defaultProvider: (standard_2._defaultProvider || null)
- };
- }
- var standard = networks[network.name];
- // Not a standard network; check that it is a valid network in general
- if (!standard) {
- if (typeof (network.chainId) !== "number") {
- logger.throwArgumentError("invalid network chainId", "network", network);
- }
- return network;
- }
- // Make sure the chainId matches the expected network chainId (or is 0; disable EIP-155)
- if (network.chainId !== 0 && network.chainId !== standard.chainId) {
- logger.throwArgumentError("network chainId mismatch", "network", network);
- }
- // @TODO: In the next major version add an attach function to a defaultProvider
- // class and move the _defaultProvider internal to this file (extend Network)
- var defaultProvider = network._defaultProvider || null;
- if (defaultProvider == null && standard._defaultProvider) {
- if (isRenetworkable(standard._defaultProvider)) {
- defaultProvider = standard._defaultProvider.renetwork(network);
- }
- else {
- defaultProvider = standard._defaultProvider;
- }
- }
- // Standard Network (allow overriding the ENS address)
- return {
- name: network.name,
- chainId: standard.chainId,
- ensAddress: (network.ensAddress || standard.ensAddress || null),
- _defaultProvider: defaultProvider
- };
- }
- exports.getNetwork = getNetwork;
- });
- var index$o = /*@__PURE__*/getDefaultExportFromCjs(lib$o);
- var browserBase64 = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.encode = exports.decode = void 0;
- function decode(textData) {
- textData = atob(textData);
- var data = [];
- for (var i = 0; i < textData.length; i++) {
- data.push(textData.charCodeAt(i));
- }
- return (0, lib$1.arrayify)(data);
- }
- exports.decode = decode;
- function encode(data) {
- data = (0, lib$1.arrayify)(data);
- var textData = "";
- for (var i = 0; i < data.length; i++) {
- textData += String.fromCharCode(data[i]);
- }
- return btoa(textData);
- }
- exports.encode = encode;
- });
- var browserBase64$1 = /*@__PURE__*/getDefaultExportFromCjs(browserBase64);
- var lib$p = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.encode = exports.decode = void 0;
- Object.defineProperty(exports, "decode", { enumerable: true, get: function () { return browserBase64.decode; } });
- Object.defineProperty(exports, "encode", { enumerable: true, get: function () { return browserBase64.encode; } });
- });
- var index$p = /*@__PURE__*/getDefaultExportFromCjs(lib$p);
- var _version$G = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "web/5.6.0";
- });
- var _version$H = /*@__PURE__*/getDefaultExportFromCjs(_version$G);
- var browserGeturl = createCommonjsModule(function (module, exports) {
- "use strict";
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.getUrl = void 0;
- function getUrl(href, options) {
- return __awaiter(this, void 0, void 0, function () {
- var request, response, body, headers;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (options == null) {
- options = {};
- }
- request = {
- method: (options.method || "GET"),
- headers: (options.headers || {}),
- body: (options.body || undefined),
- };
- if (options.skipFetchSetup !== true) {
- request.mode = "cors"; // no-cors, cors, *same-origin
- request.cache = "no-cache"; // *default, no-cache, reload, force-cache, only-if-cached
- request.credentials = "same-origin"; // include, *same-origin, omit
- request.redirect = "follow"; // manual, *follow, error
- request.referrer = "client"; // no-referrer, *client
- }
- ;
- return [4 /*yield*/, fetch(href, request)];
- case 1:
- response = _a.sent();
- return [4 /*yield*/, response.arrayBuffer()];
- case 2:
- body = _a.sent();
- headers = {};
- if (response.headers.forEach) {
- response.headers.forEach(function (value, key) {
- headers[key.toLowerCase()] = value;
- });
- }
- else {
- ((response.headers).keys)().forEach(function (key) {
- headers[key.toLowerCase()] = response.headers.get(key);
- });
- }
- return [2 /*return*/, {
- headers: headers,
- statusCode: response.status,
- statusMessage: response.statusText,
- body: (0, lib$1.arrayify)(new Uint8Array(body)),
- }];
- }
- });
- });
- }
- exports.getUrl = getUrl;
- });
- var browserGeturl$1 = /*@__PURE__*/getDefaultExportFromCjs(browserGeturl);
- var lib$q = createCommonjsModule(function (module, exports) {
- "use strict";
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.poll = exports.fetchJson = exports._fetchData = void 0;
- var logger = new lib.Logger(_version$G.version);
- function staller(duration) {
- return new Promise(function (resolve) {
- setTimeout(resolve, duration);
- });
- }
- function bodyify(value, type) {
- if (value == null) {
- return null;
- }
- if (typeof (value) === "string") {
- return value;
- }
- if ((0, lib$1.isBytesLike)(value)) {
- if (type && (type.split("/")[0] === "text" || type.split(";")[0].trim() === "application/json")) {
- try {
- return (0, lib$8.toUtf8String)(value);
- }
- catch (error) { }
- ;
- }
- return (0, lib$1.hexlify)(value);
- }
- return value;
- }
- // This API is still a work in progress; the future changes will likely be:
- // - ConnectionInfo => FetchDataRequest<T = any>
- // - FetchDataRequest.body? = string | Uint8Array | { contentType: string, data: string | Uint8Array }
- // - If string => text/plain, Uint8Array => application/octet-stream (if content-type unspecified)
- // - FetchDataRequest.processFunc = (body: Uint8Array, response: FetchDataResponse) => T
- // For this reason, it should be considered internal until the API is finalized
- function _fetchData(connection, body, processFunc) {
- // How many times to retry in the event of a throttle
- var attemptLimit = (typeof (connection) === "object" && connection.throttleLimit != null) ? connection.throttleLimit : 12;
- logger.assertArgument((attemptLimit > 0 && (attemptLimit % 1) === 0), "invalid connection throttle limit", "connection.throttleLimit", attemptLimit);
- var throttleCallback = ((typeof (connection) === "object") ? connection.throttleCallback : null);
- var throttleSlotInterval = ((typeof (connection) === "object" && typeof (connection.throttleSlotInterval) === "number") ? connection.throttleSlotInterval : 100);
- logger.assertArgument((throttleSlotInterval > 0 && (throttleSlotInterval % 1) === 0), "invalid connection throttle slot interval", "connection.throttleSlotInterval", throttleSlotInterval);
- var errorPassThrough = ((typeof (connection) === "object") ? !!(connection.errorPassThrough) : false);
- var headers = {};
- var url = null;
- // @TODO: Allow ConnectionInfo to override some of these values
- var options = {
- method: "GET",
- };
- var allow304 = false;
- var timeout = 2 * 60 * 1000;
- if (typeof (connection) === "string") {
- url = connection;
- }
- else if (typeof (connection) === "object") {
- if (connection == null || connection.url == null) {
- logger.throwArgumentError("missing URL", "connection.url", connection);
- }
- url = connection.url;
- if (typeof (connection.timeout) === "number" && connection.timeout > 0) {
- timeout = connection.timeout;
- }
- if (connection.headers) {
- for (var key in connection.headers) {
- headers[key.toLowerCase()] = { key: key, value: String(connection.headers[key]) };
- if (["if-none-match", "if-modified-since"].indexOf(key.toLowerCase()) >= 0) {
- allow304 = true;
- }
- }
- }
- options.allowGzip = !!connection.allowGzip;
- if (connection.user != null && connection.password != null) {
- if (url.substring(0, 6) !== "https:" && connection.allowInsecureAuthentication !== true) {
- logger.throwError("basic authentication requires a secure https url", lib.Logger.errors.INVALID_ARGUMENT, { argument: "url", url: url, user: connection.user, password: "[REDACTED]" });
- }
- var authorization = connection.user + ":" + connection.password;
- headers["authorization"] = {
- key: "Authorization",
- value: "Basic " + (0, lib$p.encode)((0, lib$8.toUtf8Bytes)(authorization))
- };
- }
- if (connection.skipFetchSetup != null) {
- options.skipFetchSetup = !!connection.skipFetchSetup;
- }
- }
- var reData = new RegExp("^data:([a-z0-9-]+/[a-z0-9-]+);base64,(.*)$", "i");
- var dataMatch = ((url) ? url.match(reData) : null);
- if (dataMatch) {
- try {
- var response = {
- statusCode: 200,
- statusMessage: "OK",
- headers: { "content-type": dataMatch[1] },
- body: (0, lib$p.decode)(dataMatch[2])
- };
- var result = response.body;
- if (processFunc) {
- result = processFunc(response.body, response);
- }
- return Promise.resolve(result);
- }
- catch (error) {
- logger.throwError("processing response error", lib.Logger.errors.SERVER_ERROR, {
- body: bodyify(dataMatch[1], dataMatch[2]),
- error: error,
- requestBody: null,
- requestMethod: "GET",
- url: url
- });
- }
- }
- if (body) {
- options.method = "POST";
- options.body = body;
- if (headers["content-type"] == null) {
- headers["content-type"] = { key: "Content-Type", value: "application/octet-stream" };
- }
- if (headers["content-length"] == null) {
- headers["content-length"] = { key: "Content-Length", value: String(body.length) };
- }
- }
- var flatHeaders = {};
- Object.keys(headers).forEach(function (key) {
- var header = headers[key];
- flatHeaders[header.key] = header.value;
- });
- options.headers = flatHeaders;
- var runningTimeout = (function () {
- var timer = null;
- var promise = new Promise(function (resolve, reject) {
- if (timeout) {
- timer = setTimeout(function () {
- if (timer == null) {
- return;
- }
- timer = null;
- reject(logger.makeError("timeout", lib.Logger.errors.TIMEOUT, {
- requestBody: bodyify(options.body, flatHeaders["content-type"]),
- requestMethod: options.method,
- timeout: timeout,
- url: url
- }));
- }, timeout);
- }
- });
- var cancel = function () {
- if (timer == null) {
- return;
- }
- clearTimeout(timer);
- timer = null;
- };
- return { promise: promise, cancel: cancel };
- })();
- var runningFetch = (function () {
- return __awaiter(this, void 0, void 0, function () {
- var attempt, response, location_1, tryAgain, stall, retryAfter, error_1, body_1, result, error_2, tryAgain, timeout_1;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- attempt = 0;
- _a.label = 1;
- case 1:
- if (!(attempt < attemptLimit)) return [3 /*break*/, 20];
- response = null;
- _a.label = 2;
- case 2:
- _a.trys.push([2, 9, , 10]);
- return [4 /*yield*/, (0, browserGeturl.getUrl)(url, options)];
- case 3:
- response = _a.sent();
- if (!(attempt < attemptLimit)) return [3 /*break*/, 8];
- if (!(response.statusCode === 301 || response.statusCode === 302)) return [3 /*break*/, 4];
- location_1 = response.headers.location || "";
- if (options.method === "GET" && location_1.match(/^https:/)) {
- url = response.headers.location;
- return [3 /*break*/, 19];
- }
- return [3 /*break*/, 8];
- case 4:
- if (!(response.statusCode === 429)) return [3 /*break*/, 8];
- tryAgain = true;
- if (!throttleCallback) return [3 /*break*/, 6];
- return [4 /*yield*/, throttleCallback(attempt, url)];
- case 5:
- tryAgain = _a.sent();
- _a.label = 6;
- case 6:
- if (!tryAgain) return [3 /*break*/, 8];
- stall = 0;
- retryAfter = response.headers["retry-after"];
- if (typeof (retryAfter) === "string" && retryAfter.match(/^[1-9][0-9]*$/)) {
- stall = parseInt(retryAfter) * 1000;
- }
- else {
- stall = throttleSlotInterval * parseInt(String(Math.random() * Math.pow(2, attempt)));
- }
- //console.log("Stalling 429");
- return [4 /*yield*/, staller(stall)];
- case 7:
- //console.log("Stalling 429");
- _a.sent();
- return [3 /*break*/, 19];
- case 8: return [3 /*break*/, 10];
- case 9:
- error_1 = _a.sent();
- response = error_1.response;
- if (response == null) {
- runningTimeout.cancel();
- logger.throwError("missing response", lib.Logger.errors.SERVER_ERROR, {
- requestBody: bodyify(options.body, flatHeaders["content-type"]),
- requestMethod: options.method,
- serverError: error_1,
- url: url
- });
- }
- return [3 /*break*/, 10];
- case 10:
- body_1 = response.body;
- if (allow304 && response.statusCode === 304) {
- body_1 = null;
- }
- else if (!errorPassThrough && (response.statusCode < 200 || response.statusCode >= 300)) {
- runningTimeout.cancel();
- logger.throwError("bad response", lib.Logger.errors.SERVER_ERROR, {
- status: response.statusCode,
- headers: response.headers,
- body: bodyify(body_1, ((response.headers) ? response.headers["content-type"] : null)),
- requestBody: bodyify(options.body, flatHeaders["content-type"]),
- requestMethod: options.method,
- url: url
- });
- }
- if (!processFunc) return [3 /*break*/, 18];
- _a.label = 11;
- case 11:
- _a.trys.push([11, 13, , 18]);
- return [4 /*yield*/, processFunc(body_1, response)];
- case 12:
- result = _a.sent();
- runningTimeout.cancel();
- return [2 /*return*/, result];
- case 13:
- error_2 = _a.sent();
- if (!(error_2.throttleRetry && attempt < attemptLimit)) return [3 /*break*/, 17];
- tryAgain = true;
- if (!throttleCallback) return [3 /*break*/, 15];
- return [4 /*yield*/, throttleCallback(attempt, url)];
- case 14:
- tryAgain = _a.sent();
- _a.label = 15;
- case 15:
- if (!tryAgain) return [3 /*break*/, 17];
- timeout_1 = throttleSlotInterval * parseInt(String(Math.random() * Math.pow(2, attempt)));
- //console.log("Stalling callback");
- return [4 /*yield*/, staller(timeout_1)];
- case 16:
- //console.log("Stalling callback");
- _a.sent();
- return [3 /*break*/, 19];
- case 17:
- runningTimeout.cancel();
- logger.throwError("processing response error", lib.Logger.errors.SERVER_ERROR, {
- body: bodyify(body_1, ((response.headers) ? response.headers["content-type"] : null)),
- error: error_2,
- requestBody: bodyify(options.body, flatHeaders["content-type"]),
- requestMethod: options.method,
- url: url
- });
- return [3 /*break*/, 18];
- case 18:
- runningTimeout.cancel();
- // If we had a processFunc, it either returned a T or threw above.
- // The "body" is now a Uint8Array.
- return [2 /*return*/, body_1];
- case 19:
- attempt++;
- return [3 /*break*/, 1];
- case 20: return [2 /*return*/, logger.throwError("failed response", lib.Logger.errors.SERVER_ERROR, {
- requestBody: bodyify(options.body, flatHeaders["content-type"]),
- requestMethod: options.method,
- url: url
- })];
- }
- });
- });
- })();
- return Promise.race([runningTimeout.promise, runningFetch]);
- }
- exports._fetchData = _fetchData;
- function fetchJson(connection, json, processFunc) {
- var processJsonFunc = function (value, response) {
- var result = null;
- if (value != null) {
- try {
- result = JSON.parse((0, lib$8.toUtf8String)(value));
- }
- catch (error) {
- logger.throwError("invalid JSON", lib.Logger.errors.SERVER_ERROR, {
- body: value,
- error: error
- });
- }
- }
- if (processFunc) {
- result = processFunc(result, response);
- }
- return result;
- };
- // If we have json to send, we must
- // - add content-type of application/json (unless already overridden)
- // - convert the json to bytes
- var body = null;
- if (json != null) {
- body = (0, lib$8.toUtf8Bytes)(json);
- // Create a connection with the content-type set for JSON
- var updated = (typeof (connection) === "string") ? ({ url: connection }) : (0, lib$3.shallowCopy)(connection);
- if (updated.headers) {
- var hasContentType = (Object.keys(updated.headers).filter(function (k) { return (k.toLowerCase() === "content-type"); }).length) !== 0;
- if (!hasContentType) {
- updated.headers = (0, lib$3.shallowCopy)(updated.headers);
- updated.headers["content-type"] = "application/json";
- }
- }
- else {
- updated.headers = { "content-type": "application/json" };
- }
- connection = updated;
- }
- return _fetchData(connection, body, processJsonFunc);
- }
- exports.fetchJson = fetchJson;
- function poll(func, options) {
- if (!options) {
- options = {};
- }
- options = (0, lib$3.shallowCopy)(options);
- if (options.floor == null) {
- options.floor = 0;
- }
- if (options.ceiling == null) {
- options.ceiling = 10000;
- }
- if (options.interval == null) {
- options.interval = 250;
- }
- return new Promise(function (resolve, reject) {
- var timer = null;
- var done = false;
- // Returns true if cancel was successful. Unsuccessful cancel means we're already done.
- var cancel = function () {
- if (done) {
- return false;
- }
- done = true;
- if (timer) {
- clearTimeout(timer);
- }
- return true;
- };
- if (options.timeout) {
- timer = setTimeout(function () {
- if (cancel()) {
- reject(new Error("timeout"));
- }
- }, options.timeout);
- }
- var retryLimit = options.retryLimit;
- var attempt = 0;
- function check() {
- return func().then(function (result) {
- // If we have a result, or are allowed null then we're done
- if (result !== undefined) {
- if (cancel()) {
- resolve(result);
- }
- }
- else if (options.oncePoll) {
- options.oncePoll.once("poll", check);
- }
- else if (options.onceBlock) {
- options.onceBlock.once("block", check);
- // Otherwise, exponential back-off (up to 10s) our next request
- }
- else if (!done) {
- attempt++;
- if (attempt > retryLimit) {
- if (cancel()) {
- reject(new Error("retry limit reached"));
- }
- return;
- }
- var timeout = options.interval * parseInt(String(Math.random() * Math.pow(2, attempt)));
- if (timeout < options.floor) {
- timeout = options.floor;
- }
- if (timeout > options.ceiling) {
- timeout = options.ceiling;
- }
- setTimeout(check, timeout);
- }
- return null;
- }, function (error) {
- if (cancel()) {
- reject(error);
- }
- });
- }
- check();
- });
- }
- exports.poll = poll;
- });
- var index$q = /*@__PURE__*/getDefaultExportFromCjs(lib$q);
- 'use strict';
- var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';
- // pre-compute lookup table
- var ALPHABET_MAP = {};
- for (var z = 0; z < ALPHABET.length; z++) {
- var x = ALPHABET.charAt(z);
- if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous')
- ALPHABET_MAP[x] = z;
- }
- function polymodStep (pre) {
- var b = pre >> 25;
- return ((pre & 0x1FFFFFF) << 5) ^
- (-((b >> 0) & 1) & 0x3b6a57b2) ^
- (-((b >> 1) & 1) & 0x26508e6d) ^
- (-((b >> 2) & 1) & 0x1ea119fa) ^
- (-((b >> 3) & 1) & 0x3d4233dd) ^
- (-((b >> 4) & 1) & 0x2a1462b3)
- }
- function prefixChk (prefix) {
- var chk = 1;
- for (var i = 0; i < prefix.length; ++i) {
- var c = prefix.charCodeAt(i);
- if (c < 33 || c > 126) return 'Invalid prefix (' + prefix + ')'
- chk = polymodStep(chk) ^ (c >> 5);
- }
- chk = polymodStep(chk);
- for (i = 0; i < prefix.length; ++i) {
- var v = prefix.charCodeAt(i);
- chk = polymodStep(chk) ^ (v & 0x1f);
- }
- return chk
- }
- function encode (prefix, words, LIMIT) {
- LIMIT = LIMIT || 90;
- if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit')
- prefix = prefix.toLowerCase();
- // determine chk mod
- var chk = prefixChk(prefix);
- if (typeof chk === 'string') throw new Error(chk)
- var result = prefix + '1';
- for (var i = 0; i < words.length; ++i) {
- var x = words[i];
- if ((x >> 5) !== 0) throw new Error('Non 5-bit word')
- chk = polymodStep(chk) ^ x;
- result += ALPHABET.charAt(x);
- }
- for (i = 0; i < 6; ++i) {
- chk = polymodStep(chk);
- }
- chk ^= 1;
- for (i = 0; i < 6; ++i) {
- var v = (chk >> ((5 - i) * 5)) & 0x1f;
- result += ALPHABET.charAt(v);
- }
- return result
- }
- function __decode (str, LIMIT) {
- LIMIT = LIMIT || 90;
- if (str.length < 8) return str + ' too short'
- if (str.length > LIMIT) return 'Exceeds length limit'
- // don't allow mixed case
- var lowered = str.toLowerCase();
- var uppered = str.toUpperCase();
- if (str !== lowered && str !== uppered) return 'Mixed-case string ' + str
- str = lowered;
- var split = str.lastIndexOf('1');
- if (split === -1) return 'No separator character for ' + str
- if (split === 0) return 'Missing prefix for ' + str
- var prefix = str.slice(0, split);
- var wordChars = str.slice(split + 1);
- if (wordChars.length < 6) return 'Data too short'
- var chk = prefixChk(prefix);
- if (typeof chk === 'string') return chk
- var words = [];
- for (var i = 0; i < wordChars.length; ++i) {
- var c = wordChars.charAt(i);
- var v = ALPHABET_MAP[c];
- if (v === undefined) return 'Unknown character ' + c
- chk = polymodStep(chk) ^ v;
- // not in the checksum?
- if (i + 6 >= wordChars.length) continue
- words.push(v);
- }
- if (chk !== 1) return 'Invalid checksum for ' + str
- return { prefix: prefix, words: words }
- }
- function decodeUnsafe () {
- var res = __decode.apply(null, arguments);
- if (typeof res === 'object') return res
- }
- function decode (str) {
- var res = __decode.apply(null, arguments);
- if (typeof res === 'object') return res
- throw new Error(res)
- }
- function convert (data, inBits, outBits, pad) {
- var value = 0;
- var bits = 0;
- var maxV = (1 << outBits) - 1;
- var result = [];
- for (var i = 0; i < data.length; ++i) {
- value = (value << inBits) | data[i];
- bits += inBits;
- while (bits >= outBits) {
- bits -= outBits;
- result.push((value >> bits) & maxV);
- }
- }
- if (pad) {
- if (bits > 0) {
- result.push((value << (outBits - bits)) & maxV);
- }
- } else {
- if (bits >= inBits) return 'Excess padding'
- if ((value << (outBits - bits)) & maxV) return 'Non-zero padding'
- }
- return result
- }
- function toWordsUnsafe (bytes) {
- var res = convert(bytes, 8, 5, true);
- if (Array.isArray(res)) return res
- }
- function toWords (bytes) {
- var res = convert(bytes, 8, 5, true);
- if (Array.isArray(res)) return res
- throw new Error(res)
- }
- function fromWordsUnsafe (words) {
- var res = convert(words, 5, 8, false);
- if (Array.isArray(res)) return res
- }
- function fromWords (words) {
- var res = convert(words, 5, 8, false);
- if (Array.isArray(res)) return res
- throw new Error(res)
- }
- var bech32 = {
- decodeUnsafe: decodeUnsafe,
- decode: decode,
- encode: encode,
- toWordsUnsafe: toWordsUnsafe,
- toWords: toWords,
- fromWordsUnsafe: fromWordsUnsafe,
- fromWords: fromWords
- };
- var _version$I = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "providers/5.6.0";
- });
- var _version$J = /*@__PURE__*/getDefaultExportFromCjs(_version$I);
- var formatter = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.showThrottleMessage = exports.isCommunityResource = exports.isCommunityResourcable = exports.Formatter = void 0;
- var logger = new lib.Logger(_version$I.version);
- var Formatter = /** @class */ (function () {
- function Formatter() {
- var _newTarget = this.constructor;
- logger.checkNew(_newTarget, Formatter);
- this.formats = this.getDefaultFormats();
- }
- Formatter.prototype.getDefaultFormats = function () {
- var _this = this;
- var formats = ({});
- var address = this.address.bind(this);
- var bigNumber = this.bigNumber.bind(this);
- var blockTag = this.blockTag.bind(this);
- var data = this.data.bind(this);
- var hash = this.hash.bind(this);
- var hex = this.hex.bind(this);
- var number = this.number.bind(this);
- var type = this.type.bind(this);
- var strictData = function (v) { return _this.data(v, true); };
- formats.transaction = {
- hash: hash,
- type: type,
- accessList: Formatter.allowNull(this.accessList.bind(this), null),
- blockHash: Formatter.allowNull(hash, null),
- blockNumber: Formatter.allowNull(number, null),
- transactionIndex: Formatter.allowNull(number, null),
- confirmations: Formatter.allowNull(number, null),
- from: address,
- // either (gasPrice) or (maxPriorityFeePerGas + maxFeePerGas)
- // must be set
- gasPrice: Formatter.allowNull(bigNumber),
- maxPriorityFeePerGas: Formatter.allowNull(bigNumber),
- maxFeePerGas: Formatter.allowNull(bigNumber),
- gasLimit: bigNumber,
- to: Formatter.allowNull(address, null),
- value: bigNumber,
- nonce: number,
- data: data,
- r: Formatter.allowNull(this.uint256),
- s: Formatter.allowNull(this.uint256),
- v: Formatter.allowNull(number),
- creates: Formatter.allowNull(address, null),
- raw: Formatter.allowNull(data),
- };
- formats.transactionRequest = {
- from: Formatter.allowNull(address),
- nonce: Formatter.allowNull(number),
- gasLimit: Formatter.allowNull(bigNumber),
- gasPrice: Formatter.allowNull(bigNumber),
- maxPriorityFeePerGas: Formatter.allowNull(bigNumber),
- maxFeePerGas: Formatter.allowNull(bigNumber),
- to: Formatter.allowNull(address),
- value: Formatter.allowNull(bigNumber),
- data: Formatter.allowNull(strictData),
- type: Formatter.allowNull(number),
- accessList: Formatter.allowNull(this.accessList.bind(this), null),
- };
- formats.receiptLog = {
- transactionIndex: number,
- blockNumber: number,
- transactionHash: hash,
- address: address,
- topics: Formatter.arrayOf(hash),
- data: data,
- logIndex: number,
- blockHash: hash,
- };
- formats.receipt = {
- to: Formatter.allowNull(this.address, null),
- from: Formatter.allowNull(this.address, null),
- contractAddress: Formatter.allowNull(address, null),
- transactionIndex: number,
- // should be allowNull(hash), but broken-EIP-658 support is handled in receipt
- root: Formatter.allowNull(hex),
- gasUsed: bigNumber,
- logsBloom: Formatter.allowNull(data),
- blockHash: hash,
- transactionHash: hash,
- logs: Formatter.arrayOf(this.receiptLog.bind(this)),
- blockNumber: number,
- confirmations: Formatter.allowNull(number, null),
- cumulativeGasUsed: bigNumber,
- effectiveGasPrice: Formatter.allowNull(bigNumber),
- status: Formatter.allowNull(number),
- type: type
- };
- formats.block = {
- hash: Formatter.allowNull(hash),
- parentHash: hash,
- number: number,
- timestamp: number,
- nonce: Formatter.allowNull(hex),
- difficulty: this.difficulty.bind(this),
- gasLimit: bigNumber,
- gasUsed: bigNumber,
- miner: Formatter.allowNull(address),
- extraData: data,
- transactions: Formatter.allowNull(Formatter.arrayOf(hash)),
- baseFeePerGas: Formatter.allowNull(bigNumber)
- };
- formats.blockWithTransactions = (0, lib$3.shallowCopy)(formats.block);
- formats.blockWithTransactions.transactions = Formatter.allowNull(Formatter.arrayOf(this.transactionResponse.bind(this)));
- formats.filter = {
- fromBlock: Formatter.allowNull(blockTag, undefined),
- toBlock: Formatter.allowNull(blockTag, undefined),
- blockHash: Formatter.allowNull(hash, undefined),
- address: Formatter.allowNull(address, undefined),
- topics: Formatter.allowNull(this.topics.bind(this), undefined),
- };
- formats.filterLog = {
- blockNumber: Formatter.allowNull(number),
- blockHash: Formatter.allowNull(hash),
- transactionIndex: number,
- removed: Formatter.allowNull(this.boolean.bind(this)),
- address: address,
- data: Formatter.allowFalsish(data, "0x"),
- topics: Formatter.arrayOf(hash),
- transactionHash: hash,
- logIndex: number,
- };
- return formats;
- };
- Formatter.prototype.accessList = function (accessList) {
- return (0, lib$e.accessListify)(accessList || []);
- };
- // Requires a BigNumberish that is within the IEEE754 safe integer range; returns a number
- // Strict! Used on input.
- Formatter.prototype.number = function (number) {
- if (number === "0x") {
- return 0;
- }
- return lib$2.BigNumber.from(number).toNumber();
- };
- Formatter.prototype.type = function (number) {
- if (number === "0x" || number == null) {
- return 0;
- }
- return lib$2.BigNumber.from(number).toNumber();
- };
- // Strict! Used on input.
- Formatter.prototype.bigNumber = function (value) {
- return lib$2.BigNumber.from(value);
- };
- // Requires a boolean, "true" or "false"; returns a boolean
- Formatter.prototype.boolean = function (value) {
- if (typeof (value) === "boolean") {
- return value;
- }
- if (typeof (value) === "string") {
- value = value.toLowerCase();
- if (value === "true") {
- return true;
- }
- if (value === "false") {
- return false;
- }
- }
- throw new Error("invalid boolean - " + value);
- };
- Formatter.prototype.hex = function (value, strict) {
- if (typeof (value) === "string") {
- if (!strict && value.substring(0, 2) !== "0x") {
- value = "0x" + value;
- }
- if ((0, lib$1.isHexString)(value)) {
- return value.toLowerCase();
- }
- }
- return logger.throwArgumentError("invalid hash", "value", value);
- };
- Formatter.prototype.data = function (value, strict) {
- var result = this.hex(value, strict);
- if ((result.length % 2) !== 0) {
- throw new Error("invalid data; odd-length - " + value);
- }
- return result;
- };
- // Requires an address
- // Strict! Used on input.
- Formatter.prototype.address = function (value) {
- return (0, lib$6.getAddress)(value);
- };
- Formatter.prototype.callAddress = function (value) {
- if (!(0, lib$1.isHexString)(value, 32)) {
- return null;
- }
- var address = (0, lib$6.getAddress)((0, lib$1.hexDataSlice)(value, 12));
- return (address === lib$7.AddressZero) ? null : address;
- };
- Formatter.prototype.contractAddress = function (value) {
- return (0, lib$6.getContractAddress)(value);
- };
- // Strict! Used on input.
- Formatter.prototype.blockTag = function (blockTag) {
- if (blockTag == null) {
- return "latest";
- }
- if (blockTag === "earliest") {
- return "0x0";
- }
- if (blockTag === "latest" || blockTag === "pending") {
- return blockTag;
- }
- if (typeof (blockTag) === "number" || (0, lib$1.isHexString)(blockTag)) {
- return (0, lib$1.hexValue)(blockTag);
- }
- throw new Error("invalid blockTag");
- };
- // Requires a hash, optionally requires 0x prefix; returns prefixed lowercase hash.
- Formatter.prototype.hash = function (value, strict) {
- var result = this.hex(value, strict);
- if ((0, lib$1.hexDataLength)(result) !== 32) {
- return logger.throwArgumentError("invalid hash", "value", value);
- }
- return result;
- };
- // Returns the difficulty as a number, or if too large (i.e. PoA network) null
- Formatter.prototype.difficulty = function (value) {
- if (value == null) {
- return null;
- }
- var v = lib$2.BigNumber.from(value);
- try {
- return v.toNumber();
- }
- catch (error) { }
- return null;
- };
- Formatter.prototype.uint256 = function (value) {
- if (!(0, lib$1.isHexString)(value)) {
- throw new Error("invalid uint256");
- }
- return (0, lib$1.hexZeroPad)(value, 32);
- };
- Formatter.prototype._block = function (value, format) {
- if (value.author != null && value.miner == null) {
- value.miner = value.author;
- }
- // The difficulty may need to come from _difficulty in recursed blocks
- var difficulty = (value._difficulty != null) ? value._difficulty : value.difficulty;
- var result = Formatter.check(format, value);
- result._difficulty = ((difficulty == null) ? null : lib$2.BigNumber.from(difficulty));
- return result;
- };
- Formatter.prototype.block = function (value) {
- return this._block(value, this.formats.block);
- };
- Formatter.prototype.blockWithTransactions = function (value) {
- return this._block(value, this.formats.blockWithTransactions);
- };
- // Strict! Used on input.
- Formatter.prototype.transactionRequest = function (value) {
- return Formatter.check(this.formats.transactionRequest, value);
- };
- Formatter.prototype.transactionResponse = function (transaction) {
- // Rename gas to gasLimit
- if (transaction.gas != null && transaction.gasLimit == null) {
- transaction.gasLimit = transaction.gas;
- }
- // Some clients (TestRPC) do strange things like return 0x0 for the
- // 0 address; correct this to be a real address
- if (transaction.to && lib$2.BigNumber.from(transaction.to).isZero()) {
- transaction.to = "0x0000000000000000000000000000000000000000";
- }
- // Rename input to data
- if (transaction.input != null && transaction.data == null) {
- transaction.data = transaction.input;
- }
- // If to and creates are empty, populate the creates from the transaction
- if (transaction.to == null && transaction.creates == null) {
- transaction.creates = this.contractAddress(transaction);
- }
- if ((transaction.type === 1 || transaction.type === 2) && transaction.accessList == null) {
- transaction.accessList = [];
- }
- var result = Formatter.check(this.formats.transaction, transaction);
- if (transaction.chainId != null) {
- var chainId = transaction.chainId;
- if ((0, lib$1.isHexString)(chainId)) {
- chainId = lib$2.BigNumber.from(chainId).toNumber();
- }
- result.chainId = chainId;
- }
- else {
- var chainId = transaction.networkId;
- // geth-etc returns chainId
- if (chainId == null && result.v == null) {
- chainId = transaction.chainId;
- }
- if ((0, lib$1.isHexString)(chainId)) {
- chainId = lib$2.BigNumber.from(chainId).toNumber();
- }
- if (typeof (chainId) !== "number" && result.v != null) {
- chainId = (result.v - 35) / 2;
- if (chainId < 0) {
- chainId = 0;
- }
- chainId = parseInt(chainId);
- }
- if (typeof (chainId) !== "number") {
- chainId = 0;
- }
- result.chainId = chainId;
- }
- // 0x0000... should actually be null
- if (result.blockHash && result.blockHash.replace(/0/g, "") === "x") {
- result.blockHash = null;
- }
- return result;
- };
- Formatter.prototype.transaction = function (value) {
- return (0, lib$e.parse)(value);
- };
- Formatter.prototype.receiptLog = function (value) {
- return Formatter.check(this.formats.receiptLog, value);
- };
- Formatter.prototype.receipt = function (value) {
- var result = Formatter.check(this.formats.receipt, value);
- // RSK incorrectly implemented EIP-658, so we munge things a bit here for it
- if (result.root != null) {
- if (result.root.length <= 4) {
- // Could be 0x00, 0x0, 0x01 or 0x1
- var value_1 = lib$2.BigNumber.from(result.root).toNumber();
- if (value_1 === 0 || value_1 === 1) {
- // Make sure if both are specified, they match
- if (result.status != null && (result.status !== value_1)) {
- logger.throwArgumentError("alt-root-status/status mismatch", "value", { root: result.root, status: result.status });
- }
- result.status = value_1;
- delete result.root;
- }
- else {
- logger.throwArgumentError("invalid alt-root-status", "value.root", result.root);
- }
- }
- else if (result.root.length !== 66) {
- // Must be a valid bytes32
- logger.throwArgumentError("invalid root hash", "value.root", result.root);
- }
- }
- if (result.status != null) {
- result.byzantium = true;
- }
- return result;
- };
- Formatter.prototype.topics = function (value) {
- var _this = this;
- if (Array.isArray(value)) {
- return value.map(function (v) { return _this.topics(v); });
- }
- else if (value != null) {
- return this.hash(value, true);
- }
- return null;
- };
- Formatter.prototype.filter = function (value) {
- return Formatter.check(this.formats.filter, value);
- };
- Formatter.prototype.filterLog = function (value) {
- return Formatter.check(this.formats.filterLog, value);
- };
- Formatter.check = function (format, object) {
- var result = {};
- for (var key in format) {
- try {
- var value = format[key](object[key]);
- if (value !== undefined) {
- result[key] = value;
- }
- }
- catch (error) {
- error.checkKey = key;
- error.checkValue = object[key];
- throw error;
- }
- }
- return result;
- };
- // if value is null-ish, nullValue is returned
- Formatter.allowNull = function (format, nullValue) {
- return (function (value) {
- if (value == null) {
- return nullValue;
- }
- return format(value);
- });
- };
- // If value is false-ish, replaceValue is returned
- Formatter.allowFalsish = function (format, replaceValue) {
- return (function (value) {
- if (!value) {
- return replaceValue;
- }
- return format(value);
- });
- };
- // Requires an Array satisfying check
- Formatter.arrayOf = function (format) {
- return (function (array) {
- if (!Array.isArray(array)) {
- throw new Error("not an array");
- }
- var result = [];
- array.forEach(function (value) {
- result.push(format(value));
- });
- return result;
- });
- };
- return Formatter;
- }());
- exports.Formatter = Formatter;
- function isCommunityResourcable(value) {
- return (value && typeof (value.isCommunityResource) === "function");
- }
- exports.isCommunityResourcable = isCommunityResourcable;
- function isCommunityResource(value) {
- return (isCommunityResourcable(value) && value.isCommunityResource());
- }
- exports.isCommunityResource = isCommunityResource;
- // Show the throttle message only once
- var throttleMessage = false;
- function showThrottleMessage() {
- if (throttleMessage) {
- return;
- }
- throttleMessage = true;
- console.log("========= NOTICE =========");
- console.log("Request-Rate Exceeded (this message will not be repeated)");
- console.log("");
- console.log("The default API keys for each service are provided as a highly-throttled,");
- console.log("community resource for low-traffic projects and early prototyping.");
- console.log("");
- console.log("While your application will continue to function, we highly recommended");
- console.log("signing up for your own API keys to improve performance, increase your");
- console.log("request rate/limit and enable other perks, such as metrics and advanced APIs.");
- console.log("");
- console.log("For more details: https:/\/docs.ethers.io/api-keys/");
- console.log("==========================");
- }
- exports.showThrottleMessage = showThrottleMessage;
- });
- var formatter$1 = /*@__PURE__*/getDefaultExportFromCjs(formatter);
- var baseProvider = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- };
- var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.BaseProvider = exports.Resolver = exports.Event = void 0;
- var bech32_1 = __importDefault(bech32);
- var logger = new lib.Logger(_version$I.version);
- var MAX_CCIP_REDIRECTS = 10;
- //////////////////////////////
- // Event Serializeing
- function checkTopic(topic) {
- if (topic == null) {
- return "null";
- }
- if ((0, lib$1.hexDataLength)(topic) !== 32) {
- logger.throwArgumentError("invalid topic", "topic", topic);
- }
- return topic.toLowerCase();
- }
- function serializeTopics(topics) {
- // Remove trailing null AND-topics; they are redundant
- topics = topics.slice();
- while (topics.length > 0 && topics[topics.length - 1] == null) {
- topics.pop();
- }
- return topics.map(function (topic) {
- if (Array.isArray(topic)) {
- // Only track unique OR-topics
- var unique_1 = {};
- topic.forEach(function (topic) {
- unique_1[checkTopic(topic)] = true;
- });
- // The order of OR-topics does not matter
- var sorted = Object.keys(unique_1);
- sorted.sort();
- return sorted.join("|");
- }
- else {
- return checkTopic(topic);
- }
- }).join("&");
- }
- function deserializeTopics(data) {
- if (data === "") {
- return [];
- }
- return data.split(/&/g).map(function (topic) {
- if (topic === "") {
- return [];
- }
- var comps = topic.split("|").map(function (topic) {
- return ((topic === "null") ? null : topic);
- });
- return ((comps.length === 1) ? comps[0] : comps);
- });
- }
- function getEventTag(eventName) {
- if (typeof (eventName) === "string") {
- eventName = eventName.toLowerCase();
- if ((0, lib$1.hexDataLength)(eventName) === 32) {
- return "tx:" + eventName;
- }
- if (eventName.indexOf(":") === -1) {
- return eventName;
- }
- }
- else if (Array.isArray(eventName)) {
- return "filter:*:" + serializeTopics(eventName);
- }
- else if (lib$b.ForkEvent.isForkEvent(eventName)) {
- logger.warn("not implemented");
- throw new Error("not implemented");
- }
- else if (eventName && typeof (eventName) === "object") {
- return "filter:" + (eventName.address || "*") + ":" + serializeTopics(eventName.topics || []);
- }
- throw new Error("invalid event - " + eventName);
- }
- //////////////////////////////
- // Helper Object
- function getTime() {
- return (new Date()).getTime();
- }
- function stall(duration) {
- return new Promise(function (resolve) {
- setTimeout(resolve, duration);
- });
- }
- //////////////////////////////
- // Provider Object
- /**
- * EventType
- * - "block"
- * - "poll"
- * - "didPoll"
- * - "pending"
- * - "error"
- * - "network"
- * - filter
- * - topics array
- * - transaction hash
- */
- var PollableEvents = ["block", "network", "pending", "poll"];
- var Event = /** @class */ (function () {
- function Event(tag, listener, once) {
- (0, lib$3.defineReadOnly)(this, "tag", tag);
- (0, lib$3.defineReadOnly)(this, "listener", listener);
- (0, lib$3.defineReadOnly)(this, "once", once);
- this._lastBlockNumber = -2;
- this._inflight = false;
- }
- Object.defineProperty(Event.prototype, "event", {
- get: function () {
- switch (this.type) {
- case "tx":
- return this.hash;
- case "filter":
- return this.filter;
- }
- return this.tag;
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(Event.prototype, "type", {
- get: function () {
- return this.tag.split(":")[0];
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(Event.prototype, "hash", {
- get: function () {
- var comps = this.tag.split(":");
- if (comps[0] !== "tx") {
- return null;
- }
- return comps[1];
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(Event.prototype, "filter", {
- get: function () {
- var comps = this.tag.split(":");
- if (comps[0] !== "filter") {
- return null;
- }
- var address = comps[1];
- var topics = deserializeTopics(comps[2]);
- var filter = {};
- if (topics.length > 0) {
- filter.topics = topics;
- }
- if (address && address !== "*") {
- filter.address = address;
- }
- return filter;
- },
- enumerable: false,
- configurable: true
- });
- Event.prototype.pollable = function () {
- return (this.tag.indexOf(":") >= 0 || PollableEvents.indexOf(this.tag) >= 0);
- };
- return Event;
- }());
- exports.Event = Event;
- ;
- // https://github.com/satoshilabs/slips/blob/master/slip-0044.md
- var coinInfos = {
- "0": { symbol: "btc", p2pkh: 0x00, p2sh: 0x05, prefix: "bc" },
- "2": { symbol: "ltc", p2pkh: 0x30, p2sh: 0x32, prefix: "ltc" },
- "3": { symbol: "doge", p2pkh: 0x1e, p2sh: 0x16 },
- "60": { symbol: "eth", ilk: "eth" },
- "61": { symbol: "etc", ilk: "eth" },
- "700": { symbol: "xdai", ilk: "eth" },
- };
- function bytes32ify(value) {
- return (0, lib$1.hexZeroPad)(lib$2.BigNumber.from(value).toHexString(), 32);
- }
- // Compute the Base58Check encoded data (checksum is first 4 bytes of sha256d)
- function base58Encode(data) {
- return lib$g.Base58.encode((0, lib$1.concat)([data, (0, lib$1.hexDataSlice)((0, lib$h.sha256)((0, lib$h.sha256)(data)), 0, 4)]));
- }
- var matcherIpfs = new RegExp("^(ipfs):/\/(.*)$", "i");
- var matchers = [
- new RegExp("^(https):/\/(.*)$", "i"),
- new RegExp("^(data):(.*)$", "i"),
- matcherIpfs,
- new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$", "i"),
- ];
- function _parseString(result, start) {
- try {
- return (0, lib$8.toUtf8String)(_parseBytes(result, start));
- }
- catch (error) { }
- return null;
- }
- function _parseBytes(result, start) {
- if (result === "0x") {
- return null;
- }
- var offset = lib$2.BigNumber.from((0, lib$1.hexDataSlice)(result, start, start + 32)).toNumber();
- var length = lib$2.BigNumber.from((0, lib$1.hexDataSlice)(result, offset, offset + 32)).toNumber();
- return (0, lib$1.hexDataSlice)(result, offset + 32, offset + 32 + length);
- }
- // Trim off the ipfs:// prefix and return the default gateway URL
- function getIpfsLink(link) {
- if (link.match(/^ipfs:\/\/ipfs\//i)) {
- link = link.substring(12);
- }
- else if (link.match(/^ipfs:\/\//i)) {
- link = link.substring(7);
- }
- else {
- logger.throwArgumentError("unsupported IPFS format", "link", link);
- }
- return "https://gateway.ipfs.io/ipfs/" + link;
- }
- function numPad(value) {
- var result = (0, lib$1.arrayify)(value);
- if (result.length > 32) {
- throw new Error("internal; should not happen");
- }
- var padded = new Uint8Array(32);
- padded.set(result, 32 - result.length);
- return padded;
- }
- function bytesPad(value) {
- if ((value.length % 32) === 0) {
- return value;
- }
- var result = new Uint8Array(Math.ceil(value.length / 32) * 32);
- result.set(value);
- return result;
- }
- // ABI Encodes a series of (bytes, bytes, ...)
- function encodeBytes(datas) {
- var result = [];
- var byteCount = 0;
- // Add place-holders for pointers as we add items
- for (var i = 0; i < datas.length; i++) {
- result.push(null);
- byteCount += 32;
- }
- for (var i = 0; i < datas.length; i++) {
- var data = (0, lib$1.arrayify)(datas[i]);
- // Update the bytes offset
- result[i] = numPad(byteCount);
- // The length and padded value of data
- result.push(numPad(data.length));
- result.push(bytesPad(data));
- byteCount += 32 + Math.ceil(data.length / 32) * 32;
- }
- return (0, lib$1.hexConcat)(result);
- }
- var Resolver = /** @class */ (function () {
- // The resolvedAddress is only for creating a ReverseLookup resolver
- function Resolver(provider, address, name, resolvedAddress) {
- (0, lib$3.defineReadOnly)(this, "provider", provider);
- (0, lib$3.defineReadOnly)(this, "name", name);
- (0, lib$3.defineReadOnly)(this, "address", provider.formatter.address(address));
- (0, lib$3.defineReadOnly)(this, "_resolvedAddress", resolvedAddress);
- }
- Resolver.prototype.supportsWildcard = function () {
- var _this = this;
- if (!this._supportsEip2544) {
- // supportsInterface(bytes4 = selector("resolve(bytes,bytes)"))
- this._supportsEip2544 = this.provider.call({
- to: this.address,
- data: "0x01ffc9a79061b92300000000000000000000000000000000000000000000000000000000"
- }).then(function (result) {
- return lib$2.BigNumber.from(result).eq(1);
- }).catch(function (error) {
- if (error.code === lib.Logger.errors.CALL_EXCEPTION) {
- return false;
- }
- // Rethrow the error: link is down, etc. Let future attempts retry.
- _this._supportsEip2544 = null;
- throw error;
- });
- }
- return this._supportsEip2544;
- };
- Resolver.prototype._fetch = function (selector, parameters) {
- return __awaiter(this, void 0, void 0, function () {
- var tx, parseBytes, result, error_1;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- tx = {
- to: this.address,
- ccipReadEnabled: true,
- data: (0, lib$1.hexConcat)([selector, (0, lib$9.namehash)(this.name), (parameters || "0x")])
- };
- parseBytes = false;
- return [4 /*yield*/, this.supportsWildcard()];
- case 1:
- if (_a.sent()) {
- parseBytes = true;
- // selector("resolve(bytes,bytes)")
- tx.data = (0, lib$1.hexConcat)(["0x9061b923", encodeBytes([(0, lib$9.dnsEncode)(this.name), tx.data])]);
- }
- _a.label = 2;
- case 2:
- _a.trys.push([2, 4, , 5]);
- return [4 /*yield*/, this.provider.call(tx)];
- case 3:
- result = _a.sent();
- if (((0, lib$1.arrayify)(result).length % 32) === 4) {
- logger.throwError("resolver threw error", lib.Logger.errors.CALL_EXCEPTION, {
- transaction: tx, data: result
- });
- }
- if (parseBytes) {
- result = _parseBytes(result, 0);
- }
- return [2 /*return*/, result];
- case 4:
- error_1 = _a.sent();
- if (error_1.code === lib.Logger.errors.CALL_EXCEPTION) {
- return [2 /*return*/, null];
- }
- throw error_1;
- case 5: return [2 /*return*/];
- }
- });
- });
- };
- Resolver.prototype._fetchBytes = function (selector, parameters) {
- return __awaiter(this, void 0, void 0, function () {
- var result;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, this._fetch(selector, parameters)];
- case 1:
- result = _a.sent();
- if (result != null) {
- return [2 /*return*/, _parseBytes(result, 0)];
- }
- return [2 /*return*/, null];
- }
- });
- });
- };
- Resolver.prototype._getAddress = function (coinType, hexBytes) {
- var coinInfo = coinInfos[String(coinType)];
- if (coinInfo == null) {
- logger.throwError("unsupported coin type: " + coinType, lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "getAddress(" + coinType + ")"
- });
- }
- if (coinInfo.ilk === "eth") {
- return this.provider.formatter.address(hexBytes);
- }
- var bytes = (0, lib$1.arrayify)(hexBytes);
- // P2PKH: OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
- if (coinInfo.p2pkh != null) {
- var p2pkh = hexBytes.match(/^0x76a9([0-9a-f][0-9a-f])([0-9a-f]*)88ac$/);
- if (p2pkh) {
- var length_1 = parseInt(p2pkh[1], 16);
- if (p2pkh[2].length === length_1 * 2 && length_1 >= 1 && length_1 <= 75) {
- return base58Encode((0, lib$1.concat)([[coinInfo.p2pkh], ("0x" + p2pkh[2])]));
- }
- }
- }
- // P2SH: OP_HASH160 <scriptHash> OP_EQUAL
- if (coinInfo.p2sh != null) {
- var p2sh = hexBytes.match(/^0xa9([0-9a-f][0-9a-f])([0-9a-f]*)87$/);
- if (p2sh) {
- var length_2 = parseInt(p2sh[1], 16);
- if (p2sh[2].length === length_2 * 2 && length_2 >= 1 && length_2 <= 75) {
- return base58Encode((0, lib$1.concat)([[coinInfo.p2sh], ("0x" + p2sh[2])]));
- }
- }
- }
- // Bech32
- if (coinInfo.prefix != null) {
- var length_3 = bytes[1];
- // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#witness-program
- var version_1 = bytes[0];
- if (version_1 === 0x00) {
- if (length_3 !== 20 && length_3 !== 32) {
- version_1 = -1;
- }
- }
- else {
- version_1 = -1;
- }
- if (version_1 >= 0 && bytes.length === 2 + length_3 && length_3 >= 1 && length_3 <= 75) {
- var words = bech32_1.default.toWords(bytes.slice(2));
- words.unshift(version_1);
- return bech32_1.default.encode(coinInfo.prefix, words);
- }
- }
- return null;
- };
- Resolver.prototype.getAddress = function (coinType) {
- return __awaiter(this, void 0, void 0, function () {
- var result, error_2, hexBytes, address;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (coinType == null) {
- coinType = 60;
- }
- if (!(coinType === 60)) return [3 /*break*/, 4];
- _a.label = 1;
- case 1:
- _a.trys.push([1, 3, , 4]);
- return [4 /*yield*/, this._fetch("0x3b3b57de")];
- case 2:
- result = _a.sent();
- // No address
- if (result === "0x" || result === lib$7.HashZero) {
- return [2 /*return*/, null];
- }
- return [2 /*return*/, this.provider.formatter.callAddress(result)];
- case 3:
- error_2 = _a.sent();
- if (error_2.code === lib.Logger.errors.CALL_EXCEPTION) {
- return [2 /*return*/, null];
- }
- throw error_2;
- case 4: return [4 /*yield*/, this._fetchBytes("0xf1cb7e06", bytes32ify(coinType))];
- case 5:
- hexBytes = _a.sent();
- // No address
- if (hexBytes == null || hexBytes === "0x") {
- return [2 /*return*/, null];
- }
- address = this._getAddress(coinType, hexBytes);
- if (address == null) {
- logger.throwError("invalid or unsupported coin data", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "getAddress(" + coinType + ")",
- coinType: coinType,
- data: hexBytes
- });
- }
- return [2 /*return*/, address];
- }
- });
- });
- };
- Resolver.prototype.getAvatar = function () {
- return __awaiter(this, void 0, void 0, function () {
- var linkage, avatar, i, match, scheme, _a, selector, owner, _b, comps, addr, tokenId, tokenOwner, _c, _d, balance, _e, _f, tx, metadataUrl, _g, metadata, imageUrl, ipfs, error_3;
- return __generator(this, function (_h) {
- switch (_h.label) {
- case 0:
- linkage = [{ type: "name", content: this.name }];
- _h.label = 1;
- case 1:
- _h.trys.push([1, 19, , 20]);
- return [4 /*yield*/, this.getText("avatar")];
- case 2:
- avatar = _h.sent();
- if (avatar == null) {
- return [2 /*return*/, null];
- }
- i = 0;
- _h.label = 3;
- case 3:
- if (!(i < matchers.length)) return [3 /*break*/, 18];
- match = avatar.match(matchers[i]);
- if (match == null) {
- return [3 /*break*/, 17];
- }
- scheme = match[1].toLowerCase();
- _a = scheme;
- switch (_a) {
- case "https": return [3 /*break*/, 4];
- case "data": return [3 /*break*/, 5];
- case "ipfs": return [3 /*break*/, 6];
- case "erc721": return [3 /*break*/, 7];
- case "erc1155": return [3 /*break*/, 7];
- }
- return [3 /*break*/, 17];
- case 4:
- linkage.push({ type: "url", content: avatar });
- return [2 /*return*/, { linkage: linkage, url: avatar }];
- case 5:
- linkage.push({ type: "data", content: avatar });
- return [2 /*return*/, { linkage: linkage, url: avatar }];
- case 6:
- linkage.push({ type: "ipfs", content: avatar });
- return [2 /*return*/, { linkage: linkage, url: getIpfsLink(avatar) }];
- case 7:
- selector = (scheme === "erc721") ? "0xc87b56dd" : "0x0e89341c";
- linkage.push({ type: scheme, content: avatar });
- _b = this._resolvedAddress;
- if (_b) return [3 /*break*/, 9];
- return [4 /*yield*/, this.getAddress()];
- case 8:
- _b = (_h.sent());
- _h.label = 9;
- case 9:
- owner = (_b);
- comps = (match[2] || "").split("/");
- if (comps.length !== 2) {
- return [2 /*return*/, null];
- }
- return [4 /*yield*/, this.provider.formatter.address(comps[0])];
- case 10:
- addr = _h.sent();
- tokenId = (0, lib$1.hexZeroPad)(lib$2.BigNumber.from(comps[1]).toHexString(), 32);
- if (!(scheme === "erc721")) return [3 /*break*/, 12];
- _d = (_c = this.provider.formatter).callAddress;
- return [4 /*yield*/, this.provider.call({
- to: addr, data: (0, lib$1.hexConcat)(["0x6352211e", tokenId])
- })];
- case 11:
- tokenOwner = _d.apply(_c, [_h.sent()]);
- if (owner !== tokenOwner) {
- return [2 /*return*/, null];
- }
- linkage.push({ type: "owner", content: tokenOwner });
- return [3 /*break*/, 14];
- case 12:
- if (!(scheme === "erc1155")) return [3 /*break*/, 14];
- _f = (_e = lib$2.BigNumber).from;
- return [4 /*yield*/, this.provider.call({
- to: addr, data: (0, lib$1.hexConcat)(["0x00fdd58e", (0, lib$1.hexZeroPad)(owner, 32), tokenId])
- })];
- case 13:
- balance = _f.apply(_e, [_h.sent()]);
- if (balance.isZero()) {
- return [2 /*return*/, null];
- }
- linkage.push({ type: "balance", content: balance.toString() });
- _h.label = 14;
- case 14:
- tx = {
- to: this.provider.formatter.address(comps[0]),
- data: (0, lib$1.hexConcat)([selector, tokenId])
- };
- _g = _parseString;
- return [4 /*yield*/, this.provider.call(tx)];
- case 15:
- metadataUrl = _g.apply(void 0, [_h.sent(), 0]);
- if (metadataUrl == null) {
- return [2 /*return*/, null];
- }
- linkage.push({ type: "metadata-url-base", content: metadataUrl });
- // ERC-1155 allows a generic {id} in the URL
- if (scheme === "erc1155") {
- metadataUrl = metadataUrl.replace("{id}", tokenId.substring(2));
- linkage.push({ type: "metadata-url-expanded", content: metadataUrl });
- }
- // Transform IPFS metadata links
- if (metadataUrl.match(/^ipfs:/i)) {
- metadataUrl = getIpfsLink(metadataUrl);
- }
- linkage.push({ type: "metadata-url", content: metadataUrl });
- return [4 /*yield*/, (0, lib$q.fetchJson)(metadataUrl)];
- case 16:
- metadata = _h.sent();
- if (!metadata) {
- return [2 /*return*/, null];
- }
- linkage.push({ type: "metadata", content: JSON.stringify(metadata) });
- imageUrl = metadata.image;
- if (typeof (imageUrl) !== "string") {
- return [2 /*return*/, null];
- }
- if (imageUrl.match(/^(https:\/\/|data:)/i)) {
- // Allow
- }
- else {
- ipfs = imageUrl.match(matcherIpfs);
- if (ipfs == null) {
- return [2 /*return*/, null];
- }
- linkage.push({ type: "url-ipfs", content: imageUrl });
- imageUrl = getIpfsLink(imageUrl);
- }
- linkage.push({ type: "url", content: imageUrl });
- return [2 /*return*/, { linkage: linkage, url: imageUrl }];
- case 17:
- i++;
- return [3 /*break*/, 3];
- case 18: return [3 /*break*/, 20];
- case 19:
- error_3 = _h.sent();
- return [3 /*break*/, 20];
- case 20: return [2 /*return*/, null];
- }
- });
- });
- };
- Resolver.prototype.getContentHash = function () {
- return __awaiter(this, void 0, void 0, function () {
- var hexBytes, ipfs, length_4, swarm;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, this._fetchBytes("0xbc1c58d1")];
- case 1:
- hexBytes = _a.sent();
- // No contenthash
- if (hexBytes == null || hexBytes === "0x") {
- return [2 /*return*/, null];
- }
- ipfs = hexBytes.match(/^0xe3010170(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);
- if (ipfs) {
- length_4 = parseInt(ipfs[3], 16);
- if (ipfs[4].length === length_4 * 2) {
- return [2 /*return*/, "ipfs:/\/" + lib$g.Base58.encode("0x" + ipfs[1])];
- }
- }
- swarm = hexBytes.match(/^0xe40101fa011b20([0-9a-f]*)$/);
- if (swarm) {
- if (swarm[1].length === (32 * 2)) {
- return [2 /*return*/, "bzz:/\/" + swarm[1]];
- }
- }
- return [2 /*return*/, logger.throwError("invalid or unsupported content hash data", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "getContentHash()",
- data: hexBytes
- })];
- }
- });
- });
- };
- Resolver.prototype.getText = function (key) {
- return __awaiter(this, void 0, void 0, function () {
- var keyBytes, hexBytes;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- keyBytes = (0, lib$8.toUtf8Bytes)(key);
- // The nodehash consumes the first slot, so the string pointer targets
- // offset 64, with the length at offset 64 and data starting at offset 96
- keyBytes = (0, lib$1.concat)([bytes32ify(64), bytes32ify(keyBytes.length), keyBytes]);
- // Pad to word-size (32 bytes)
- if ((keyBytes.length % 32) !== 0) {
- keyBytes = (0, lib$1.concat)([keyBytes, (0, lib$1.hexZeroPad)("0x", 32 - (key.length % 32))]);
- }
- return [4 /*yield*/, this._fetchBytes("0x59d1d43c", (0, lib$1.hexlify)(keyBytes))];
- case 1:
- hexBytes = _a.sent();
- if (hexBytes == null || hexBytes === "0x") {
- return [2 /*return*/, null];
- }
- return [2 /*return*/, (0, lib$8.toUtf8String)(hexBytes)];
- }
- });
- });
- };
- return Resolver;
- }());
- exports.Resolver = Resolver;
- var defaultFormatter = null;
- var nextPollId = 1;
- var BaseProvider = /** @class */ (function (_super) {
- __extends(BaseProvider, _super);
- /**
- * ready
- *
- * A Promise<Network> that resolves only once the provider is ready.
- *
- * Sub-classes that call the super with a network without a chainId
- * MUST set this. Standard named networks have a known chainId.
- *
- */
- function BaseProvider(network) {
- var _newTarget = this.constructor;
- var _this = this;
- logger.checkNew(_newTarget, lib$b.Provider);
- _this = _super.call(this) || this;
- // Events being listened to
- _this._events = [];
- _this._emitted = { block: -2 };
- _this.disableCcipRead = false;
- _this.formatter = _newTarget.getFormatter();
- // If network is any, this Provider allows the underlying
- // network to change dynamically, and we auto-detect the
- // current network
- (0, lib$3.defineReadOnly)(_this, "anyNetwork", (network === "any"));
- if (_this.anyNetwork) {
- network = _this.detectNetwork();
- }
- if (network instanceof Promise) {
- _this._networkPromise = network;
- // Squash any "unhandled promise" errors; that do not need to be handled
- network.catch(function (error) { });
- // Trigger initial network setting (async)
- _this._ready().catch(function (error) { });
- }
- else {
- var knownNetwork = (0, lib$3.getStatic)(_newTarget, "getNetwork")(network);
- if (knownNetwork) {
- (0, lib$3.defineReadOnly)(_this, "_network", knownNetwork);
- _this.emit("network", knownNetwork, null);
- }
- else {
- logger.throwArgumentError("invalid network", "network", network);
- }
- }
- _this._maxInternalBlockNumber = -1024;
- _this._lastBlockNumber = -2;
- _this._maxFilterBlockRange = 10;
- _this._pollingInterval = 4000;
- _this._fastQueryDate = 0;
- return _this;
- }
- BaseProvider.prototype._ready = function () {
- return __awaiter(this, void 0, void 0, function () {
- var network, error_4;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (!(this._network == null)) return [3 /*break*/, 7];
- network = null;
- if (!this._networkPromise) return [3 /*break*/, 4];
- _a.label = 1;
- case 1:
- _a.trys.push([1, 3, , 4]);
- return [4 /*yield*/, this._networkPromise];
- case 2:
- network = _a.sent();
- return [3 /*break*/, 4];
- case 3:
- error_4 = _a.sent();
- return [3 /*break*/, 4];
- case 4:
- if (!(network == null)) return [3 /*break*/, 6];
- return [4 /*yield*/, this.detectNetwork()];
- case 5:
- network = _a.sent();
- _a.label = 6;
- case 6:
- // This should never happen; every Provider sub-class should have
- // suggested a network by here (or have thrown).
- if (!network) {
- logger.throwError("no network detected", lib.Logger.errors.UNKNOWN_ERROR, {});
- }
- // Possible this call stacked so do not call defineReadOnly again
- if (this._network == null) {
- if (this.anyNetwork) {
- this._network = network;
- }
- else {
- (0, lib$3.defineReadOnly)(this, "_network", network);
- }
- this.emit("network", network, null);
- }
- _a.label = 7;
- case 7: return [2 /*return*/, this._network];
- }
- });
- });
- };
- Object.defineProperty(BaseProvider.prototype, "ready", {
- // This will always return the most recently established network.
- // For "any", this can change (a "network" event is emitted before
- // any change is reflected); otherwise this cannot change
- get: function () {
- var _this = this;
- return (0, lib$q.poll)(function () {
- return _this._ready().then(function (network) {
- return network;
- }, function (error) {
- // If the network isn't running yet, we will wait
- if (error.code === lib.Logger.errors.NETWORK_ERROR && error.event === "noNetwork") {
- return undefined;
- }
- throw error;
- });
- });
- },
- enumerable: false,
- configurable: true
- });
- // @TODO: Remove this and just create a singleton formatter
- BaseProvider.getFormatter = function () {
- if (defaultFormatter == null) {
- defaultFormatter = new formatter.Formatter();
- }
- return defaultFormatter;
- };
- // @TODO: Remove this and just use getNetwork
- BaseProvider.getNetwork = function (network) {
- return (0, lib$o.getNetwork)((network == null) ? "homestead" : network);
- };
- BaseProvider.prototype.ccipReadFetch = function (tx, calldata, urls) {
- return __awaiter(this, void 0, void 0, function () {
- var sender, data, errorMessages, i, url, href, json, result, errorMessage;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (this.disableCcipRead || urls.length === 0) {
- return [2 /*return*/, null];
- }
- sender = (tx.from || "0x0000000000000000000000000000000000000000").toLowerCase();
- data = calldata.toLowerCase();
- errorMessages = [];
- i = 0;
- _a.label = 1;
- case 1:
- if (!(i < urls.length)) return [3 /*break*/, 4];
- url = urls[i];
- href = url.replace("{sender}", sender).replace("{data}", data);
- json = (url.indexOf("{data}") >= 0) ? null : JSON.stringify({ data: data, sender: sender });
- return [4 /*yield*/, (0, lib$q.fetchJson)({ url: href, errorPassThrough: true }, json, function (value, response) {
- value.status = response.statusCode;
- return value;
- })];
- case 2:
- result = _a.sent();
- if (result.data) {
- return [2 /*return*/, result.data];
- }
- errorMessage = (result.message || "unknown error");
- // 4xx indicates the result is not present; stop
- if (result.status >= 400 && result.status < 500) {
- return [2 /*return*/, logger.throwError("response not found during CCIP fetch: " + errorMessage, lib.Logger.errors.SERVER_ERROR, { url: url, errorMessage: errorMessage })];
- }
- // 5xx indicates server issue; try the next url
- errorMessages.push(errorMessage);
- _a.label = 3;
- case 3:
- i++;
- return [3 /*break*/, 1];
- case 4: return [2 /*return*/, logger.throwError("error encountered during CCIP fetch: " + errorMessages.map(function (m) { return JSON.stringify(m); }).join(", "), lib.Logger.errors.SERVER_ERROR, {
- urls: urls,
- errorMessages: errorMessages
- })];
- }
- });
- });
- };
- // Fetches the blockNumber, but will reuse any result that is less
- // than maxAge old or has been requested since the last request
- BaseProvider.prototype._getInternalBlockNumber = function (maxAge) {
- return __awaiter(this, void 0, void 0, function () {
- var internalBlockNumber, result, error_5, reqTime, checkInternalBlockNumber;
- var _this = this;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, this._ready()];
- case 1:
- _a.sent();
- if (!(maxAge > 0)) return [3 /*break*/, 7];
- _a.label = 2;
- case 2:
- if (!this._internalBlockNumber) return [3 /*break*/, 7];
- internalBlockNumber = this._internalBlockNumber;
- _a.label = 3;
- case 3:
- _a.trys.push([3, 5, , 6]);
- return [4 /*yield*/, internalBlockNumber];
- case 4:
- result = _a.sent();
- if ((getTime() - result.respTime) <= maxAge) {
- return [2 /*return*/, result.blockNumber];
- }
- // Too old; fetch a new value
- return [3 /*break*/, 7];
- case 5:
- error_5 = _a.sent();
- // The fetch rejected; if we are the first to get the
- // rejection, drop through so we replace it with a new
- // fetch; all others blocked will then get that fetch
- // which won't match the one they "remembered" and loop
- if (this._internalBlockNumber === internalBlockNumber) {
- return [3 /*break*/, 7];
- }
- return [3 /*break*/, 6];
- case 6: return [3 /*break*/, 2];
- case 7:
- reqTime = getTime();
- checkInternalBlockNumber = (0, lib$3.resolveProperties)({
- blockNumber: this.perform("getBlockNumber", {}),
- networkError: this.getNetwork().then(function (network) { return (null); }, function (error) { return (error); })
- }).then(function (_a) {
- var blockNumber = _a.blockNumber, networkError = _a.networkError;
- if (networkError) {
- // Unremember this bad internal block number
- if (_this._internalBlockNumber === checkInternalBlockNumber) {
- _this._internalBlockNumber = null;
- }
- throw networkError;
- }
- var respTime = getTime();
- blockNumber = lib$2.BigNumber.from(blockNumber).toNumber();
- if (blockNumber < _this._maxInternalBlockNumber) {
- blockNumber = _this._maxInternalBlockNumber;
- }
- _this._maxInternalBlockNumber = blockNumber;
- _this._setFastBlockNumber(blockNumber); // @TODO: Still need this?
- return { blockNumber: blockNumber, reqTime: reqTime, respTime: respTime };
- });
- this._internalBlockNumber = checkInternalBlockNumber;
- // Swallow unhandled exceptions; if needed they are handled else where
- checkInternalBlockNumber.catch(function (error) {
- // Don't null the dead (rejected) fetch, if it has already been updated
- if (_this._internalBlockNumber === checkInternalBlockNumber) {
- _this._internalBlockNumber = null;
- }
- });
- return [4 /*yield*/, checkInternalBlockNumber];
- case 8: return [2 /*return*/, (_a.sent()).blockNumber];
- }
- });
- });
- };
- BaseProvider.prototype.poll = function () {
- return __awaiter(this, void 0, void 0, function () {
- var pollId, runners, blockNumber, error_6, i;
- var _this = this;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- pollId = nextPollId++;
- runners = [];
- blockNumber = null;
- _a.label = 1;
- case 1:
- _a.trys.push([1, 3, , 4]);
- return [4 /*yield*/, this._getInternalBlockNumber(100 + this.pollingInterval / 2)];
- case 2:
- blockNumber = _a.sent();
- return [3 /*break*/, 4];
- case 3:
- error_6 = _a.sent();
- this.emit("error", error_6);
- return [2 /*return*/];
- case 4:
- this._setFastBlockNumber(blockNumber);
- // Emit a poll event after we have the latest (fast) block number
- this.emit("poll", pollId, blockNumber);
- // If the block has not changed, meh.
- if (blockNumber === this._lastBlockNumber) {
- this.emit("didPoll", pollId);
- return [2 /*return*/];
- }
- // First polling cycle, trigger a "block" events
- if (this._emitted.block === -2) {
- this._emitted.block = blockNumber - 1;
- }
- if (Math.abs((this._emitted.block) - blockNumber) > 1000) {
- logger.warn("network block skew detected; skipping block events (emitted=" + this._emitted.block + " blockNumber" + blockNumber + ")");
- this.emit("error", logger.makeError("network block skew detected", lib.Logger.errors.NETWORK_ERROR, {
- blockNumber: blockNumber,
- event: "blockSkew",
- previousBlockNumber: this._emitted.block
- }));
- this.emit("block", blockNumber);
- }
- else {
- // Notify all listener for each block that has passed
- for (i = this._emitted.block + 1; i <= blockNumber; i++) {
- this.emit("block", i);
- }
- }
- // The emitted block was updated, check for obsolete events
- if (this._emitted.block !== blockNumber) {
- this._emitted.block = blockNumber;
- Object.keys(this._emitted).forEach(function (key) {
- // The block event does not expire
- if (key === "block") {
- return;
- }
- // The block we were at when we emitted this event
- var eventBlockNumber = _this._emitted[key];
- // We cannot garbage collect pending transactions or blocks here
- // They should be garbage collected by the Provider when setting
- // "pending" events
- if (eventBlockNumber === "pending") {
- return;
- }
- // Evict any transaction hashes or block hashes over 12 blocks
- // old, since they should not return null anyways
- if (blockNumber - eventBlockNumber > 12) {
- delete _this._emitted[key];
- }
- });
- }
- // First polling cycle
- if (this._lastBlockNumber === -2) {
- this._lastBlockNumber = blockNumber - 1;
- }
- // Find all transaction hashes we are waiting on
- this._events.forEach(function (event) {
- switch (event.type) {
- case "tx": {
- var hash_2 = event.hash;
- var runner = _this.getTransactionReceipt(hash_2).then(function (receipt) {
- if (!receipt || receipt.blockNumber == null) {
- return null;
- }
- _this._emitted["t:" + hash_2] = receipt.blockNumber;
- _this.emit(hash_2, receipt);
- return null;
- }).catch(function (error) { _this.emit("error", error); });
- runners.push(runner);
- break;
- }
- case "filter": {
- // We only allow a single getLogs to be in-flight at a time
- if (!event._inflight) {
- event._inflight = true;
- // Filter from the last known event; due to load-balancing
- // and some nodes returning updated block numbers before
- // indexing events, a logs result with 0 entries cannot be
- // trusted and we must retry a range which includes it again
- var filter_1 = event.filter;
- filter_1.fromBlock = event._lastBlockNumber + 1;
- filter_1.toBlock = blockNumber;
- // Prevent fitler ranges from growing too wild
- if (filter_1.toBlock - _this._maxFilterBlockRange > filter_1.fromBlock) {
- filter_1.fromBlock = filter_1.toBlock - _this._maxFilterBlockRange;
- }
- var runner = _this.getLogs(filter_1).then(function (logs) {
- // Allow the next getLogs
- event._inflight = false;
- if (logs.length === 0) {
- return;
- }
- logs.forEach(function (log) {
- // Only when we get an event for a given block number
- // can we trust the events are indexed
- if (log.blockNumber > event._lastBlockNumber) {
- event._lastBlockNumber = log.blockNumber;
- }
- // Make sure we stall requests to fetch blocks and txs
- _this._emitted["b:" + log.blockHash] = log.blockNumber;
- _this._emitted["t:" + log.transactionHash] = log.blockNumber;
- _this.emit(filter_1, log);
- });
- }).catch(function (error) {
- _this.emit("error", error);
- // Allow another getLogs (the range was not updated)
- event._inflight = false;
- });
- runners.push(runner);
- }
- break;
- }
- }
- });
- this._lastBlockNumber = blockNumber;
- // Once all events for this loop have been processed, emit "didPoll"
- Promise.all(runners).then(function () {
- _this.emit("didPoll", pollId);
- }).catch(function (error) { _this.emit("error", error); });
- return [2 /*return*/];
- }
- });
- });
- };
- // Deprecated; do not use this
- BaseProvider.prototype.resetEventsBlock = function (blockNumber) {
- this._lastBlockNumber = blockNumber - 1;
- if (this.polling) {
- this.poll();
- }
- };
- Object.defineProperty(BaseProvider.prototype, "network", {
- get: function () {
- return this._network;
- },
- enumerable: false,
- configurable: true
- });
- // This method should query the network if the underlying network
- // can change, such as when connected to a JSON-RPC backend
- BaseProvider.prototype.detectNetwork = function () {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- return [2 /*return*/, logger.throwError("provider does not support network detection", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "provider.detectNetwork"
- })];
- });
- });
- };
- BaseProvider.prototype.getNetwork = function () {
- return __awaiter(this, void 0, void 0, function () {
- var network, currentNetwork, error;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, this._ready()];
- case 1:
- network = _a.sent();
- return [4 /*yield*/, this.detectNetwork()];
- case 2:
- currentNetwork = _a.sent();
- if (!(network.chainId !== currentNetwork.chainId)) return [3 /*break*/, 5];
- if (!this.anyNetwork) return [3 /*break*/, 4];
- this._network = currentNetwork;
- // Reset all internal block number guards and caches
- this._lastBlockNumber = -2;
- this._fastBlockNumber = null;
- this._fastBlockNumberPromise = null;
- this._fastQueryDate = 0;
- this._emitted.block = -2;
- this._maxInternalBlockNumber = -1024;
- this._internalBlockNumber = null;
- // The "network" event MUST happen before this method resolves
- // so any events have a chance to unregister, so we stall an
- // additional event loop before returning from /this/ call
- this.emit("network", currentNetwork, network);
- return [4 /*yield*/, stall(0)];
- case 3:
- _a.sent();
- return [2 /*return*/, this._network];
- case 4:
- error = logger.makeError("underlying network changed", lib.Logger.errors.NETWORK_ERROR, {
- event: "changed",
- network: network,
- detectedNetwork: currentNetwork
- });
- this.emit("error", error);
- throw error;
- case 5: return [2 /*return*/, network];
- }
- });
- });
- };
- Object.defineProperty(BaseProvider.prototype, "blockNumber", {
- get: function () {
- var _this = this;
- this._getInternalBlockNumber(100 + this.pollingInterval / 2).then(function (blockNumber) {
- _this._setFastBlockNumber(blockNumber);
- }, function (error) { });
- return (this._fastBlockNumber != null) ? this._fastBlockNumber : -1;
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(BaseProvider.prototype, "polling", {
- get: function () {
- return (this._poller != null);
- },
- set: function (value) {
- var _this = this;
- if (value && !this._poller) {
- this._poller = setInterval(function () { _this.poll(); }, this.pollingInterval);
- if (!this._bootstrapPoll) {
- this._bootstrapPoll = setTimeout(function () {
- _this.poll();
- // We block additional polls until the polling interval
- // is done, to prevent overwhelming the poll function
- _this._bootstrapPoll = setTimeout(function () {
- // If polling was disabled, something may require a poke
- // since starting the bootstrap poll and it was disabled
- if (!_this._poller) {
- _this.poll();
- }
- // Clear out the bootstrap so we can do another
- _this._bootstrapPoll = null;
- }, _this.pollingInterval);
- }, 0);
- }
- }
- else if (!value && this._poller) {
- clearInterval(this._poller);
- this._poller = null;
- }
- },
- enumerable: false,
- configurable: true
- });
- Object.defineProperty(BaseProvider.prototype, "pollingInterval", {
- get: function () {
- return this._pollingInterval;
- },
- set: function (value) {
- var _this = this;
- if (typeof (value) !== "number" || value <= 0 || parseInt(String(value)) != value) {
- throw new Error("invalid polling interval");
- }
- this._pollingInterval = value;
- if (this._poller) {
- clearInterval(this._poller);
- this._poller = setInterval(function () { _this.poll(); }, this._pollingInterval);
- }
- },
- enumerable: false,
- configurable: true
- });
- BaseProvider.prototype._getFastBlockNumber = function () {
- var _this = this;
- var now = getTime();
- // Stale block number, request a newer value
- if ((now - this._fastQueryDate) > 2 * this._pollingInterval) {
- this._fastQueryDate = now;
- this._fastBlockNumberPromise = this.getBlockNumber().then(function (blockNumber) {
- if (_this._fastBlockNumber == null || blockNumber > _this._fastBlockNumber) {
- _this._fastBlockNumber = blockNumber;
- }
- return _this._fastBlockNumber;
- });
- }
- return this._fastBlockNumberPromise;
- };
- BaseProvider.prototype._setFastBlockNumber = function (blockNumber) {
- // Older block, maybe a stale request
- if (this._fastBlockNumber != null && blockNumber < this._fastBlockNumber) {
- return;
- }
- // Update the time we updated the blocknumber
- this._fastQueryDate = getTime();
- // Newer block number, use it
- if (this._fastBlockNumber == null || blockNumber > this._fastBlockNumber) {
- this._fastBlockNumber = blockNumber;
- this._fastBlockNumberPromise = Promise.resolve(blockNumber);
- }
- };
- BaseProvider.prototype.waitForTransaction = function (transactionHash, confirmations, timeout) {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- return [2 /*return*/, this._waitForTransaction(transactionHash, (confirmations == null) ? 1 : confirmations, timeout || 0, null)];
- });
- });
- };
- BaseProvider.prototype._waitForTransaction = function (transactionHash, confirmations, timeout, replaceable) {
- return __awaiter(this, void 0, void 0, function () {
- var receipt;
- var _this = this;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, this.getTransactionReceipt(transactionHash)];
- case 1:
- receipt = _a.sent();
- // Receipt is already good
- if ((receipt ? receipt.confirmations : 0) >= confirmations) {
- return [2 /*return*/, receipt];
- }
- // Poll until the receipt is good...
- return [2 /*return*/, new Promise(function (resolve, reject) {
- var cancelFuncs = [];
- var done = false;
- var alreadyDone = function () {
- if (done) {
- return true;
- }
- done = true;
- cancelFuncs.forEach(function (func) { func(); });
- return false;
- };
- var minedHandler = function (receipt) {
- if (receipt.confirmations < confirmations) {
- return;
- }
- if (alreadyDone()) {
- return;
- }
- resolve(receipt);
- };
- _this.on(transactionHash, minedHandler);
- cancelFuncs.push(function () { _this.removeListener(transactionHash, minedHandler); });
- if (replaceable) {
- var lastBlockNumber_1 = replaceable.startBlock;
- var scannedBlock_1 = null;
- var replaceHandler_1 = function (blockNumber) { return __awaiter(_this, void 0, void 0, function () {
- var _this = this;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (done) {
- return [2 /*return*/];
- }
- // Wait 1 second; this is only used in the case of a fault, so
- // we will trade off a little bit of latency for more consistent
- // results and fewer JSON-RPC calls
- return [4 /*yield*/, stall(1000)];
- case 1:
- // Wait 1 second; this is only used in the case of a fault, so
- // we will trade off a little bit of latency for more consistent
- // results and fewer JSON-RPC calls
- _a.sent();
- this.getTransactionCount(replaceable.from).then(function (nonce) { return __awaiter(_this, void 0, void 0, function () {
- var mined, block, ti, tx, receipt_1, reason;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (done) {
- return [2 /*return*/];
- }
- if (!(nonce <= replaceable.nonce)) return [3 /*break*/, 1];
- lastBlockNumber_1 = blockNumber;
- return [3 /*break*/, 9];
- case 1: return [4 /*yield*/, this.getTransaction(transactionHash)];
- case 2:
- mined = _a.sent();
- if (mined && mined.blockNumber != null) {
- return [2 /*return*/];
- }
- // First time scanning. We start a little earlier for some
- // wiggle room here to handle the eventually consistent nature
- // of blockchain (e.g. the getTransactionCount was for a
- // different block)
- if (scannedBlock_1 == null) {
- scannedBlock_1 = lastBlockNumber_1 - 3;
- if (scannedBlock_1 < replaceable.startBlock) {
- scannedBlock_1 = replaceable.startBlock;
- }
- }
- _a.label = 3;
- case 3:
- if (!(scannedBlock_1 <= blockNumber)) return [3 /*break*/, 9];
- if (done) {
- return [2 /*return*/];
- }
- return [4 /*yield*/, this.getBlockWithTransactions(scannedBlock_1)];
- case 4:
- block = _a.sent();
- ti = 0;
- _a.label = 5;
- case 5:
- if (!(ti < block.transactions.length)) return [3 /*break*/, 8];
- tx = block.transactions[ti];
- // Successfully mined!
- if (tx.hash === transactionHash) {
- return [2 /*return*/];
- }
- if (!(tx.from === replaceable.from && tx.nonce === replaceable.nonce)) return [3 /*break*/, 7];
- if (done) {
- return [2 /*return*/];
- }
- return [4 /*yield*/, this.waitForTransaction(tx.hash, confirmations)];
- case 6:
- receipt_1 = _a.sent();
- // Already resolved or rejected (prolly a timeout)
- if (alreadyDone()) {
- return [2 /*return*/];
- }
- reason = "replaced";
- if (tx.data === replaceable.data && tx.to === replaceable.to && tx.value.eq(replaceable.value)) {
- reason = "repriced";
- }
- else if (tx.data === "0x" && tx.from === tx.to && tx.value.isZero()) {
- reason = "cancelled";
- }
- // Explain why we were replaced
- reject(logger.makeError("transaction was replaced", lib.Logger.errors.TRANSACTION_REPLACED, {
- cancelled: (reason === "replaced" || reason === "cancelled"),
- reason: reason,
- replacement: this._wrapTransaction(tx),
- hash: transactionHash,
- receipt: receipt_1
- }));
- return [2 /*return*/];
- case 7:
- ti++;
- return [3 /*break*/, 5];
- case 8:
- scannedBlock_1++;
- return [3 /*break*/, 3];
- case 9:
- if (done) {
- return [2 /*return*/];
- }
- this.once("block", replaceHandler_1);
- return [2 /*return*/];
- }
- });
- }); }, function (error) {
- if (done) {
- return;
- }
- _this.once("block", replaceHandler_1);
- });
- return [2 /*return*/];
- }
- });
- }); };
- if (done) {
- return;
- }
- _this.once("block", replaceHandler_1);
- cancelFuncs.push(function () {
- _this.removeListener("block", replaceHandler_1);
- });
- }
- if (typeof (timeout) === "number" && timeout > 0) {
- var timer_1 = setTimeout(function () {
- if (alreadyDone()) {
- return;
- }
- reject(logger.makeError("timeout exceeded", lib.Logger.errors.TIMEOUT, { timeout: timeout }));
- }, timeout);
- if (timer_1.unref) {
- timer_1.unref();
- }
- cancelFuncs.push(function () { clearTimeout(timer_1); });
- }
- })];
- }
- });
- });
- };
- BaseProvider.prototype.getBlockNumber = function () {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- return [2 /*return*/, this._getInternalBlockNumber(0)];
- });
- });
- };
- BaseProvider.prototype.getGasPrice = function () {
- return __awaiter(this, void 0, void 0, function () {
- var result;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, this.getNetwork()];
- case 1:
- _a.sent();
- return [4 /*yield*/, this.perform("getGasPrice", {})];
- case 2:
- result = _a.sent();
- try {
- return [2 /*return*/, lib$2.BigNumber.from(result)];
- }
- catch (error) {
- return [2 /*return*/, logger.throwError("bad result from backend", lib.Logger.errors.SERVER_ERROR, {
- method: "getGasPrice",
- result: result,
- error: error
- })];
- }
- return [2 /*return*/];
- }
- });
- });
- };
- BaseProvider.prototype.getBalance = function (addressOrName, blockTag) {
- return __awaiter(this, void 0, void 0, function () {
- var params, result;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, this.getNetwork()];
- case 1:
- _a.sent();
- return [4 /*yield*/, (0, lib$3.resolveProperties)({
- address: this._getAddress(addressOrName),
- blockTag: this._getBlockTag(blockTag)
- })];
- case 2:
- params = _a.sent();
- return [4 /*yield*/, this.perform("getBalance", params)];
- case 3:
- result = _a.sent();
- try {
- return [2 /*return*/, lib$2.BigNumber.from(result)];
- }
- catch (error) {
- return [2 /*return*/, logger.throwError("bad result from backend", lib.Logger.errors.SERVER_ERROR, {
- method: "getBalance",
- params: params,
- result: result,
- error: error
- })];
- }
- return [2 /*return*/];
- }
- });
- });
- };
- BaseProvider.prototype.getTransactionCount = function (addressOrName, blockTag) {
- return __awaiter(this, void 0, void 0, function () {
- var params, result;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, this.getNetwork()];
- case 1:
- _a.sent();
- return [4 /*yield*/, (0, lib$3.resolveProperties)({
- address: this._getAddress(addressOrName),
- blockTag: this._getBlockTag(blockTag)
- })];
- case 2:
- params = _a.sent();
- return [4 /*yield*/, this.perform("getTransactionCount", params)];
- case 3:
- result = _a.sent();
- try {
- return [2 /*return*/, lib$2.BigNumber.from(result).toNumber()];
- }
- catch (error) {
- return [2 /*return*/, logger.throwError("bad result from backend", lib.Logger.errors.SERVER_ERROR, {
- method: "getTransactionCount",
- params: params,
- result: result,
- error: error
- })];
- }
- return [2 /*return*/];
- }
- });
- });
- };
- BaseProvider.prototype.getCode = function (addressOrName, blockTag) {
- return __awaiter(this, void 0, void 0, function () {
- var params, result;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, this.getNetwork()];
- case 1:
- _a.sent();
- return [4 /*yield*/, (0, lib$3.resolveProperties)({
- address: this._getAddress(addressOrName),
- blockTag: this._getBlockTag(blockTag)
- })];
- case 2:
- params = _a.sent();
- return [4 /*yield*/, this.perform("getCode", params)];
- case 3:
- result = _a.sent();
- try {
- return [2 /*return*/, (0, lib$1.hexlify)(result)];
- }
- catch (error) {
- return [2 /*return*/, logger.throwError("bad result from backend", lib.Logger.errors.SERVER_ERROR, {
- method: "getCode",
- params: params,
- result: result,
- error: error
- })];
- }
- return [2 /*return*/];
- }
- });
- });
- };
- BaseProvider.prototype.getStorageAt = function (addressOrName, position, blockTag) {
- return __awaiter(this, void 0, void 0, function () {
- var params, result;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, this.getNetwork()];
- case 1:
- _a.sent();
- return [4 /*yield*/, (0, lib$3.resolveProperties)({
- address: this._getAddress(addressOrName),
- blockTag: this._getBlockTag(blockTag),
- position: Promise.resolve(position).then(function (p) { return (0, lib$1.hexValue)(p); })
- })];
- case 2:
- params = _a.sent();
- return [4 /*yield*/, this.perform("getStorageAt", params)];
- case 3:
- result = _a.sent();
- try {
- return [2 /*return*/, (0, lib$1.hexlify)(result)];
- }
- catch (error) {
- return [2 /*return*/, logger.throwError("bad result from backend", lib.Logger.errors.SERVER_ERROR, {
- method: "getStorageAt",
- params: params,
- result: result,
- error: error
- })];
- }
- return [2 /*return*/];
- }
- });
- });
- };
- // This should be called by any subclass wrapping a TransactionResponse
- BaseProvider.prototype._wrapTransaction = function (tx, hash, startBlock) {
- var _this = this;
- if (hash != null && (0, lib$1.hexDataLength)(hash) !== 32) {
- throw new Error("invalid response - sendTransaction");
- }
- var result = tx;
- // Check the hash we expect is the same as the hash the server reported
- if (hash != null && tx.hash !== hash) {
- logger.throwError("Transaction hash mismatch from Provider.sendTransaction.", lib.Logger.errors.UNKNOWN_ERROR, { expectedHash: tx.hash, returnedHash: hash });
- }
- result.wait = function (confirms, timeout) { return __awaiter(_this, void 0, void 0, function () {
- var replacement, receipt;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (confirms == null) {
- confirms = 1;
- }
- if (timeout == null) {
- timeout = 0;
- }
- replacement = undefined;
- if (confirms !== 0 && startBlock != null) {
- replacement = {
- data: tx.data,
- from: tx.from,
- nonce: tx.nonce,
- to: tx.to,
- value: tx.value,
- startBlock: startBlock
- };
- }
- return [4 /*yield*/, this._waitForTransaction(tx.hash, confirms, timeout, replacement)];
- case 1:
- receipt = _a.sent();
- if (receipt == null && confirms === 0) {
- return [2 /*return*/, null];
- }
- // No longer pending, allow the polling loop to garbage collect this
- this._emitted["t:" + tx.hash] = receipt.blockNumber;
- if (receipt.status === 0) {
- logger.throwError("transaction failed", lib.Logger.errors.CALL_EXCEPTION, {
- transactionHash: tx.hash,
- transaction: tx,
- receipt: receipt
- });
- }
- return [2 /*return*/, receipt];
- }
- });
- }); };
- return result;
- };
- BaseProvider.prototype.sendTransaction = function (signedTransaction) {
- return __awaiter(this, void 0, void 0, function () {
- var hexTx, tx, blockNumber, hash, error_7;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, this.getNetwork()];
- case 1:
- _a.sent();
- return [4 /*yield*/, Promise.resolve(signedTransaction).then(function (t) { return (0, lib$1.hexlify)(t); })];
- case 2:
- hexTx = _a.sent();
- tx = this.formatter.transaction(signedTransaction);
- if (tx.confirmations == null) {
- tx.confirmations = 0;
- }
- return [4 /*yield*/, this._getInternalBlockNumber(100 + 2 * this.pollingInterval)];
- case 3:
- blockNumber = _a.sent();
- _a.label = 4;
- case 4:
- _a.trys.push([4, 6, , 7]);
- return [4 /*yield*/, this.perform("sendTransaction", { signedTransaction: hexTx })];
- case 5:
- hash = _a.sent();
- return [2 /*return*/, this._wrapTransaction(tx, hash, blockNumber)];
- case 6:
- error_7 = _a.sent();
- error_7.transaction = tx;
- error_7.transactionHash = tx.hash;
- throw error_7;
- case 7: return [2 /*return*/];
- }
- });
- });
- };
- BaseProvider.prototype._getTransactionRequest = function (transaction) {
- return __awaiter(this, void 0, void 0, function () {
- var values, tx, _a, _b;
- var _this = this;
- return __generator(this, function (_c) {
- switch (_c.label) {
- case 0: return [4 /*yield*/, transaction];
- case 1:
- values = _c.sent();
- tx = {};
- ["from", "to"].forEach(function (key) {
- if (values[key] == null) {
- return;
- }
- tx[key] = Promise.resolve(values[key]).then(function (v) { return (v ? _this._getAddress(v) : null); });
- });
- ["gasLimit", "gasPrice", "maxFeePerGas", "maxPriorityFeePerGas", "value"].forEach(function (key) {
- if (values[key] == null) {
- return;
- }
- tx[key] = Promise.resolve(values[key]).then(function (v) { return (v ? lib$2.BigNumber.from(v) : null); });
- });
- ["type"].forEach(function (key) {
- if (values[key] == null) {
- return;
- }
- tx[key] = Promise.resolve(values[key]).then(function (v) { return ((v != null) ? v : null); });
- });
- if (values.accessList) {
- tx.accessList = this.formatter.accessList(values.accessList);
- }
- ["data"].forEach(function (key) {
- if (values[key] == null) {
- return;
- }
- tx[key] = Promise.resolve(values[key]).then(function (v) { return (v ? (0, lib$1.hexlify)(v) : null); });
- });
- _b = (_a = this.formatter).transactionRequest;
- return [4 /*yield*/, (0, lib$3.resolveProperties)(tx)];
- case 2: return [2 /*return*/, _b.apply(_a, [_c.sent()])];
- }
- });
- });
- };
- BaseProvider.prototype._getFilter = function (filter) {
- return __awaiter(this, void 0, void 0, function () {
- var result, _a, _b;
- var _this = this;
- return __generator(this, function (_c) {
- switch (_c.label) {
- case 0: return [4 /*yield*/, filter];
- case 1:
- filter = _c.sent();
- result = {};
- if (filter.address != null) {
- result.address = this._getAddress(filter.address);
- }
- ["blockHash", "topics"].forEach(function (key) {
- if (filter[key] == null) {
- return;
- }
- result[key] = filter[key];
- });
- ["fromBlock", "toBlock"].forEach(function (key) {
- if (filter[key] == null) {
- return;
- }
- result[key] = _this._getBlockTag(filter[key]);
- });
- _b = (_a = this.formatter).filter;
- return [4 /*yield*/, (0, lib$3.resolveProperties)(result)];
- case 2: return [2 /*return*/, _b.apply(_a, [_c.sent()])];
- }
- });
- });
- };
- BaseProvider.prototype._call = function (transaction, blockTag, attempt) {
- return __awaiter(this, void 0, void 0, function () {
- var txSender, result, data, sender, urls, urlsOffset, urlsLength, urlsData, u, url, calldata, callbackSelector, extraData, ccipResult, tx, error_8;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (attempt >= MAX_CCIP_REDIRECTS) {
- logger.throwError("CCIP read exceeded maximum redirections", lib.Logger.errors.SERVER_ERROR, {
- redirects: attempt,
- transaction: transaction
- });
- }
- txSender = transaction.to;
- return [4 /*yield*/, this.perform("call", { transaction: transaction, blockTag: blockTag })];
- case 1:
- result = _a.sent();
- if (!(attempt >= 0 && blockTag === "latest" && txSender != null && result.substring(0, 10) === "0x556f1830" && ((0, lib$1.hexDataLength)(result) % 32 === 4))) return [3 /*break*/, 5];
- _a.label = 2;
- case 2:
- _a.trys.push([2, 4, , 5]);
- data = (0, lib$1.hexDataSlice)(result, 4);
- sender = (0, lib$1.hexDataSlice)(data, 0, 32);
- if (!lib$2.BigNumber.from(sender).eq(txSender)) {
- logger.throwError("CCIP Read sender did not match", lib.Logger.errors.CALL_EXCEPTION, {
- name: "OffchainLookup",
- signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
- transaction: transaction,
- data: result
- });
- }
- urls = [];
- urlsOffset = lib$2.BigNumber.from((0, lib$1.hexDataSlice)(data, 32, 64)).toNumber();
- urlsLength = lib$2.BigNumber.from((0, lib$1.hexDataSlice)(data, urlsOffset, urlsOffset + 32)).toNumber();
- urlsData = (0, lib$1.hexDataSlice)(data, urlsOffset + 32);
- for (u = 0; u < urlsLength; u++) {
- url = _parseString(urlsData, u * 32);
- if (url == null) {
- logger.throwError("CCIP Read contained corrupt URL string", lib.Logger.errors.CALL_EXCEPTION, {
- name: "OffchainLookup",
- signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
- transaction: transaction,
- data: result
- });
- }
- urls.push(url);
- }
- calldata = _parseBytes(data, 64);
- // Get the callbackSelector (bytes4)
- if (!lib$2.BigNumber.from((0, lib$1.hexDataSlice)(data, 100, 128)).isZero()) {
- logger.throwError("CCIP Read callback selector included junk", lib.Logger.errors.CALL_EXCEPTION, {
- name: "OffchainLookup",
- signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
- transaction: transaction,
- data: result
- });
- }
- callbackSelector = (0, lib$1.hexDataSlice)(data, 96, 100);
- extraData = _parseBytes(data, 128);
- return [4 /*yield*/, this.ccipReadFetch(transaction, calldata, urls)];
- case 3:
- ccipResult = _a.sent();
- if (ccipResult == null) {
- logger.throwError("CCIP Read disabled or provided no URLs", lib.Logger.errors.CALL_EXCEPTION, {
- name: "OffchainLookup",
- signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)",
- transaction: transaction,
- data: result
- });
- }
- tx = {
- to: txSender,
- data: (0, lib$1.hexConcat)([callbackSelector, encodeBytes([ccipResult, extraData])])
- };
- return [2 /*return*/, this._call(tx, blockTag, attempt + 1)];
- case 4:
- error_8 = _a.sent();
- if (error_8.code === lib.Logger.errors.SERVER_ERROR) {
- throw error_8;
- }
- return [3 /*break*/, 5];
- case 5:
- try {
- return [2 /*return*/, (0, lib$1.hexlify)(result)];
- }
- catch (error) {
- return [2 /*return*/, logger.throwError("bad result from backend", lib.Logger.errors.SERVER_ERROR, {
- method: "call",
- params: { transaction: transaction, blockTag: blockTag },
- result: result,
- error: error
- })];
- }
- return [2 /*return*/];
- }
- });
- });
- };
- BaseProvider.prototype.call = function (transaction, blockTag) {
- return __awaiter(this, void 0, void 0, function () {
- var resolved;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, this.getNetwork()];
- case 1:
- _a.sent();
- return [4 /*yield*/, (0, lib$3.resolveProperties)({
- transaction: this._getTransactionRequest(transaction),
- blockTag: this._getBlockTag(blockTag),
- ccipReadEnabled: Promise.resolve(transaction.ccipReadEnabled)
- })];
- case 2:
- resolved = _a.sent();
- return [2 /*return*/, this._call(resolved.transaction, resolved.blockTag, resolved.ccipReadEnabled ? 0 : -1)];
- }
- });
- });
- };
- BaseProvider.prototype.estimateGas = function (transaction) {
- return __awaiter(this, void 0, void 0, function () {
- var params, result;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, this.getNetwork()];
- case 1:
- _a.sent();
- return [4 /*yield*/, (0, lib$3.resolveProperties)({
- transaction: this._getTransactionRequest(transaction)
- })];
- case 2:
- params = _a.sent();
- return [4 /*yield*/, this.perform("estimateGas", params)];
- case 3:
- result = _a.sent();
- try {
- return [2 /*return*/, lib$2.BigNumber.from(result)];
- }
- catch (error) {
- return [2 /*return*/, logger.throwError("bad result from backend", lib.Logger.errors.SERVER_ERROR, {
- method: "estimateGas",
- params: params,
- result: result,
- error: error
- })];
- }
- return [2 /*return*/];
- }
- });
- });
- };
- BaseProvider.prototype._getAddress = function (addressOrName) {
- return __awaiter(this, void 0, void 0, function () {
- var address;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, addressOrName];
- case 1:
- addressOrName = _a.sent();
- if (typeof (addressOrName) !== "string") {
- logger.throwArgumentError("invalid address or ENS name", "name", addressOrName);
- }
- return [4 /*yield*/, this.resolveName(addressOrName)];
- case 2:
- address = _a.sent();
- if (address == null) {
- logger.throwError("ENS name not configured", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "resolveName(" + JSON.stringify(addressOrName) + ")"
- });
- }
- return [2 /*return*/, address];
- }
- });
- });
- };
- BaseProvider.prototype._getBlock = function (blockHashOrBlockTag, includeTransactions) {
- return __awaiter(this, void 0, void 0, function () {
- var blockNumber, params, _a, error_9;
- var _this = this;
- return __generator(this, function (_b) {
- switch (_b.label) {
- case 0: return [4 /*yield*/, this.getNetwork()];
- case 1:
- _b.sent();
- return [4 /*yield*/, blockHashOrBlockTag];
- case 2:
- blockHashOrBlockTag = _b.sent();
- blockNumber = -128;
- params = {
- includeTransactions: !!includeTransactions
- };
- if (!(0, lib$1.isHexString)(blockHashOrBlockTag, 32)) return [3 /*break*/, 3];
- params.blockHash = blockHashOrBlockTag;
- return [3 /*break*/, 6];
- case 3:
- _b.trys.push([3, 5, , 6]);
- _a = params;
- return [4 /*yield*/, this._getBlockTag(blockHashOrBlockTag)];
- case 4:
- _a.blockTag = _b.sent();
- if ((0, lib$1.isHexString)(params.blockTag)) {
- blockNumber = parseInt(params.blockTag.substring(2), 16);
- }
- return [3 /*break*/, 6];
- case 5:
- error_9 = _b.sent();
- logger.throwArgumentError("invalid block hash or block tag", "blockHashOrBlockTag", blockHashOrBlockTag);
- return [3 /*break*/, 6];
- case 6: return [2 /*return*/, (0, lib$q.poll)(function () { return __awaiter(_this, void 0, void 0, function () {
- var block, blockNumber_1, i, tx, confirmations, blockWithTxs;
- var _this = this;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, this.perform("getBlock", params)];
- case 1:
- block = _a.sent();
- // Block was not found
- if (block == null) {
- // For blockhashes, if we didn't say it existed, that blockhash may
- // not exist. If we did see it though, perhaps from a log, we know
- // it exists, and this node is just not caught up yet.
- if (params.blockHash != null) {
- if (this._emitted["b:" + params.blockHash] == null) {
- return [2 /*return*/, null];
- }
- }
- // For block tags, if we are asking for a future block, we return null
- if (params.blockTag != null) {
- if (blockNumber > this._emitted.block) {
- return [2 /*return*/, null];
- }
- }
- // Retry on the next block
- return [2 /*return*/, undefined];
- }
- if (!includeTransactions) return [3 /*break*/, 8];
- blockNumber_1 = null;
- i = 0;
- _a.label = 2;
- case 2:
- if (!(i < block.transactions.length)) return [3 /*break*/, 7];
- tx = block.transactions[i];
- if (!(tx.blockNumber == null)) return [3 /*break*/, 3];
- tx.confirmations = 0;
- return [3 /*break*/, 6];
- case 3:
- if (!(tx.confirmations == null)) return [3 /*break*/, 6];
- if (!(blockNumber_1 == null)) return [3 /*break*/, 5];
- return [4 /*yield*/, this._getInternalBlockNumber(100 + 2 * this.pollingInterval)];
- case 4:
- blockNumber_1 = _a.sent();
- _a.label = 5;
- case 5:
- confirmations = (blockNumber_1 - tx.blockNumber) + 1;
- if (confirmations <= 0) {
- confirmations = 1;
- }
- tx.confirmations = confirmations;
- _a.label = 6;
- case 6:
- i++;
- return [3 /*break*/, 2];
- case 7:
- blockWithTxs = this.formatter.blockWithTransactions(block);
- blockWithTxs.transactions = blockWithTxs.transactions.map(function (tx) { return _this._wrapTransaction(tx); });
- return [2 /*return*/, blockWithTxs];
- case 8: return [2 /*return*/, this.formatter.block(block)];
- }
- });
- }); }, { oncePoll: this })];
- }
- });
- });
- };
- BaseProvider.prototype.getBlock = function (blockHashOrBlockTag) {
- return (this._getBlock(blockHashOrBlockTag, false));
- };
- BaseProvider.prototype.getBlockWithTransactions = function (blockHashOrBlockTag) {
- return (this._getBlock(blockHashOrBlockTag, true));
- };
- BaseProvider.prototype.getTransaction = function (transactionHash) {
- return __awaiter(this, void 0, void 0, function () {
- var params;
- var _this = this;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, this.getNetwork()];
- case 1:
- _a.sent();
- return [4 /*yield*/, transactionHash];
- case 2:
- transactionHash = _a.sent();
- params = { transactionHash: this.formatter.hash(transactionHash, true) };
- return [2 /*return*/, (0, lib$q.poll)(function () { return __awaiter(_this, void 0, void 0, function () {
- var result, tx, blockNumber, confirmations;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, this.perform("getTransaction", params)];
- case 1:
- result = _a.sent();
- if (result == null) {
- if (this._emitted["t:" + transactionHash] == null) {
- return [2 /*return*/, null];
- }
- return [2 /*return*/, undefined];
- }
- tx = this.formatter.transactionResponse(result);
- if (!(tx.blockNumber == null)) return [3 /*break*/, 2];
- tx.confirmations = 0;
- return [3 /*break*/, 4];
- case 2:
- if (!(tx.confirmations == null)) return [3 /*break*/, 4];
- return [4 /*yield*/, this._getInternalBlockNumber(100 + 2 * this.pollingInterval)];
- case 3:
- blockNumber = _a.sent();
- confirmations = (blockNumber - tx.blockNumber) + 1;
- if (confirmations <= 0) {
- confirmations = 1;
- }
- tx.confirmations = confirmations;
- _a.label = 4;
- case 4: return [2 /*return*/, this._wrapTransaction(tx)];
- }
- });
- }); }, { oncePoll: this })];
- }
- });
- });
- };
- BaseProvider.prototype.getTransactionReceipt = function (transactionHash) {
- return __awaiter(this, void 0, void 0, function () {
- var params;
- var _this = this;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, this.getNetwork()];
- case 1:
- _a.sent();
- return [4 /*yield*/, transactionHash];
- case 2:
- transactionHash = _a.sent();
- params = { transactionHash: this.formatter.hash(transactionHash, true) };
- return [2 /*return*/, (0, lib$q.poll)(function () { return __awaiter(_this, void 0, void 0, function () {
- var result, receipt, blockNumber, confirmations;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, this.perform("getTransactionReceipt", params)];
- case 1:
- result = _a.sent();
- if (result == null) {
- if (this._emitted["t:" + transactionHash] == null) {
- return [2 /*return*/, null];
- }
- return [2 /*return*/, undefined];
- }
- // "geth-etc" returns receipts before they are ready
- if (result.blockHash == null) {
- return [2 /*return*/, undefined];
- }
- receipt = this.formatter.receipt(result);
- if (!(receipt.blockNumber == null)) return [3 /*break*/, 2];
- receipt.confirmations = 0;
- return [3 /*break*/, 4];
- case 2:
- if (!(receipt.confirmations == null)) return [3 /*break*/, 4];
- return [4 /*yield*/, this._getInternalBlockNumber(100 + 2 * this.pollingInterval)];
- case 3:
- blockNumber = _a.sent();
- confirmations = (blockNumber - receipt.blockNumber) + 1;
- if (confirmations <= 0) {
- confirmations = 1;
- }
- receipt.confirmations = confirmations;
- _a.label = 4;
- case 4: return [2 /*return*/, receipt];
- }
- });
- }); }, { oncePoll: this })];
- }
- });
- });
- };
- BaseProvider.prototype.getLogs = function (filter) {
- return __awaiter(this, void 0, void 0, function () {
- var params, logs;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, this.getNetwork()];
- case 1:
- _a.sent();
- return [4 /*yield*/, (0, lib$3.resolveProperties)({ filter: this._getFilter(filter) })];
- case 2:
- params = _a.sent();
- return [4 /*yield*/, this.perform("getLogs", params)];
- case 3:
- logs = _a.sent();
- logs.forEach(function (log) {
- if (log.removed == null) {
- log.removed = false;
- }
- });
- return [2 /*return*/, formatter.Formatter.arrayOf(this.formatter.filterLog.bind(this.formatter))(logs)];
- }
- });
- });
- };
- BaseProvider.prototype.getEtherPrice = function () {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, this.getNetwork()];
- case 1:
- _a.sent();
- return [2 /*return*/, this.perform("getEtherPrice", {})];
- }
- });
- });
- };
- BaseProvider.prototype._getBlockTag = function (blockTag) {
- return __awaiter(this, void 0, void 0, function () {
- var blockNumber;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, blockTag];
- case 1:
- blockTag = _a.sent();
- if (!(typeof (blockTag) === "number" && blockTag < 0)) return [3 /*break*/, 3];
- if (blockTag % 1) {
- logger.throwArgumentError("invalid BlockTag", "blockTag", blockTag);
- }
- return [4 /*yield*/, this._getInternalBlockNumber(100 + 2 * this.pollingInterval)];
- case 2:
- blockNumber = _a.sent();
- blockNumber += blockTag;
- if (blockNumber < 0) {
- blockNumber = 0;
- }
- return [2 /*return*/, this.formatter.blockTag(blockNumber)];
- case 3: return [2 /*return*/, this.formatter.blockTag(blockTag)];
- }
- });
- });
- };
- BaseProvider.prototype.getResolver = function (name) {
- return __awaiter(this, void 0, void 0, function () {
- var currentName, addr, resolver, _a;
- return __generator(this, function (_b) {
- switch (_b.label) {
- case 0:
- currentName = name;
- _b.label = 1;
- case 1:
- if (!true) return [3 /*break*/, 6];
- if (currentName === "" || currentName === ".") {
- return [2 /*return*/, null];
- }
- // Optimization since the eth node cannot change and does
- // not have a wildcar resolver
- if (name !== "eth" && currentName === "eth") {
- return [2 /*return*/, null];
- }
- return [4 /*yield*/, this._getResolver(currentName, "getResolver")];
- case 2:
- addr = _b.sent();
- if (!(addr != null)) return [3 /*break*/, 5];
- resolver = new Resolver(this, addr, name);
- _a = currentName !== name;
- if (!_a) return [3 /*break*/, 4];
- return [4 /*yield*/, resolver.supportsWildcard()];
- case 3:
- _a = !(_b.sent());
- _b.label = 4;
- case 4:
- // Legacy resolver found, using EIP-2544 so it isn't safe to use
- if (_a) {
- return [2 /*return*/, null];
- }
- return [2 /*return*/, resolver];
- case 5:
- // Get the parent node
- currentName = currentName.split(".").slice(1).join(".");
- return [3 /*break*/, 1];
- case 6: return [2 /*return*/];
- }
- });
- });
- };
- BaseProvider.prototype._getResolver = function (name, operation) {
- return __awaiter(this, void 0, void 0, function () {
- var network, addrData, error_10;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (operation == null) {
- operation = "ENS";
- }
- return [4 /*yield*/, this.getNetwork()];
- case 1:
- network = _a.sent();
- // No ENS...
- if (!network.ensAddress) {
- logger.throwError("network does not support ENS", lib.Logger.errors.UNSUPPORTED_OPERATION, { operation: operation, network: network.name });
- }
- _a.label = 2;
- case 2:
- _a.trys.push([2, 4, , 5]);
- return [4 /*yield*/, this.call({
- to: network.ensAddress,
- data: ("0x0178b8bf" + (0, lib$9.namehash)(name).substring(2))
- })];
- case 3:
- addrData = _a.sent();
- return [2 /*return*/, this.formatter.callAddress(addrData)];
- case 4:
- error_10 = _a.sent();
- return [3 /*break*/, 5];
- case 5: return [2 /*return*/, null];
- }
- });
- });
- };
- BaseProvider.prototype.resolveName = function (name) {
- return __awaiter(this, void 0, void 0, function () {
- var resolver;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, name];
- case 1:
- name = _a.sent();
- // If it is already an address, nothing to resolve
- try {
- return [2 /*return*/, Promise.resolve(this.formatter.address(name))];
- }
- catch (error) {
- // If is is a hexstring, the address is bad (See #694)
- if ((0, lib$1.isHexString)(name)) {
- throw error;
- }
- }
- if (typeof (name) !== "string") {
- logger.throwArgumentError("invalid ENS name", "name", name);
- }
- return [4 /*yield*/, this.getResolver(name)];
- case 2:
- resolver = _a.sent();
- if (!resolver) {
- return [2 /*return*/, null];
- }
- return [4 /*yield*/, resolver.getAddress()];
- case 3: return [2 /*return*/, _a.sent()];
- }
- });
- });
- };
- BaseProvider.prototype.lookupAddress = function (address) {
- return __awaiter(this, void 0, void 0, function () {
- var node, resolverAddr, name, _a, addr;
- return __generator(this, function (_b) {
- switch (_b.label) {
- case 0: return [4 /*yield*/, address];
- case 1:
- address = _b.sent();
- address = this.formatter.address(address);
- node = address.substring(2).toLowerCase() + ".addr.reverse";
- return [4 /*yield*/, this._getResolver(node, "lookupAddress")];
- case 2:
- resolverAddr = _b.sent();
- if (resolverAddr == null) {
- return [2 /*return*/, null];
- }
- _a = _parseString;
- return [4 /*yield*/, this.call({
- to: resolverAddr,
- data: ("0x691f3431" + (0, lib$9.namehash)(node).substring(2))
- })];
- case 3:
- name = _a.apply(void 0, [_b.sent(), 0]);
- return [4 /*yield*/, this.resolveName(name)];
- case 4:
- addr = _b.sent();
- if (addr != address) {
- return [2 /*return*/, null];
- }
- return [2 /*return*/, name];
- }
- });
- });
- };
- BaseProvider.prototype.getAvatar = function (nameOrAddress) {
- return __awaiter(this, void 0, void 0, function () {
- var resolver, address, node, resolverAddress, avatar_1, error_11, name_1, _a, error_12, avatar;
- return __generator(this, function (_b) {
- switch (_b.label) {
- case 0:
- resolver = null;
- if (!(0, lib$1.isHexString)(nameOrAddress)) return [3 /*break*/, 10];
- address = this.formatter.address(nameOrAddress);
- node = address.substring(2).toLowerCase() + ".addr.reverse";
- return [4 /*yield*/, this._getResolver(node, "getAvatar")];
- case 1:
- resolverAddress = _b.sent();
- if (!resolverAddress) {
- return [2 /*return*/, null];
- }
- // Try resolving the avatar against the addr.reverse resolver
- resolver = new Resolver(this, resolverAddress, node);
- _b.label = 2;
- case 2:
- _b.trys.push([2, 4, , 5]);
- return [4 /*yield*/, resolver.getAvatar()];
- case 3:
- avatar_1 = _b.sent();
- if (avatar_1) {
- return [2 /*return*/, avatar_1.url];
- }
- return [3 /*break*/, 5];
- case 4:
- error_11 = _b.sent();
- if (error_11.code !== lib.Logger.errors.CALL_EXCEPTION) {
- throw error_11;
- }
- return [3 /*break*/, 5];
- case 5:
- _b.trys.push([5, 8, , 9]);
- _a = _parseString;
- return [4 /*yield*/, this.call({
- to: resolverAddress,
- data: ("0x691f3431" + (0, lib$9.namehash)(node).substring(2))
- })];
- case 6:
- name_1 = _a.apply(void 0, [_b.sent(), 0]);
- return [4 /*yield*/, this.getResolver(name_1)];
- case 7:
- resolver = _b.sent();
- return [3 /*break*/, 9];
- case 8:
- error_12 = _b.sent();
- if (error_12.code !== lib.Logger.errors.CALL_EXCEPTION) {
- throw error_12;
- }
- return [2 /*return*/, null];
- case 9: return [3 /*break*/, 12];
- case 10: return [4 /*yield*/, this.getResolver(nameOrAddress)];
- case 11:
- // ENS name; forward lookup with wildcard
- resolver = _b.sent();
- if (!resolver) {
- return [2 /*return*/, null];
- }
- _b.label = 12;
- case 12: return [4 /*yield*/, resolver.getAvatar()];
- case 13:
- avatar = _b.sent();
- if (avatar == null) {
- return [2 /*return*/, null];
- }
- return [2 /*return*/, avatar.url];
- }
- });
- });
- };
- BaseProvider.prototype.perform = function (method, params) {
- return logger.throwError(method + " not implemented", lib.Logger.errors.NOT_IMPLEMENTED, { operation: method });
- };
- BaseProvider.prototype._startEvent = function (event) {
- this.polling = (this._events.filter(function (e) { return e.pollable(); }).length > 0);
- };
- BaseProvider.prototype._stopEvent = function (event) {
- this.polling = (this._events.filter(function (e) { return e.pollable(); }).length > 0);
- };
- BaseProvider.prototype._addEventListener = function (eventName, listener, once) {
- var event = new Event(getEventTag(eventName), listener, once);
- this._events.push(event);
- this._startEvent(event);
- return this;
- };
- BaseProvider.prototype.on = function (eventName, listener) {
- return this._addEventListener(eventName, listener, false);
- };
- BaseProvider.prototype.once = function (eventName, listener) {
- return this._addEventListener(eventName, listener, true);
- };
- BaseProvider.prototype.emit = function (eventName) {
- var _this = this;
- var args = [];
- for (var _i = 1; _i < arguments.length; _i++) {
- args[_i - 1] = arguments[_i];
- }
- var result = false;
- var stopped = [];
- var eventTag = getEventTag(eventName);
- this._events = this._events.filter(function (event) {
- if (event.tag !== eventTag) {
- return true;
- }
- setTimeout(function () {
- event.listener.apply(_this, args);
- }, 0);
- result = true;
- if (event.once) {
- stopped.push(event);
- return false;
- }
- return true;
- });
- stopped.forEach(function (event) { _this._stopEvent(event); });
- return result;
- };
- BaseProvider.prototype.listenerCount = function (eventName) {
- if (!eventName) {
- return this._events.length;
- }
- var eventTag = getEventTag(eventName);
- return this._events.filter(function (event) {
- return (event.tag === eventTag);
- }).length;
- };
- BaseProvider.prototype.listeners = function (eventName) {
- if (eventName == null) {
- return this._events.map(function (event) { return event.listener; });
- }
- var eventTag = getEventTag(eventName);
- return this._events
- .filter(function (event) { return (event.tag === eventTag); })
- .map(function (event) { return event.listener; });
- };
- BaseProvider.prototype.off = function (eventName, listener) {
- var _this = this;
- if (listener == null) {
- return this.removeAllListeners(eventName);
- }
- var stopped = [];
- var found = false;
- var eventTag = getEventTag(eventName);
- this._events = this._events.filter(function (event) {
- if (event.tag !== eventTag || event.listener != listener) {
- return true;
- }
- if (found) {
- return true;
- }
- found = true;
- stopped.push(event);
- return false;
- });
- stopped.forEach(function (event) { _this._stopEvent(event); });
- return this;
- };
- BaseProvider.prototype.removeAllListeners = function (eventName) {
- var _this = this;
- var stopped = [];
- if (eventName == null) {
- stopped = this._events;
- this._events = [];
- }
- else {
- var eventTag_1 = getEventTag(eventName);
- this._events = this._events.filter(function (event) {
- if (event.tag !== eventTag_1) {
- return true;
- }
- stopped.push(event);
- return false;
- });
- }
- stopped.forEach(function (event) { _this._stopEvent(event); });
- return this;
- };
- return BaseProvider;
- }(lib$b.Provider));
- exports.BaseProvider = BaseProvider;
- });
- var baseProvider$1 = /*@__PURE__*/getDefaultExportFromCjs(baseProvider);
- var jsonRpcProvider = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.JsonRpcProvider = exports.JsonRpcSigner = void 0;
- var logger = new lib.Logger(_version$I.version);
- var errorGas = ["call", "estimateGas"];
- function checkError(method, error, params) {
- // Undo the "convenience" some nodes are attempting to prevent backwards
- // incompatibility; maybe for v6 consider forwarding reverts as errors
- if (method === "call" && error.code === lib.Logger.errors.SERVER_ERROR) {
- var e = error.error;
- if (e && e.message.match("reverted") && (0, lib$1.isHexString)(e.data)) {
- return e.data;
- }
- logger.throwError("missing revert data in call exception", lib.Logger.errors.CALL_EXCEPTION, {
- error: error,
- data: "0x"
- });
- }
- var message = error.message;
- if (error.code === lib.Logger.errors.SERVER_ERROR && error.error && typeof (error.error.message) === "string") {
- message = error.error.message;
- }
- else if (typeof (error.body) === "string") {
- message = error.body;
- }
- else if (typeof (error.responseText) === "string") {
- message = error.responseText;
- }
- message = (message || "").toLowerCase();
- var transaction = params.transaction || params.signedTransaction;
- // "insufficient funds for gas * price + value + cost(data)"
- if (message.match(/insufficient funds|base fee exceeds gas limit/)) {
- logger.throwError("insufficient funds for intrinsic transaction cost", lib.Logger.errors.INSUFFICIENT_FUNDS, {
- error: error,
- method: method,
- transaction: transaction
- });
- }
- // "nonce too low"
- if (message.match(/nonce too low/)) {
- logger.throwError("nonce has already been used", lib.Logger.errors.NONCE_EXPIRED, {
- error: error,
- method: method,
- transaction: transaction
- });
- }
- // "replacement transaction underpriced"
- if (message.match(/replacement transaction underpriced/)) {
- logger.throwError("replacement fee too low", lib.Logger.errors.REPLACEMENT_UNDERPRICED, {
- error: error,
- method: method,
- transaction: transaction
- });
- }
- // "replacement transaction underpriced"
- if (message.match(/only replay-protected/)) {
- logger.throwError("legacy pre-eip-155 transactions not supported", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- error: error,
- method: method,
- transaction: transaction
- });
- }
- if (errorGas.indexOf(method) >= 0 && message.match(/gas required exceeds allowance|always failing transaction|execution reverted/)) {
- logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", lib.Logger.errors.UNPREDICTABLE_GAS_LIMIT, {
- error: error,
- method: method,
- transaction: transaction
- });
- }
- throw error;
- }
- function timer(timeout) {
- return new Promise(function (resolve) {
- setTimeout(resolve, timeout);
- });
- }
- function getResult(payload) {
- if (payload.error) {
- // @TODO: not any
- var error = new Error(payload.error.message);
- error.code = payload.error.code;
- error.data = payload.error.data;
- throw error;
- }
- return payload.result;
- }
- function getLowerCase(value) {
- if (value) {
- return value.toLowerCase();
- }
- return value;
- }
- var _constructorGuard = {};
- var JsonRpcSigner = /** @class */ (function (_super) {
- __extends(JsonRpcSigner, _super);
- function JsonRpcSigner(constructorGuard, provider, addressOrIndex) {
- var _newTarget = this.constructor;
- var _this = this;
- logger.checkNew(_newTarget, JsonRpcSigner);
- _this = _super.call(this) || this;
- if (constructorGuard !== _constructorGuard) {
- throw new Error("do not call the JsonRpcSigner constructor directly; use provider.getSigner");
- }
- (0, lib$3.defineReadOnly)(_this, "provider", provider);
- if (addressOrIndex == null) {
- addressOrIndex = 0;
- }
- if (typeof (addressOrIndex) === "string") {
- (0, lib$3.defineReadOnly)(_this, "_address", _this.provider.formatter.address(addressOrIndex));
- (0, lib$3.defineReadOnly)(_this, "_index", null);
- }
- else if (typeof (addressOrIndex) === "number") {
- (0, lib$3.defineReadOnly)(_this, "_index", addressOrIndex);
- (0, lib$3.defineReadOnly)(_this, "_address", null);
- }
- else {
- logger.throwArgumentError("invalid address or index", "addressOrIndex", addressOrIndex);
- }
- return _this;
- }
- JsonRpcSigner.prototype.connect = function (provider) {
- return logger.throwError("cannot alter JSON-RPC Signer connection", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "connect"
- });
- };
- JsonRpcSigner.prototype.connectUnchecked = function () {
- return new UncheckedJsonRpcSigner(_constructorGuard, this.provider, this._address || this._index);
- };
- JsonRpcSigner.prototype.getAddress = function () {
- var _this = this;
- if (this._address) {
- return Promise.resolve(this._address);
- }
- return this.provider.send("eth_accounts", []).then(function (accounts) {
- if (accounts.length <= _this._index) {
- logger.throwError("unknown account #" + _this._index, lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "getAddress"
- });
- }
- return _this.provider.formatter.address(accounts[_this._index]);
- });
- };
- JsonRpcSigner.prototype.sendUncheckedTransaction = function (transaction) {
- var _this = this;
- transaction = (0, lib$3.shallowCopy)(transaction);
- var fromAddress = this.getAddress().then(function (address) {
- if (address) {
- address = address.toLowerCase();
- }
- return address;
- });
- // The JSON-RPC for eth_sendTransaction uses 90000 gas; if the user
- // wishes to use this, it is easy to specify explicitly, otherwise
- // we look it up for them.
- if (transaction.gasLimit == null) {
- var estimate = (0, lib$3.shallowCopy)(transaction);
- estimate.from = fromAddress;
- transaction.gasLimit = this.provider.estimateGas(estimate);
- }
- if (transaction.to != null) {
- transaction.to = Promise.resolve(transaction.to).then(function (to) { return __awaiter(_this, void 0, void 0, function () {
- var address;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (to == null) {
- return [2 /*return*/, null];
- }
- return [4 /*yield*/, this.provider.resolveName(to)];
- case 1:
- address = _a.sent();
- if (address == null) {
- logger.throwArgumentError("provided ENS name resolves to null", "tx.to", to);
- }
- return [2 /*return*/, address];
- }
- });
- }); });
- }
- return (0, lib$3.resolveProperties)({
- tx: (0, lib$3.resolveProperties)(transaction),
- sender: fromAddress
- }).then(function (_a) {
- var tx = _a.tx, sender = _a.sender;
- if (tx.from != null) {
- if (tx.from.toLowerCase() !== sender) {
- logger.throwArgumentError("from address mismatch", "transaction", transaction);
- }
- }
- else {
- tx.from = sender;
- }
- var hexTx = _this.provider.constructor.hexlifyTransaction(tx, { from: true });
- return _this.provider.send("eth_sendTransaction", [hexTx]).then(function (hash) {
- return hash;
- }, function (error) {
- return checkError("sendTransaction", error, hexTx);
- });
- });
- };
- JsonRpcSigner.prototype.signTransaction = function (transaction) {
- return logger.throwError("signing transactions is unsupported", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "signTransaction"
- });
- };
- JsonRpcSigner.prototype.sendTransaction = function (transaction) {
- return __awaiter(this, void 0, void 0, function () {
- var blockNumber, hash, error_1;
- var _this = this;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, this.provider._getInternalBlockNumber(100 + 2 * this.provider.pollingInterval)];
- case 1:
- blockNumber = _a.sent();
- return [4 /*yield*/, this.sendUncheckedTransaction(transaction)];
- case 2:
- hash = _a.sent();
- _a.label = 3;
- case 3:
- _a.trys.push([3, 5, , 6]);
- return [4 /*yield*/, (0, lib$q.poll)(function () { return __awaiter(_this, void 0, void 0, function () {
- var tx;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, this.provider.getTransaction(hash)];
- case 1:
- tx = _a.sent();
- if (tx === null) {
- return [2 /*return*/, undefined];
- }
- return [2 /*return*/, this.provider._wrapTransaction(tx, hash, blockNumber)];
- }
- });
- }); }, { oncePoll: this.provider })];
- case 4:
- // Unfortunately, JSON-RPC only provides and opaque transaction hash
- // for a response, and we need the actual transaction, so we poll
- // for it; it should show up very quickly
- return [2 /*return*/, _a.sent()];
- case 5:
- error_1 = _a.sent();
- error_1.transactionHash = hash;
- throw error_1;
- case 6: return [2 /*return*/];
- }
- });
- });
- };
- JsonRpcSigner.prototype.signMessage = function (message) {
- return __awaiter(this, void 0, void 0, function () {
- var data, address;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- data = ((typeof (message) === "string") ? (0, lib$8.toUtf8Bytes)(message) : message);
- return [4 /*yield*/, this.getAddress()];
- case 1:
- address = _a.sent();
- return [4 /*yield*/, this.provider.send("personal_sign", [(0, lib$1.hexlify)(data), address.toLowerCase()])];
- case 2: return [2 /*return*/, _a.sent()];
- }
- });
- });
- };
- JsonRpcSigner.prototype._legacySignMessage = function (message) {
- return __awaiter(this, void 0, void 0, function () {
- var data, address;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- data = ((typeof (message) === "string") ? (0, lib$8.toUtf8Bytes)(message) : message);
- return [4 /*yield*/, this.getAddress()];
- case 1:
- address = _a.sent();
- return [4 /*yield*/, this.provider.send("eth_sign", [address.toLowerCase(), (0, lib$1.hexlify)(data)])];
- case 2:
- // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
- return [2 /*return*/, _a.sent()];
- }
- });
- });
- };
- JsonRpcSigner.prototype._signTypedData = function (domain, types, value) {
- return __awaiter(this, void 0, void 0, function () {
- var populated, address;
- var _this = this;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, lib$9._TypedDataEncoder.resolveNames(domain, types, value, function (name) {
- return _this.provider.resolveName(name);
- })];
- case 1:
- populated = _a.sent();
- return [4 /*yield*/, this.getAddress()];
- case 2:
- address = _a.sent();
- return [4 /*yield*/, this.provider.send("eth_signTypedData_v4", [
- address.toLowerCase(),
- JSON.stringify(lib$9._TypedDataEncoder.getPayload(populated.domain, types, populated.value))
- ])];
- case 3: return [2 /*return*/, _a.sent()];
- }
- });
- });
- };
- JsonRpcSigner.prototype.unlock = function (password) {
- return __awaiter(this, void 0, void 0, function () {
- var provider, address;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- provider = this.provider;
- return [4 /*yield*/, this.getAddress()];
- case 1:
- address = _a.sent();
- return [2 /*return*/, provider.send("personal_unlockAccount", [address.toLowerCase(), password, null])];
- }
- });
- });
- };
- return JsonRpcSigner;
- }(lib$c.Signer));
- exports.JsonRpcSigner = JsonRpcSigner;
- var UncheckedJsonRpcSigner = /** @class */ (function (_super) {
- __extends(UncheckedJsonRpcSigner, _super);
- function UncheckedJsonRpcSigner() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- UncheckedJsonRpcSigner.prototype.sendTransaction = function (transaction) {
- var _this = this;
- return this.sendUncheckedTransaction(transaction).then(function (hash) {
- return {
- hash: hash,
- nonce: null,
- gasLimit: null,
- gasPrice: null,
- data: null,
- value: null,
- chainId: null,
- confirmations: 0,
- from: null,
- wait: function (confirmations) { return _this.provider.waitForTransaction(hash, confirmations); }
- };
- });
- };
- return UncheckedJsonRpcSigner;
- }(JsonRpcSigner));
- var allowedTransactionKeys = {
- chainId: true, data: true, gasLimit: true, gasPrice: true, nonce: true, to: true, value: true,
- type: true, accessList: true,
- maxFeePerGas: true, maxPriorityFeePerGas: true
- };
- var JsonRpcProvider = /** @class */ (function (_super) {
- __extends(JsonRpcProvider, _super);
- function JsonRpcProvider(url, network) {
- var _newTarget = this.constructor;
- var _this = this;
- logger.checkNew(_newTarget, JsonRpcProvider);
- var networkOrReady = network;
- // The network is unknown, query the JSON-RPC for it
- if (networkOrReady == null) {
- networkOrReady = new Promise(function (resolve, reject) {
- setTimeout(function () {
- _this.detectNetwork().then(function (network) {
- resolve(network);
- }, function (error) {
- reject(error);
- });
- }, 0);
- });
- }
- _this = _super.call(this, networkOrReady) || this;
- // Default URL
- if (!url) {
- url = (0, lib$3.getStatic)(_this.constructor, "defaultUrl")();
- }
- if (typeof (url) === "string") {
- (0, lib$3.defineReadOnly)(_this, "connection", Object.freeze({
- url: url
- }));
- }
- else {
- (0, lib$3.defineReadOnly)(_this, "connection", Object.freeze((0, lib$3.shallowCopy)(url)));
- }
- _this._nextId = 42;
- return _this;
- }
- Object.defineProperty(JsonRpcProvider.prototype, "_cache", {
- get: function () {
- if (this._eventLoopCache == null) {
- this._eventLoopCache = {};
- }
- return this._eventLoopCache;
- },
- enumerable: false,
- configurable: true
- });
- JsonRpcProvider.defaultUrl = function () {
- return "http:/\/localhost:8545";
- };
- JsonRpcProvider.prototype.detectNetwork = function () {
- var _this = this;
- if (!this._cache["detectNetwork"]) {
- this._cache["detectNetwork"] = this._uncachedDetectNetwork();
- // Clear this cache at the beginning of the next event loop
- setTimeout(function () {
- _this._cache["detectNetwork"] = null;
- }, 0);
- }
- return this._cache["detectNetwork"];
- };
- JsonRpcProvider.prototype._uncachedDetectNetwork = function () {
- return __awaiter(this, void 0, void 0, function () {
- var chainId, error_2, error_3, getNetwork;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, timer(0)];
- case 1:
- _a.sent();
- chainId = null;
- _a.label = 2;
- case 2:
- _a.trys.push([2, 4, , 9]);
- return [4 /*yield*/, this.send("eth_chainId", [])];
- case 3:
- chainId = _a.sent();
- return [3 /*break*/, 9];
- case 4:
- error_2 = _a.sent();
- _a.label = 5;
- case 5:
- _a.trys.push([5, 7, , 8]);
- return [4 /*yield*/, this.send("net_version", [])];
- case 6:
- chainId = _a.sent();
- return [3 /*break*/, 8];
- case 7:
- error_3 = _a.sent();
- return [3 /*break*/, 8];
- case 8: return [3 /*break*/, 9];
- case 9:
- if (chainId != null) {
- getNetwork = (0, lib$3.getStatic)(this.constructor, "getNetwork");
- try {
- return [2 /*return*/, getNetwork(lib$2.BigNumber.from(chainId).toNumber())];
- }
- catch (error) {
- return [2 /*return*/, logger.throwError("could not detect network", lib.Logger.errors.NETWORK_ERROR, {
- chainId: chainId,
- event: "invalidNetwork",
- serverError: error
- })];
- }
- }
- return [2 /*return*/, logger.throwError("could not detect network", lib.Logger.errors.NETWORK_ERROR, {
- event: "noNetwork"
- })];
- }
- });
- });
- };
- JsonRpcProvider.prototype.getSigner = function (addressOrIndex) {
- return new JsonRpcSigner(_constructorGuard, this, addressOrIndex);
- };
- JsonRpcProvider.prototype.getUncheckedSigner = function (addressOrIndex) {
- return this.getSigner(addressOrIndex).connectUnchecked();
- };
- JsonRpcProvider.prototype.listAccounts = function () {
- var _this = this;
- return this.send("eth_accounts", []).then(function (accounts) {
- return accounts.map(function (a) { return _this.formatter.address(a); });
- });
- };
- JsonRpcProvider.prototype.send = function (method, params) {
- var _this = this;
- var request = {
- method: method,
- params: params,
- id: (this._nextId++),
- jsonrpc: "2.0"
- };
- this.emit("debug", {
- action: "request",
- request: (0, lib$3.deepCopy)(request),
- provider: this
- });
- // We can expand this in the future to any call, but for now these
- // are the biggest wins and do not require any serializing parameters.
- var cache = (["eth_chainId", "eth_blockNumber"].indexOf(method) >= 0);
- if (cache && this._cache[method]) {
- return this._cache[method];
- }
- var result = (0, lib$q.fetchJson)(this.connection, JSON.stringify(request), getResult).then(function (result) {
- _this.emit("debug", {
- action: "response",
- request: request,
- response: result,
- provider: _this
- });
- return result;
- }, function (error) {
- _this.emit("debug", {
- action: "response",
- error: error,
- request: request,
- provider: _this
- });
- throw error;
- });
- // Cache the fetch, but clear it on the next event loop
- if (cache) {
- this._cache[method] = result;
- setTimeout(function () {
- _this._cache[method] = null;
- }, 0);
- }
- return result;
- };
- JsonRpcProvider.prototype.prepareRequest = function (method, params) {
- switch (method) {
- case "getBlockNumber":
- return ["eth_blockNumber", []];
- case "getGasPrice":
- return ["eth_gasPrice", []];
- case "getBalance":
- return ["eth_getBalance", [getLowerCase(params.address), params.blockTag]];
- case "getTransactionCount":
- return ["eth_getTransactionCount", [getLowerCase(params.address), params.blockTag]];
- case "getCode":
- return ["eth_getCode", [getLowerCase(params.address), params.blockTag]];
- case "getStorageAt":
- return ["eth_getStorageAt", [getLowerCase(params.address), params.position, params.blockTag]];
- case "sendTransaction":
- return ["eth_sendRawTransaction", [params.signedTransaction]];
- case "getBlock":
- if (params.blockTag) {
- return ["eth_getBlockByNumber", [params.blockTag, !!params.includeTransactions]];
- }
- else if (params.blockHash) {
- return ["eth_getBlockByHash", [params.blockHash, !!params.includeTransactions]];
- }
- return null;
- case "getTransaction":
- return ["eth_getTransactionByHash", [params.transactionHash]];
- case "getTransactionReceipt":
- return ["eth_getTransactionReceipt", [params.transactionHash]];
- case "call": {
- var hexlifyTransaction = (0, lib$3.getStatic)(this.constructor, "hexlifyTransaction");
- return ["eth_call", [hexlifyTransaction(params.transaction, { from: true }), params.blockTag]];
- }
- case "estimateGas": {
- var hexlifyTransaction = (0, lib$3.getStatic)(this.constructor, "hexlifyTransaction");
- return ["eth_estimateGas", [hexlifyTransaction(params.transaction, { from: true })]];
- }
- case "getLogs":
- if (params.filter && params.filter.address != null) {
- params.filter.address = getLowerCase(params.filter.address);
- }
- return ["eth_getLogs", [params.filter]];
- default:
- break;
- }
- return null;
- };
- JsonRpcProvider.prototype.perform = function (method, params) {
- return __awaiter(this, void 0, void 0, function () {
- var tx, feeData, args, error_4;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (!(method === "call" || method === "estimateGas")) return [3 /*break*/, 2];
- tx = params.transaction;
- if (!(tx && tx.type != null && lib$2.BigNumber.from(tx.type).isZero())) return [3 /*break*/, 2];
- if (!(tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null)) return [3 /*break*/, 2];
- return [4 /*yield*/, this.getFeeData()];
- case 1:
- feeData = _a.sent();
- if (feeData.maxFeePerGas == null && feeData.maxPriorityFeePerGas == null) {
- // Network doesn't know about EIP-1559 (and hence type)
- params = (0, lib$3.shallowCopy)(params);
- params.transaction = (0, lib$3.shallowCopy)(tx);
- delete params.transaction.type;
- }
- _a.label = 2;
- case 2:
- args = this.prepareRequest(method, params);
- if (args == null) {
- logger.throwError(method + " not implemented", lib.Logger.errors.NOT_IMPLEMENTED, { operation: method });
- }
- _a.label = 3;
- case 3:
- _a.trys.push([3, 5, , 6]);
- return [4 /*yield*/, this.send(args[0], args[1])];
- case 4: return [2 /*return*/, _a.sent()];
- case 5:
- error_4 = _a.sent();
- return [2 /*return*/, checkError(method, error_4, params)];
- case 6: return [2 /*return*/];
- }
- });
- });
- };
- JsonRpcProvider.prototype._startEvent = function (event) {
- if (event.tag === "pending") {
- this._startPending();
- }
- _super.prototype._startEvent.call(this, event);
- };
- JsonRpcProvider.prototype._startPending = function () {
- if (this._pendingFilter != null) {
- return;
- }
- var self = this;
- var pendingFilter = this.send("eth_newPendingTransactionFilter", []);
- this._pendingFilter = pendingFilter;
- pendingFilter.then(function (filterId) {
- function poll() {
- self.send("eth_getFilterChanges", [filterId]).then(function (hashes) {
- if (self._pendingFilter != pendingFilter) {
- return null;
- }
- var seq = Promise.resolve();
- hashes.forEach(function (hash) {
- // @TODO: This should be garbage collected at some point... How? When?
- self._emitted["t:" + hash.toLowerCase()] = "pending";
- seq = seq.then(function () {
- return self.getTransaction(hash).then(function (tx) {
- self.emit("pending", tx);
- return null;
- });
- });
- });
- return seq.then(function () {
- return timer(1000);
- });
- }).then(function () {
- if (self._pendingFilter != pendingFilter) {
- self.send("eth_uninstallFilter", [filterId]);
- return;
- }
- setTimeout(function () { poll(); }, 0);
- return null;
- }).catch(function (error) { });
- }
- poll();
- return filterId;
- }).catch(function (error) { });
- };
- JsonRpcProvider.prototype._stopEvent = function (event) {
- if (event.tag === "pending" && this.listenerCount("pending") === 0) {
- this._pendingFilter = null;
- }
- _super.prototype._stopEvent.call(this, event);
- };
- // Convert an ethers.js transaction into a JSON-RPC transaction
- // - gasLimit => gas
- // - All values hexlified
- // - All numeric values zero-striped
- // - All addresses are lowercased
- // NOTE: This allows a TransactionRequest, but all values should be resolved
- // before this is called
- // @TODO: This will likely be removed in future versions and prepareRequest
- // will be the preferred method for this.
- JsonRpcProvider.hexlifyTransaction = function (transaction, allowExtra) {
- // Check only allowed properties are given
- var allowed = (0, lib$3.shallowCopy)(allowedTransactionKeys);
- if (allowExtra) {
- for (var key in allowExtra) {
- if (allowExtra[key]) {
- allowed[key] = true;
- }
- }
- }
- (0, lib$3.checkProperties)(transaction, allowed);
- var result = {};
- // JSON-RPC now requires numeric values to be "quantity" values
- ["chainId", "gasLimit", "gasPrice", "type", "maxFeePerGas", "maxPriorityFeePerGas", "nonce", "value"].forEach(function (key) {
- if (transaction[key] == null) {
- return;
- }
- var value = (0, lib$1.hexValue)(transaction[key]);
- if (key === "gasLimit") {
- key = "gas";
- }
- result[key] = value;
- });
- ["from", "to", "data"].forEach(function (key) {
- if (transaction[key] == null) {
- return;
- }
- result[key] = (0, lib$1.hexlify)(transaction[key]);
- });
- if (transaction.accessList) {
- result["accessList"] = (0, lib$e.accessListify)(transaction.accessList);
- }
- return result;
- };
- return JsonRpcProvider;
- }(baseProvider.BaseProvider));
- exports.JsonRpcProvider = JsonRpcProvider;
- });
- var jsonRpcProvider$1 = /*@__PURE__*/getDefaultExportFromCjs(jsonRpcProvider);
- var browserWs = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.WebSocket = void 0;
- var WS = null;
- exports.WebSocket = WS;
- try {
- exports.WebSocket = WS = WebSocket;
- if (WS == null) {
- throw new Error("inject please");
- }
- }
- catch (error) {
- var logger_2 = new lib.Logger(_version$I.version);
- exports.WebSocket = WS = function () {
- logger_2.throwError("WebSockets not supported in this environment", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "new WebSocket()"
- });
- };
- }
- });
- var browserWs$1 = /*@__PURE__*/getDefaultExportFromCjs(browserWs);
- var websocketProvider = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.WebSocketProvider = void 0;
- var logger = new lib.Logger(_version$I.version);
- /**
- * Notes:
- *
- * This provider differs a bit from the polling providers. One main
- * difference is how it handles consistency. The polling providers
- * will stall responses to ensure a consistent state, while this
- * WebSocket provider assumes the connected backend will manage this.
- *
- * For example, if a polling provider emits an event which indicates
- * the event occurred in blockhash XXX, a call to fetch that block by
- * its hash XXX, if not present will retry until it is present. This
- * can occur when querying a pool of nodes that are mildly out of sync
- * with each other.
- */
- var NextId = 1;
- // For more info about the Real-time Event API see:
- // https://geth.ethereum.org/docs/rpc/pubsub
- var WebSocketProvider = /** @class */ (function (_super) {
- __extends(WebSocketProvider, _super);
- function WebSocketProvider(url, network) {
- var _this = this;
- // This will be added in the future; please open an issue to expedite
- if (network === "any") {
- logger.throwError("WebSocketProvider does not support 'any' network yet", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "network:any"
- });
- }
- if (typeof (url) === "string") {
- _this = _super.call(this, url, network) || this;
- }
- else {
- _this = _super.call(this, "_websocket", network) || this;
- }
- _this._pollingInterval = -1;
- _this._wsReady = false;
- if (typeof (url) === "string") {
- (0, lib$3.defineReadOnly)(_this, "_websocket", new browserWs.WebSocket(_this.connection.url));
- }
- else {
- (0, lib$3.defineReadOnly)(_this, "_websocket", url);
- }
- (0, lib$3.defineReadOnly)(_this, "_requests", {});
- (0, lib$3.defineReadOnly)(_this, "_subs", {});
- (0, lib$3.defineReadOnly)(_this, "_subIds", {});
- (0, lib$3.defineReadOnly)(_this, "_detectNetwork", _super.prototype.detectNetwork.call(_this));
- // Stall sending requests until the socket is open...
- _this.websocket.onopen = function () {
- _this._wsReady = true;
- Object.keys(_this._requests).forEach(function (id) {
- _this.websocket.send(_this._requests[id].payload);
- });
- };
- _this.websocket.onmessage = function (messageEvent) {
- var data = messageEvent.data;
- var result = JSON.parse(data);
- if (result.id != null) {
- var id = String(result.id);
- var request = _this._requests[id];
- delete _this._requests[id];
- if (result.result !== undefined) {
- request.callback(null, result.result);
- _this.emit("debug", {
- action: "response",
- request: JSON.parse(request.payload),
- response: result.result,
- provider: _this
- });
- }
- else {
- var error = null;
- if (result.error) {
- error = new Error(result.error.message || "unknown error");
- (0, lib$3.defineReadOnly)(error, "code", result.error.code || null);
- (0, lib$3.defineReadOnly)(error, "response", data);
- }
- else {
- error = new Error("unknown error");
- }
- request.callback(error, undefined);
- _this.emit("debug", {
- action: "response",
- error: error,
- request: JSON.parse(request.payload),
- provider: _this
- });
- }
- }
- else if (result.method === "eth_subscription") {
- // Subscription...
- var sub = _this._subs[result.params.subscription];
- if (sub) {
- //this.emit.apply(this, );
- sub.processFunc(result.params.result);
- }
- }
- else {
- console.warn("this should not happen");
- }
- };
- // This Provider does not actually poll, but we want to trigger
- // poll events for things that depend on them (like stalling for
- // block and transaction lookups)
- var fauxPoll = setInterval(function () {
- _this.emit("poll");
- }, 1000);
- if (fauxPoll.unref) {
- fauxPoll.unref();
- }
- return _this;
- }
- Object.defineProperty(WebSocketProvider.prototype, "websocket", {
- // Cannot narrow the type of _websocket, as that is not backwards compatible
- // so we add a getter and let the WebSocket be a public API.
- get: function () { return this._websocket; },
- enumerable: false,
- configurable: true
- });
- WebSocketProvider.prototype.detectNetwork = function () {
- return this._detectNetwork;
- };
- Object.defineProperty(WebSocketProvider.prototype, "pollingInterval", {
- get: function () {
- return 0;
- },
- set: function (value) {
- logger.throwError("cannot set polling interval on WebSocketProvider", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "setPollingInterval"
- });
- },
- enumerable: false,
- configurable: true
- });
- WebSocketProvider.prototype.resetEventsBlock = function (blockNumber) {
- logger.throwError("cannot reset events block on WebSocketProvider", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "resetEventBlock"
- });
- };
- WebSocketProvider.prototype.poll = function () {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- return [2 /*return*/, null];
- });
- });
- };
- Object.defineProperty(WebSocketProvider.prototype, "polling", {
- set: function (value) {
- if (!value) {
- return;
- }
- logger.throwError("cannot set polling on WebSocketProvider", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "setPolling"
- });
- },
- enumerable: false,
- configurable: true
- });
- WebSocketProvider.prototype.send = function (method, params) {
- var _this = this;
- var rid = NextId++;
- return new Promise(function (resolve, reject) {
- function callback(error, result) {
- if (error) {
- return reject(error);
- }
- return resolve(result);
- }
- var payload = JSON.stringify({
- method: method,
- params: params,
- id: rid,
- jsonrpc: "2.0"
- });
- _this.emit("debug", {
- action: "request",
- request: JSON.parse(payload),
- provider: _this
- });
- _this._requests[String(rid)] = { callback: callback, payload: payload };
- if (_this._wsReady) {
- _this.websocket.send(payload);
- }
- });
- };
- WebSocketProvider.defaultUrl = function () {
- return "ws:/\/localhost:8546";
- };
- WebSocketProvider.prototype._subscribe = function (tag, param, processFunc) {
- return __awaiter(this, void 0, void 0, function () {
- var subIdPromise, subId;
- var _this = this;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- subIdPromise = this._subIds[tag];
- if (subIdPromise == null) {
- subIdPromise = Promise.all(param).then(function (param) {
- return _this.send("eth_subscribe", param);
- });
- this._subIds[tag] = subIdPromise;
- }
- return [4 /*yield*/, subIdPromise];
- case 1:
- subId = _a.sent();
- this._subs[subId] = { tag: tag, processFunc: processFunc };
- return [2 /*return*/];
- }
- });
- });
- };
- WebSocketProvider.prototype._startEvent = function (event) {
- var _this = this;
- switch (event.type) {
- case "block":
- this._subscribe("block", ["newHeads"], function (result) {
- var blockNumber = lib$2.BigNumber.from(result.number).toNumber();
- _this._emitted.block = blockNumber;
- _this.emit("block", blockNumber);
- });
- break;
- case "pending":
- this._subscribe("pending", ["newPendingTransactions"], function (result) {
- _this.emit("pending", result);
- });
- break;
- case "filter":
- this._subscribe(event.tag, ["logs", this._getFilter(event.filter)], function (result) {
- if (result.removed == null) {
- result.removed = false;
- }
- _this.emit(event.filter, _this.formatter.filterLog(result));
- });
- break;
- case "tx": {
- var emitReceipt_1 = function (event) {
- var hash = event.hash;
- _this.getTransactionReceipt(hash).then(function (receipt) {
- if (!receipt) {
- return;
- }
- _this.emit(hash, receipt);
- });
- };
- // In case it is already mined
- emitReceipt_1(event);
- // To keep things simple, we start up a single newHeads subscription
- // to keep an eye out for transactions we are watching for.
- // Starting a subscription for an event (i.e. "tx") that is already
- // running is (basically) a nop.
- this._subscribe("tx", ["newHeads"], function (result) {
- _this._events.filter(function (e) { return (e.type === "tx"); }).forEach(emitReceipt_1);
- });
- break;
- }
- // Nothing is needed
- case "debug":
- case "poll":
- case "willPoll":
- case "didPoll":
- case "error":
- break;
- default:
- console.log("unhandled:", event);
- break;
- }
- };
- WebSocketProvider.prototype._stopEvent = function (event) {
- var _this = this;
- var tag = event.tag;
- if (event.type === "tx") {
- // There are remaining transaction event listeners
- if (this._events.filter(function (e) { return (e.type === "tx"); }).length) {
- return;
- }
- tag = "tx";
- }
- else if (this.listenerCount(event.event)) {
- // There are remaining event listeners
- return;
- }
- var subId = this._subIds[tag];
- if (!subId) {
- return;
- }
- delete this._subIds[tag];
- subId.then(function (subId) {
- if (!_this._subs[subId]) {
- return;
- }
- delete _this._subs[subId];
- _this.send("eth_unsubscribe", [subId]);
- });
- };
- WebSocketProvider.prototype.destroy = function () {
- return __awaiter(this, void 0, void 0, function () {
- var _this = this;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (!(this.websocket.readyState === browserWs.WebSocket.CONNECTING)) return [3 /*break*/, 2];
- return [4 /*yield*/, (new Promise(function (resolve) {
- _this.websocket.onopen = function () {
- resolve(true);
- };
- _this.websocket.onerror = function () {
- resolve(false);
- };
- }))];
- case 1:
- _a.sent();
- _a.label = 2;
- case 2:
- // Hangup
- // See: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes
- this.websocket.close(1000);
- return [2 /*return*/];
- }
- });
- });
- };
- return WebSocketProvider;
- }(jsonRpcProvider.JsonRpcProvider));
- exports.WebSocketProvider = WebSocketProvider;
- });
- var websocketProvider$1 = /*@__PURE__*/getDefaultExportFromCjs(websocketProvider);
- var urlJsonRpcProvider = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.UrlJsonRpcProvider = exports.StaticJsonRpcProvider = void 0;
- var logger = new lib.Logger(_version$I.version);
- // A StaticJsonRpcProvider is useful when you *know* for certain that
- // the backend will never change, as it never calls eth_chainId to
- // verify its backend. However, if the backend does change, the effects
- // are undefined and may include:
- // - inconsistent results
- // - locking up the UI
- // - block skew warnings
- // - wrong results
- // If the network is not explicit (i.e. auto-detection is expected), the
- // node MUST be running and available to respond to requests BEFORE this
- // is instantiated.
- var StaticJsonRpcProvider = /** @class */ (function (_super) {
- __extends(StaticJsonRpcProvider, _super);
- function StaticJsonRpcProvider() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- StaticJsonRpcProvider.prototype.detectNetwork = function () {
- return __awaiter(this, void 0, void 0, function () {
- var network;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- network = this.network;
- if (!(network == null)) return [3 /*break*/, 2];
- return [4 /*yield*/, _super.prototype.detectNetwork.call(this)];
- case 1:
- network = _a.sent();
- if (!network) {
- logger.throwError("no network detected", lib.Logger.errors.UNKNOWN_ERROR, {});
- }
- // If still not set, set it
- if (this._network == null) {
- // A static network does not support "any"
- (0, lib$3.defineReadOnly)(this, "_network", network);
- this.emit("network", network, null);
- }
- _a.label = 2;
- case 2: return [2 /*return*/, network];
- }
- });
- });
- };
- return StaticJsonRpcProvider;
- }(jsonRpcProvider.JsonRpcProvider));
- exports.StaticJsonRpcProvider = StaticJsonRpcProvider;
- var UrlJsonRpcProvider = /** @class */ (function (_super) {
- __extends(UrlJsonRpcProvider, _super);
- function UrlJsonRpcProvider(network, apiKey) {
- var _newTarget = this.constructor;
- var _this = this;
- logger.checkAbstract(_newTarget, UrlJsonRpcProvider);
- // Normalize the Network and API Key
- network = (0, lib$3.getStatic)(_newTarget, "getNetwork")(network);
- apiKey = (0, lib$3.getStatic)(_newTarget, "getApiKey")(apiKey);
- var connection = (0, lib$3.getStatic)(_newTarget, "getUrl")(network, apiKey);
- _this = _super.call(this, connection, network) || this;
- if (typeof (apiKey) === "string") {
- (0, lib$3.defineReadOnly)(_this, "apiKey", apiKey);
- }
- else if (apiKey != null) {
- Object.keys(apiKey).forEach(function (key) {
- (0, lib$3.defineReadOnly)(_this, key, apiKey[key]);
- });
- }
- return _this;
- }
- UrlJsonRpcProvider.prototype._startPending = function () {
- logger.warn("WARNING: API provider does not support pending filters");
- };
- UrlJsonRpcProvider.prototype.isCommunityResource = function () {
- return false;
- };
- UrlJsonRpcProvider.prototype.getSigner = function (address) {
- return logger.throwError("API provider does not support signing", lib.Logger.errors.UNSUPPORTED_OPERATION, { operation: "getSigner" });
- };
- UrlJsonRpcProvider.prototype.listAccounts = function () {
- return Promise.resolve([]);
- };
- // Return a defaultApiKey if null, otherwise validate the API key
- UrlJsonRpcProvider.getApiKey = function (apiKey) {
- return apiKey;
- };
- // Returns the url or connection for the given network and API key. The
- // API key will have been sanitized by the getApiKey first, so any validation
- // or transformations can be done there.
- UrlJsonRpcProvider.getUrl = function (network, apiKey) {
- return logger.throwError("not implemented; sub-classes must override getUrl", lib.Logger.errors.NOT_IMPLEMENTED, {
- operation: "getUrl"
- });
- };
- return UrlJsonRpcProvider;
- }(StaticJsonRpcProvider));
- exports.UrlJsonRpcProvider = UrlJsonRpcProvider;
- });
- var urlJsonRpcProvider$1 = /*@__PURE__*/getDefaultExportFromCjs(urlJsonRpcProvider);
- var alchemyProvider = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.AlchemyProvider = exports.AlchemyWebSocketProvider = void 0;
- var logger = new lib.Logger(_version$I.version);
- // This key was provided to ethers.js by Alchemy to be used by the
- // default provider, but it is recommended that for your own
- // production environments, that you acquire your own API key at:
- // https://dashboard.alchemyapi.io
- var defaultApiKey = "_gg7wSSi0KMBsdKnGVfHDueq6xMB9EkC";
- var AlchemyWebSocketProvider = /** @class */ (function (_super) {
- __extends(AlchemyWebSocketProvider, _super);
- function AlchemyWebSocketProvider(network, apiKey) {
- var _this = this;
- var provider = new AlchemyProvider(network, apiKey);
- var url = provider.connection.url.replace(/^http/i, "ws")
- .replace(".alchemyapi.", ".ws.alchemyapi.");
- _this = _super.call(this, url, provider.network) || this;
- (0, lib$3.defineReadOnly)(_this, "apiKey", provider.apiKey);
- return _this;
- }
- AlchemyWebSocketProvider.prototype.isCommunityResource = function () {
- return (this.apiKey === defaultApiKey);
- };
- return AlchemyWebSocketProvider;
- }(websocketProvider.WebSocketProvider));
- exports.AlchemyWebSocketProvider = AlchemyWebSocketProvider;
- var AlchemyProvider = /** @class */ (function (_super) {
- __extends(AlchemyProvider, _super);
- function AlchemyProvider() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- AlchemyProvider.getWebSocketProvider = function (network, apiKey) {
- return new AlchemyWebSocketProvider(network, apiKey);
- };
- AlchemyProvider.getApiKey = function (apiKey) {
- if (apiKey == null) {
- return defaultApiKey;
- }
- if (apiKey && typeof (apiKey) !== "string") {
- logger.throwArgumentError("invalid apiKey", "apiKey", apiKey);
- }
- return apiKey;
- };
- AlchemyProvider.getUrl = function (network, apiKey) {
- var host = null;
- switch (network.name) {
- case "homestead":
- host = "eth-mainnet.alchemyapi.io/v2/";
- break;
- case "ropsten":
- host = "eth-ropsten.alchemyapi.io/v2/";
- break;
- case "rinkeby":
- host = "eth-rinkeby.alchemyapi.io/v2/";
- break;
- case "goerli":
- host = "eth-goerli.alchemyapi.io/v2/";
- break;
- case "kovan":
- host = "eth-kovan.alchemyapi.io/v2/";
- break;
- case "matic":
- host = "polygon-mainnet.g.alchemy.com/v2/";
- break;
- case "maticmum":
- host = "polygon-mumbai.g.alchemy.com/v2/";
- break;
- case "arbitrum":
- host = "arb-mainnet.g.alchemy.com/v2/";
- break;
- case "arbitrum-rinkeby":
- host = "arb-rinkeby.g.alchemy.com/v2/";
- break;
- case "optimism":
- host = "opt-mainnet.g.alchemy.com/v2/";
- break;
- case "optimism-kovan":
- host = "opt-kovan.g.alchemy.com/v2/";
- break;
- default:
- logger.throwArgumentError("unsupported network", "network", arguments[0]);
- }
- return {
- allowGzip: true,
- url: ("https:/" + "/" + host + apiKey),
- throttleCallback: function (attempt, url) {
- if (apiKey === defaultApiKey) {
- (0, formatter.showThrottleMessage)();
- }
- return Promise.resolve(true);
- }
- };
- };
- AlchemyProvider.prototype.isCommunityResource = function () {
- return (this.apiKey === defaultApiKey);
- };
- return AlchemyProvider;
- }(urlJsonRpcProvider.UrlJsonRpcProvider));
- exports.AlchemyProvider = AlchemyProvider;
- });
- var alchemyProvider$1 = /*@__PURE__*/getDefaultExportFromCjs(alchemyProvider);
- var cloudflareProvider = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.CloudflareProvider = void 0;
- var logger = new lib.Logger(_version$I.version);
- var CloudflareProvider = /** @class */ (function (_super) {
- __extends(CloudflareProvider, _super);
- function CloudflareProvider() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- CloudflareProvider.getApiKey = function (apiKey) {
- if (apiKey != null) {
- logger.throwArgumentError("apiKey not supported for cloudflare", "apiKey", apiKey);
- }
- return null;
- };
- CloudflareProvider.getUrl = function (network, apiKey) {
- var host = null;
- switch (network.name) {
- case "homestead":
- host = "https://cloudflare-eth.com/";
- break;
- default:
- logger.throwArgumentError("unsupported network", "network", arguments[0]);
- }
- return host;
- };
- CloudflareProvider.prototype.perform = function (method, params) {
- return __awaiter(this, void 0, void 0, function () {
- var block;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (!(method === "getBlockNumber")) return [3 /*break*/, 2];
- return [4 /*yield*/, _super.prototype.perform.call(this, "getBlock", { blockTag: "latest" })];
- case 1:
- block = _a.sent();
- return [2 /*return*/, block.number];
- case 2: return [2 /*return*/, _super.prototype.perform.call(this, method, params)];
- }
- });
- });
- };
- return CloudflareProvider;
- }(urlJsonRpcProvider.UrlJsonRpcProvider));
- exports.CloudflareProvider = CloudflareProvider;
- });
- var cloudflareProvider$1 = /*@__PURE__*/getDefaultExportFromCjs(cloudflareProvider);
- var etherscanProvider = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.EtherscanProvider = void 0;
- var logger = new lib.Logger(_version$I.version);
- // The transaction has already been sanitized by the calls in Provider
- function getTransactionPostData(transaction) {
- var result = {};
- for (var key in transaction) {
- if (transaction[key] == null) {
- continue;
- }
- var value = transaction[key];
- if (key === "type" && value === 0) {
- continue;
- }
- // Quantity-types require no leading zero, unless 0
- if ({ type: true, gasLimit: true, gasPrice: true, maxFeePerGs: true, maxPriorityFeePerGas: true, nonce: true, value: true }[key]) {
- value = (0, lib$1.hexValue)((0, lib$1.hexlify)(value));
- }
- else if (key === "accessList") {
- value = "[" + (0, lib$e.accessListify)(value).map(function (set) {
- return "{address:\"" + set.address + "\",storageKeys:[\"" + set.storageKeys.join('","') + "\"]}";
- }).join(",") + "]";
- }
- else {
- value = (0, lib$1.hexlify)(value);
- }
- result[key] = value;
- }
- return result;
- }
- function getResult(result) {
- // getLogs, getHistory have weird success responses
- if (result.status == 0 && (result.message === "No records found" || result.message === "No transactions found")) {
- return result.result;
- }
- if (result.status != 1 || result.message != "OK") {
- var error = new Error("invalid response");
- error.result = JSON.stringify(result);
- if ((result.result || "").toLowerCase().indexOf("rate limit") >= 0) {
- error.throttleRetry = true;
- }
- throw error;
- }
- return result.result;
- }
- function getJsonResult(result) {
- // This response indicates we are being throttled
- if (result && result.status == 0 && result.message == "NOTOK" && (result.result || "").toLowerCase().indexOf("rate limit") >= 0) {
- var error = new Error("throttled response");
- error.result = JSON.stringify(result);
- error.throttleRetry = true;
- throw error;
- }
- if (result.jsonrpc != "2.0") {
- // @TODO: not any
- var error = new Error("invalid response");
- error.result = JSON.stringify(result);
- throw error;
- }
- if (result.error) {
- // @TODO: not any
- var error = new Error(result.error.message || "unknown error");
- if (result.error.code) {
- error.code = result.error.code;
- }
- if (result.error.data) {
- error.data = result.error.data;
- }
- throw error;
- }
- return result.result;
- }
- // The blockTag was normalized as a string by the Provider pre-perform operations
- function checkLogTag(blockTag) {
- if (blockTag === "pending") {
- throw new Error("pending not supported");
- }
- if (blockTag === "latest") {
- return blockTag;
- }
- return parseInt(blockTag.substring(2), 16);
- }
- var defaultApiKey = "9D13ZE7XSBTJ94N9BNJ2MA33VMAY2YPIRB";
- function checkError(method, error, transaction) {
- // Undo the "convenience" some nodes are attempting to prevent backwards
- // incompatibility; maybe for v6 consider forwarding reverts as errors
- if (method === "call" && error.code === lib.Logger.errors.SERVER_ERROR) {
- var e = error.error;
- // Etherscan keeps changing their string
- if (e && (e.message.match(/reverted/i) || e.message.match(/VM execution error/i))) {
- // Etherscan prefixes the data like "Reverted 0x1234"
- var data = e.data;
- if (data) {
- data = "0x" + data.replace(/^.*0x/i, "");
- }
- if ((0, lib$1.isHexString)(data)) {
- return data;
- }
- logger.throwError("missing revert data in call exception", lib.Logger.errors.CALL_EXCEPTION, {
- error: error,
- data: "0x"
- });
- }
- }
- // Get the message from any nested error structure
- var message = error.message;
- if (error.code === lib.Logger.errors.SERVER_ERROR) {
- if (error.error && typeof (error.error.message) === "string") {
- message = error.error.message;
- }
- else if (typeof (error.body) === "string") {
- message = error.body;
- }
- else if (typeof (error.responseText) === "string") {
- message = error.responseText;
- }
- }
- message = (message || "").toLowerCase();
- // "Insufficient funds. The account you tried to send transaction from does not have enough funds. Required 21464000000000 and got: 0"
- if (message.match(/insufficient funds/)) {
- logger.throwError("insufficient funds for intrinsic transaction cost", lib.Logger.errors.INSUFFICIENT_FUNDS, {
- error: error,
- method: method,
- transaction: transaction
- });
- }
- // "Transaction with the same hash was already imported."
- if (message.match(/same hash was already imported|transaction nonce is too low|nonce too low/)) {
- logger.throwError("nonce has already been used", lib.Logger.errors.NONCE_EXPIRED, {
- error: error,
- method: method,
- transaction: transaction
- });
- }
- // "Transaction gas price is too low. There is another transaction with same nonce in the queue. Try increasing the gas price or incrementing the nonce."
- if (message.match(/another transaction with same nonce/)) {
- logger.throwError("replacement fee too low", lib.Logger.errors.REPLACEMENT_UNDERPRICED, {
- error: error,
- method: method,
- transaction: transaction
- });
- }
- if (message.match(/execution failed due to an exception|execution reverted/)) {
- logger.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", lib.Logger.errors.UNPREDICTABLE_GAS_LIMIT, {
- error: error,
- method: method,
- transaction: transaction
- });
- }
- throw error;
- }
- var EtherscanProvider = /** @class */ (function (_super) {
- __extends(EtherscanProvider, _super);
- function EtherscanProvider(network, apiKey) {
- var _newTarget = this.constructor;
- var _this = this;
- logger.checkNew(_newTarget, EtherscanProvider);
- _this = _super.call(this, network) || this;
- (0, lib$3.defineReadOnly)(_this, "baseUrl", _this.getBaseUrl());
- (0, lib$3.defineReadOnly)(_this, "apiKey", apiKey || defaultApiKey);
- return _this;
- }
- EtherscanProvider.prototype.getBaseUrl = function () {
- switch (this.network ? this.network.name : "invalid") {
- case "homestead":
- return "https:/\/api.etherscan.io";
- case "ropsten":
- return "https:/\/api-ropsten.etherscan.io";
- case "rinkeby":
- return "https:/\/api-rinkeby.etherscan.io";
- case "kovan":
- return "https:/\/api-kovan.etherscan.io";
- case "goerli":
- return "https:/\/api-goerli.etherscan.io";
- default:
- }
- return logger.throwArgumentError("unsupported network", "network", name);
- };
- EtherscanProvider.prototype.getUrl = function (module, params) {
- var query = Object.keys(params).reduce(function (accum, key) {
- var value = params[key];
- if (value != null) {
- accum += "&" + key + "=" + value;
- }
- return accum;
- }, "");
- var apiKey = ((this.apiKey) ? "&apikey=" + this.apiKey : "");
- return this.baseUrl + "/api?module=" + module + query + apiKey;
- };
- EtherscanProvider.prototype.getPostUrl = function () {
- return this.baseUrl + "/api";
- };
- EtherscanProvider.prototype.getPostData = function (module, params) {
- params.module = module;
- params.apikey = this.apiKey;
- return params;
- };
- EtherscanProvider.prototype.fetch = function (module, params, post) {
- return __awaiter(this, void 0, void 0, function () {
- var url, payload, procFunc, connection, payloadStr, result;
- var _this = this;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- url = (post ? this.getPostUrl() : this.getUrl(module, params));
- payload = (post ? this.getPostData(module, params) : null);
- procFunc = (module === "proxy") ? getJsonResult : getResult;
- this.emit("debug", {
- action: "request",
- request: url,
- provider: this
- });
- connection = {
- url: url,
- throttleSlotInterval: 1000,
- throttleCallback: function (attempt, url) {
- if (_this.isCommunityResource()) {
- (0, formatter.showThrottleMessage)();
- }
- return Promise.resolve(true);
- }
- };
- payloadStr = null;
- if (payload) {
- connection.headers = { "content-type": "application/x-www-form-urlencoded; charset=UTF-8" };
- payloadStr = Object.keys(payload).map(function (key) {
- return key + "=" + payload[key];
- }).join("&");
- }
- return [4 /*yield*/, (0, lib$q.fetchJson)(connection, payloadStr, procFunc || getJsonResult)];
- case 1:
- result = _a.sent();
- this.emit("debug", {
- action: "response",
- request: url,
- response: (0, lib$3.deepCopy)(result),
- provider: this
- });
- return [2 /*return*/, result];
- }
- });
- });
- };
- EtherscanProvider.prototype.detectNetwork = function () {
- return __awaiter(this, void 0, void 0, function () {
- return __generator(this, function (_a) {
- return [2 /*return*/, this.network];
- });
- });
- };
- EtherscanProvider.prototype.perform = function (method, params) {
- return __awaiter(this, void 0, void 0, function () {
- var _a, postData, error_1, postData, error_2, args, topic0, logs, blocks, i, log, block, _b;
- return __generator(this, function (_c) {
- switch (_c.label) {
- case 0:
- _a = method;
- switch (_a) {
- case "getBlockNumber": return [3 /*break*/, 1];
- case "getGasPrice": return [3 /*break*/, 2];
- case "getBalance": return [3 /*break*/, 3];
- case "getTransactionCount": return [3 /*break*/, 4];
- case "getCode": return [3 /*break*/, 5];
- case "getStorageAt": return [3 /*break*/, 6];
- case "sendTransaction": return [3 /*break*/, 7];
- case "getBlock": return [3 /*break*/, 8];
- case "getTransaction": return [3 /*break*/, 9];
- case "getTransactionReceipt": return [3 /*break*/, 10];
- case "call": return [3 /*break*/, 11];
- case "estimateGas": return [3 /*break*/, 15];
- case "getLogs": return [3 /*break*/, 19];
- case "getEtherPrice": return [3 /*break*/, 26];
- }
- return [3 /*break*/, 28];
- case 1: return [2 /*return*/, this.fetch("proxy", { action: "eth_blockNumber" })];
- case 2: return [2 /*return*/, this.fetch("proxy", { action: "eth_gasPrice" })];
- case 3:
- // Returns base-10 result
- return [2 /*return*/, this.fetch("account", {
- action: "balance",
- address: params.address,
- tag: params.blockTag
- })];
- case 4: return [2 /*return*/, this.fetch("proxy", {
- action: "eth_getTransactionCount",
- address: params.address,
- tag: params.blockTag
- })];
- case 5: return [2 /*return*/, this.fetch("proxy", {
- action: "eth_getCode",
- address: params.address,
- tag: params.blockTag
- })];
- case 6: return [2 /*return*/, this.fetch("proxy", {
- action: "eth_getStorageAt",
- address: params.address,
- position: params.position,
- tag: params.blockTag
- })];
- case 7: return [2 /*return*/, this.fetch("proxy", {
- action: "eth_sendRawTransaction",
- hex: params.signedTransaction
- }, true).catch(function (error) {
- return checkError("sendTransaction", error, params.signedTransaction);
- })];
- case 8:
- if (params.blockTag) {
- return [2 /*return*/, this.fetch("proxy", {
- action: "eth_getBlockByNumber",
- tag: params.blockTag,
- boolean: (params.includeTransactions ? "true" : "false")
- })];
- }
- throw new Error("getBlock by blockHash not implemented");
- case 9: return [2 /*return*/, this.fetch("proxy", {
- action: "eth_getTransactionByHash",
- txhash: params.transactionHash
- })];
- case 10: return [2 /*return*/, this.fetch("proxy", {
- action: "eth_getTransactionReceipt",
- txhash: params.transactionHash
- })];
- case 11:
- if (params.blockTag !== "latest") {
- throw new Error("EtherscanProvider does not support blockTag for call");
- }
- postData = getTransactionPostData(params.transaction);
- postData.module = "proxy";
- postData.action = "eth_call";
- _c.label = 12;
- case 12:
- _c.trys.push([12, 14, , 15]);
- return [4 /*yield*/, this.fetch("proxy", postData, true)];
- case 13: return [2 /*return*/, _c.sent()];
- case 14:
- error_1 = _c.sent();
- return [2 /*return*/, checkError("call", error_1, params.transaction)];
- case 15:
- postData = getTransactionPostData(params.transaction);
- postData.module = "proxy";
- postData.action = "eth_estimateGas";
- _c.label = 16;
- case 16:
- _c.trys.push([16, 18, , 19]);
- return [4 /*yield*/, this.fetch("proxy", postData, true)];
- case 17: return [2 /*return*/, _c.sent()];
- case 18:
- error_2 = _c.sent();
- return [2 /*return*/, checkError("estimateGas", error_2, params.transaction)];
- case 19:
- args = { action: "getLogs" };
- if (params.filter.fromBlock) {
- args.fromBlock = checkLogTag(params.filter.fromBlock);
- }
- if (params.filter.toBlock) {
- args.toBlock = checkLogTag(params.filter.toBlock);
- }
- if (params.filter.address) {
- args.address = params.filter.address;
- }
- // @TODO: We can handle slightly more complicated logs using the logs API
- if (params.filter.topics && params.filter.topics.length > 0) {
- if (params.filter.topics.length > 1) {
- logger.throwError("unsupported topic count", lib.Logger.errors.UNSUPPORTED_OPERATION, { topics: params.filter.topics });
- }
- if (params.filter.topics.length === 1) {
- topic0 = params.filter.topics[0];
- if (typeof (topic0) !== "string" || topic0.length !== 66) {
- logger.throwError("unsupported topic format", lib.Logger.errors.UNSUPPORTED_OPERATION, { topic0: topic0 });
- }
- args.topic0 = topic0;
- }
- }
- return [4 /*yield*/, this.fetch("logs", args)];
- case 20:
- logs = _c.sent();
- blocks = {};
- i = 0;
- _c.label = 21;
- case 21:
- if (!(i < logs.length)) return [3 /*break*/, 25];
- log = logs[i];
- if (log.blockHash != null) {
- return [3 /*break*/, 24];
- }
- if (!(blocks[log.blockNumber] == null)) return [3 /*break*/, 23];
- return [4 /*yield*/, this.getBlock(log.blockNumber)];
- case 22:
- block = _c.sent();
- if (block) {
- blocks[log.blockNumber] = block.hash;
- }
- _c.label = 23;
- case 23:
- log.blockHash = blocks[log.blockNumber];
- _c.label = 24;
- case 24:
- i++;
- return [3 /*break*/, 21];
- case 25: return [2 /*return*/, logs];
- case 26:
- if (this.network.name !== "homestead") {
- return [2 /*return*/, 0.0];
- }
- _b = parseFloat;
- return [4 /*yield*/, this.fetch("stats", { action: "ethprice" })];
- case 27: return [2 /*return*/, _b.apply(void 0, [(_c.sent()).ethusd])];
- case 28: return [3 /*break*/, 29];
- case 29: return [2 /*return*/, _super.prototype.perform.call(this, method, params)];
- }
- });
- });
- };
- // Note: The `page` page parameter only allows pagination within the
- // 10,000 window available without a page and offset parameter
- // Error: Result window is too large, PageNo x Offset size must
- // be less than or equal to 10000
- EtherscanProvider.prototype.getHistory = function (addressOrName, startBlock, endBlock) {
- return __awaiter(this, void 0, void 0, function () {
- var params, result;
- var _a;
- var _this = this;
- return __generator(this, function (_b) {
- switch (_b.label) {
- case 0:
- _a = {
- action: "txlist"
- };
- return [4 /*yield*/, this.resolveName(addressOrName)];
- case 1:
- params = (_a.address = (_b.sent()),
- _a.startblock = ((startBlock == null) ? 0 : startBlock),
- _a.endblock = ((endBlock == null) ? 99999999 : endBlock),
- _a.sort = "asc",
- _a);
- return [4 /*yield*/, this.fetch("account", params)];
- case 2:
- result = _b.sent();
- return [2 /*return*/, result.map(function (tx) {
- ["contractAddress", "to"].forEach(function (key) {
- if (tx[key] == "") {
- delete tx[key];
- }
- });
- if (tx.creates == null && tx.contractAddress != null) {
- tx.creates = tx.contractAddress;
- }
- var item = _this.formatter.transactionResponse(tx);
- if (tx.timeStamp) {
- item.timestamp = parseInt(tx.timeStamp);
- }
- return item;
- })];
- }
- });
- });
- };
- EtherscanProvider.prototype.isCommunityResource = function () {
- return (this.apiKey === defaultApiKey);
- };
- return EtherscanProvider;
- }(baseProvider.BaseProvider));
- exports.EtherscanProvider = EtherscanProvider;
- });
- var etherscanProvider$1 = /*@__PURE__*/getDefaultExportFromCjs(etherscanProvider);
- var fallbackProvider = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (_) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.FallbackProvider = void 0;
- var logger = new lib.Logger(_version$I.version);
- function now() { return (new Date()).getTime(); }
- // Returns to network as long as all agree, or null if any is null.
- // Throws an error if any two networks do not match.
- function checkNetworks(networks) {
- var result = null;
- for (var i = 0; i < networks.length; i++) {
- var network = networks[i];
- // Null! We do not know our network; bail.
- if (network == null) {
- return null;
- }
- if (result) {
- // Make sure the network matches the previous networks
- if (!(result.name === network.name && result.chainId === network.chainId &&
- ((result.ensAddress === network.ensAddress) || (result.ensAddress == null && network.ensAddress == null)))) {
- logger.throwArgumentError("provider mismatch", "networks", networks);
- }
- }
- else {
- result = network;
- }
- }
- return result;
- }
- function median(values, maxDelta) {
- values = values.slice().sort();
- var middle = Math.floor(values.length / 2);
- // Odd length; take the middle
- if (values.length % 2) {
- return values[middle];
- }
- // Even length; take the average of the two middle
- var a = values[middle - 1], b = values[middle];
- if (maxDelta != null && Math.abs(a - b) > maxDelta) {
- return null;
- }
- return (a + b) / 2;
- }
- function serialize(value) {
- if (value === null) {
- return "null";
- }
- else if (typeof (value) === "number" || typeof (value) === "boolean") {
- return JSON.stringify(value);
- }
- else if (typeof (value) === "string") {
- return value;
- }
- else if (lib$2.BigNumber.isBigNumber(value)) {
- return value.toString();
- }
- else if (Array.isArray(value)) {
- return JSON.stringify(value.map(function (i) { return serialize(i); }));
- }
- else if (typeof (value) === "object") {
- var keys = Object.keys(value);
- keys.sort();
- return "{" + keys.map(function (key) {
- var v = value[key];
- if (typeof (v) === "function") {
- v = "[function]";
- }
- else {
- v = serialize(v);
- }
- return JSON.stringify(key) + ":" + v;
- }).join(",") + "}";
- }
- throw new Error("unknown value type: " + typeof (value));
- }
- // Next request ID to use for emitting debug info
- var nextRid = 1;
- ;
- function stall(duration) {
- var cancel = null;
- var timer = null;
- var promise = (new Promise(function (resolve) {
- cancel = function () {
- if (timer) {
- clearTimeout(timer);
- timer = null;
- }
- resolve();
- };
- timer = setTimeout(cancel, duration);
- }));
- var wait = function (func) {
- promise = promise.then(func);
- return promise;
- };
- function getPromise() {
- return promise;
- }
- return { cancel: cancel, getPromise: getPromise, wait: wait };
- }
- var ForwardErrors = [
- lib.Logger.errors.CALL_EXCEPTION,
- lib.Logger.errors.INSUFFICIENT_FUNDS,
- lib.Logger.errors.NONCE_EXPIRED,
- lib.Logger.errors.REPLACEMENT_UNDERPRICED,
- lib.Logger.errors.UNPREDICTABLE_GAS_LIMIT
- ];
- var ForwardProperties = [
- "address",
- "args",
- "errorArgs",
- "errorSignature",
- "method",
- "transaction",
- ];
- ;
- function exposeDebugConfig(config, now) {
- var result = {
- weight: config.weight
- };
- Object.defineProperty(result, "provider", { get: function () { return config.provider; } });
- if (config.start) {
- result.start = config.start;
- }
- if (now) {
- result.duration = (now - config.start);
- }
- if (config.done) {
- if (config.error) {
- result.error = config.error;
- }
- else {
- result.result = config.result || null;
- }
- }
- return result;
- }
- function normalizedTally(normalize, quorum) {
- return function (configs) {
- // Count the votes for each result
- var tally = {};
- configs.forEach(function (c) {
- var value = normalize(c.result);
- if (!tally[value]) {
- tally[value] = { count: 0, result: c.result };
- }
- tally[value].count++;
- });
- // Check for a quorum on any given result
- var keys = Object.keys(tally);
- for (var i = 0; i < keys.length; i++) {
- var check = tally[keys[i]];
- if (check.count >= quorum) {
- return check.result;
- }
- }
- // No quroum
- return undefined;
- };
- }
- function getProcessFunc(provider, method, params) {
- var normalize = serialize;
- switch (method) {
- case "getBlockNumber":
- // Return the median value, unless there is (median + 1) is also
- // present, in which case that is probably true and the median
- // is going to be stale soon. In the event of a malicious node,
- // the lie will be true soon enough.
- return function (configs) {
- var values = configs.map(function (c) { return c.result; });
- // Get the median block number
- var blockNumber = median(configs.map(function (c) { return c.result; }), 2);
- if (blockNumber == null) {
- return undefined;
- }
- blockNumber = Math.ceil(blockNumber);
- // If the next block height is present, its prolly safe to use
- if (values.indexOf(blockNumber + 1) >= 0) {
- blockNumber++;
- }
- // Don't ever roll back the blockNumber
- if (blockNumber >= provider._highestBlockNumber) {
- provider._highestBlockNumber = blockNumber;
- }
- return provider._highestBlockNumber;
- };
- case "getGasPrice":
- // Return the middle (round index up) value, similar to median
- // but do not average even entries and choose the higher.
- // Malicious actors must compromise 50% of the nodes to lie.
- return function (configs) {
- var values = configs.map(function (c) { return c.result; });
- values.sort();
- return values[Math.floor(values.length / 2)];
- };
- case "getEtherPrice":
- // Returns the median price. Malicious actors must compromise at
- // least 50% of the nodes to lie (in a meaningful way).
- return function (configs) {
- return median(configs.map(function (c) { return c.result; }));
- };
- // No additional normalizing required; serialize is enough
- case "getBalance":
- case "getTransactionCount":
- case "getCode":
- case "getStorageAt":
- case "call":
- case "estimateGas":
- case "getLogs":
- break;
- // We drop the confirmations from transactions as it is approximate
- case "getTransaction":
- case "getTransactionReceipt":
- normalize = function (tx) {
- if (tx == null) {
- return null;
- }
- tx = (0, lib$3.shallowCopy)(tx);
- tx.confirmations = -1;
- return serialize(tx);
- };
- break;
- // We drop the confirmations from transactions as it is approximate
- case "getBlock":
- // We drop the confirmations from transactions as it is approximate
- if (params.includeTransactions) {
- normalize = function (block) {
- if (block == null) {
- return null;
- }
- block = (0, lib$3.shallowCopy)(block);
- block.transactions = block.transactions.map(function (tx) {
- tx = (0, lib$3.shallowCopy)(tx);
- tx.confirmations = -1;
- return tx;
- });
- return serialize(block);
- };
- }
- else {
- normalize = function (block) {
- if (block == null) {
- return null;
- }
- return serialize(block);
- };
- }
- break;
- default:
- throw new Error("unknown method: " + method);
- }
- // Return the result if and only if the expected quorum is
- // satisfied and agreed upon for the final result.
- return normalizedTally(normalize, provider.quorum);
- }
- // If we are doing a blockTag query, we need to make sure the backend is
- // caught up to the FallbackProvider, before sending a request to it.
- function waitForSync(config, blockNumber) {
- return __awaiter(this, void 0, void 0, function () {
- var provider;
- return __generator(this, function (_a) {
- provider = (config.provider);
- if ((provider.blockNumber != null && provider.blockNumber >= blockNumber) || blockNumber === -1) {
- return [2 /*return*/, provider];
- }
- return [2 /*return*/, (0, lib$q.poll)(function () {
- return new Promise(function (resolve, reject) {
- setTimeout(function () {
- // We are synced
- if (provider.blockNumber >= blockNumber) {
- return resolve(provider);
- }
- // We're done; just quit
- if (config.cancelled) {
- return resolve(null);
- }
- // Try again, next block
- return resolve(undefined);
- }, 0);
- });
- }, { oncePoll: provider })];
- });
- });
- }
- function getRunner(config, currentBlockNumber, method, params) {
- return __awaiter(this, void 0, void 0, function () {
- var provider, _a, filter;
- return __generator(this, function (_b) {
- switch (_b.label) {
- case 0:
- provider = config.provider;
- _a = method;
- switch (_a) {
- case "getBlockNumber": return [3 /*break*/, 1];
- case "getGasPrice": return [3 /*break*/, 1];
- case "getEtherPrice": return [3 /*break*/, 2];
- case "getBalance": return [3 /*break*/, 3];
- case "getTransactionCount": return [3 /*break*/, 3];
- case "getCode": return [3 /*break*/, 3];
- case "getStorageAt": return [3 /*break*/, 6];
- case "getBlock": return [3 /*break*/, 9];
- case "call": return [3 /*break*/, 12];
- case "estimateGas": return [3 /*break*/, 12];
- case "getTransaction": return [3 /*break*/, 15];
- case "getTransactionReceipt": return [3 /*break*/, 15];
- case "getLogs": return [3 /*break*/, 16];
- }
- return [3 /*break*/, 19];
- case 1: return [2 /*return*/, provider[method]()];
- case 2:
- if (provider.getEtherPrice) {
- return [2 /*return*/, provider.getEtherPrice()];
- }
- return [3 /*break*/, 19];
- case 3:
- if (!(params.blockTag && (0, lib$1.isHexString)(params.blockTag))) return [3 /*break*/, 5];
- return [4 /*yield*/, waitForSync(config, currentBlockNumber)];
- case 4:
- provider = _b.sent();
- _b.label = 5;
- case 5: return [2 /*return*/, provider[method](params.address, params.blockTag || "latest")];
- case 6:
- if (!(params.blockTag && (0, lib$1.isHexString)(params.blockTag))) return [3 /*break*/, 8];
- return [4 /*yield*/, waitForSync(config, currentBlockNumber)];
- case 7:
- provider = _b.sent();
- _b.label = 8;
- case 8: return [2 /*return*/, provider.getStorageAt(params.address, params.position, params.blockTag || "latest")];
- case 9:
- if (!(params.blockTag && (0, lib$1.isHexString)(params.blockTag))) return [3 /*break*/, 11];
- return [4 /*yield*/, waitForSync(config, currentBlockNumber)];
- case 10:
- provider = _b.sent();
- _b.label = 11;
- case 11: return [2 /*return*/, provider[(params.includeTransactions ? "getBlockWithTransactions" : "getBlock")](params.blockTag || params.blockHash)];
- case 12:
- if (!(params.blockTag && (0, lib$1.isHexString)(params.blockTag))) return [3 /*break*/, 14];
- return [4 /*yield*/, waitForSync(config, currentBlockNumber)];
- case 13:
- provider = _b.sent();
- _b.label = 14;
- case 14: return [2 /*return*/, provider[method](params.transaction)];
- case 15: return [2 /*return*/, provider[method](params.transactionHash)];
- case 16:
- filter = params.filter;
- if (!((filter.fromBlock && (0, lib$1.isHexString)(filter.fromBlock)) || (filter.toBlock && (0, lib$1.isHexString)(filter.toBlock)))) return [3 /*break*/, 18];
- return [4 /*yield*/, waitForSync(config, currentBlockNumber)];
- case 17:
- provider = _b.sent();
- _b.label = 18;
- case 18: return [2 /*return*/, provider.getLogs(filter)];
- case 19: return [2 /*return*/, logger.throwError("unknown method error", lib.Logger.errors.UNKNOWN_ERROR, {
- method: method,
- params: params
- })];
- }
- });
- });
- }
- var FallbackProvider = /** @class */ (function (_super) {
- __extends(FallbackProvider, _super);
- function FallbackProvider(providers, quorum) {
- var _newTarget = this.constructor;
- var _this = this;
- logger.checkNew(_newTarget, FallbackProvider);
- if (providers.length === 0) {
- logger.throwArgumentError("missing providers", "providers", providers);
- }
- var providerConfigs = providers.map(function (configOrProvider, index) {
- if (lib$b.Provider.isProvider(configOrProvider)) {
- var stallTimeout = (0, formatter.isCommunityResource)(configOrProvider) ? 2000 : 750;
- var priority = 1;
- return Object.freeze({ provider: configOrProvider, weight: 1, stallTimeout: stallTimeout, priority: priority });
- }
- var config = (0, lib$3.shallowCopy)(configOrProvider);
- if (config.priority == null) {
- config.priority = 1;
- }
- if (config.stallTimeout == null) {
- config.stallTimeout = (0, formatter.isCommunityResource)(configOrProvider) ? 2000 : 750;
- }
- if (config.weight == null) {
- config.weight = 1;
- }
- var weight = config.weight;
- if (weight % 1 || weight > 512 || weight < 1) {
- logger.throwArgumentError("invalid weight; must be integer in [1, 512]", "providers[" + index + "].weight", weight);
- }
- return Object.freeze(config);
- });
- var total = providerConfigs.reduce(function (accum, c) { return (accum + c.weight); }, 0);
- if (quorum == null) {
- quorum = total / 2;
- }
- else if (quorum > total) {
- logger.throwArgumentError("quorum will always fail; larger than total weight", "quorum", quorum);
- }
- // Are all providers' networks are known
- var networkOrReady = checkNetworks(providerConfigs.map(function (c) { return (c.provider).network; }));
- // Not all networks are known; we must stall
- if (networkOrReady == null) {
- networkOrReady = new Promise(function (resolve, reject) {
- setTimeout(function () {
- _this.detectNetwork().then(resolve, reject);
- }, 0);
- });
- }
- _this = _super.call(this, networkOrReady) || this;
- // Preserve a copy, so we do not get mutated
- (0, lib$3.defineReadOnly)(_this, "providerConfigs", Object.freeze(providerConfigs));
- (0, lib$3.defineReadOnly)(_this, "quorum", quorum);
- _this._highestBlockNumber = -1;
- return _this;
- }
- FallbackProvider.prototype.detectNetwork = function () {
- return __awaiter(this, void 0, void 0, function () {
- var networks;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 /*yield*/, Promise.all(this.providerConfigs.map(function (c) { return c.provider.getNetwork(); }))];
- case 1:
- networks = _a.sent();
- return [2 /*return*/, checkNetworks(networks)];
- }
- });
- });
- };
- FallbackProvider.prototype.perform = function (method, params) {
- return __awaiter(this, void 0, void 0, function () {
- var results, i_1, result, processFunc, configs, currentBlockNumber, i, first, _loop_1, this_1, state_1;
- var _this = this;
- return __generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (!(method === "sendTransaction")) return [3 /*break*/, 2];
- return [4 /*yield*/, Promise.all(this.providerConfigs.map(function (c) {
- return c.provider.sendTransaction(params.signedTransaction).then(function (result) {
- return result.hash;
- }, function (error) {
- return error;
- });
- }))];
- case 1:
- results = _a.sent();
- // Any success is good enough (other errors are likely "already seen" errors
- for (i_1 = 0; i_1 < results.length; i_1++) {
- result = results[i_1];
- if (typeof (result) === "string") {
- return [2 /*return*/, result];
- }
- }
- // They were all an error; pick the first error
- throw results[0];
- case 2:
- if (!(this._highestBlockNumber === -1 && method !== "getBlockNumber")) return [3 /*break*/, 4];
- return [4 /*yield*/, this.getBlockNumber()];
- case 3:
- _a.sent();
- _a.label = 4;
- case 4:
- processFunc = getProcessFunc(this, method, params);
- configs = (0, lib$l.shuffled)(this.providerConfigs.map(lib$3.shallowCopy));
- configs.sort(function (a, b) { return (a.priority - b.priority); });
- currentBlockNumber = this._highestBlockNumber;
- i = 0;
- first = true;
- _loop_1 = function () {
- var t0, inflightWeight, _loop_2, waiting, results, result, errors;
- return __generator(this, function (_b) {
- switch (_b.label) {
- case 0:
- t0 = now();
- inflightWeight = configs.filter(function (c) { return (c.runner && ((t0 - c.start) < c.stallTimeout)); })
- .reduce(function (accum, c) { return (accum + c.weight); }, 0);
- _loop_2 = function () {
- var config = configs[i++];
- var rid = nextRid++;
- config.start = now();
- config.staller = stall(config.stallTimeout);
- config.staller.wait(function () { config.staller = null; });
- config.runner = getRunner(config, currentBlockNumber, method, params).then(function (result) {
- config.done = true;
- config.result = result;
- if (_this.listenerCount("debug")) {
- _this.emit("debug", {
- action: "request",
- rid: rid,
- backend: exposeDebugConfig(config, now()),
- request: { method: method, params: (0, lib$3.deepCopy)(params) },
- provider: _this
- });
- }
- }, function (error) {
- config.done = true;
- config.error = error;
- if (_this.listenerCount("debug")) {
- _this.emit("debug", {
- action: "request",
- rid: rid,
- backend: exposeDebugConfig(config, now()),
- request: { method: method, params: (0, lib$3.deepCopy)(params) },
- provider: _this
- });
- }
- });
- if (this_1.listenerCount("debug")) {
- this_1.emit("debug", {
- action: "request",
- rid: rid,
- backend: exposeDebugConfig(config, null),
- request: { method: method, params: (0, lib$3.deepCopy)(params) },
- provider: this_1
- });
- }
- inflightWeight += config.weight;
- };
- // Start running enough to meet quorum
- while (inflightWeight < this_1.quorum && i < configs.length) {
- _loop_2();
- }
- waiting = [];
- configs.forEach(function (c) {
- if (c.done || !c.runner) {
- return;
- }
- waiting.push(c.runner);
- if (c.staller) {
- waiting.push(c.staller.getPromise());
- }
- });
- if (!waiting.length) return [3 /*break*/, 2];
- return [4 /*yield*/, Promise.race(waiting)];
- case 1:
- _b.sent();
- _b.label = 2;
- case 2:
- results = configs.filter(function (c) { return (c.done && c.error == null); });
- if (!(results.length >= this_1.quorum)) return [3 /*break*/, 5];
- result = processFunc(results);
- if (result !== undefined) {
- // Shut down any stallers
- configs.forEach(function (c) {
- if (c.staller) {
- c.staller.cancel();
- }
- c.cancelled = true;
- });
- return [2 /*return*/, { value: result }];
- }
- if (!!first) return [3 /*break*/, 4];
- return [4 /*yield*/, stall(100).getPromise()];
- case 3:
- _b.sent();
- _b.label = 4;
- case 4:
- first = false;
- _b.label = 5;
- case 5:
- errors = configs.reduce(function (accum, c) {
- if (!c.done || c.error == null) {
- return accum;
- }
- var code = (c.error).code;
- if (ForwardErrors.indexOf(code) >= 0) {
- if (!accum[code]) {
- accum[code] = { error: c.error, weight: 0 };
- }
- accum[code].weight += c.weight;
- }
- return accum;
- }, ({}));
- Object.keys(errors).forEach(function (errorCode) {
- var tally = errors[errorCode];
- if (tally.weight < _this.quorum) {
- return;
- }
- // Shut down any stallers
- configs.forEach(function (c) {
- if (c.staller) {
- c.staller.cancel();
- }
- c.cancelled = true;
- });
- var e = (tally.error);
- var props = {};
- ForwardProperties.forEach(function (name) {
- if (e[name] == null) {
- return;
- }
- props[name] = e[name];
- });
- logger.throwError(e.reason || e.message, errorCode, props);
- });
- // All configs have run to completion; we will never get more data
- if (configs.filter(function (c) { return !c.done; }).length === 0) {
- return [2 /*return*/, "break"];
- }
- return [2 /*return*/];
- }
- });
- };
- this_1 = this;
- _a.label = 5;
- case 5:
- if (!true) return [3 /*break*/, 7];
- return [5 /*yield**/, _loop_1()];
- case 6:
- state_1 = _a.sent();
- if (typeof state_1 === "object")
- return [2 /*return*/, state_1.value];
- if (state_1 === "break")
- return [3 /*break*/, 7];
- return [3 /*break*/, 5];
- case 7:
- // Shut down any stallers; shouldn't be any
- configs.forEach(function (c) {
- if (c.staller) {
- c.staller.cancel();
- }
- c.cancelled = true;
- });
- return [2 /*return*/, logger.throwError("failed to meet quorum", lib.Logger.errors.SERVER_ERROR, {
- method: method,
- params: params,
- //results: configs.map((c) => c.result),
- //errors: configs.map((c) => c.error),
- results: configs.map(function (c) { return exposeDebugConfig(c); }),
- provider: this
- })];
- }
- });
- });
- };
- return FallbackProvider;
- }(baseProvider.BaseProvider));
- exports.FallbackProvider = FallbackProvider;
- });
- var fallbackProvider$1 = /*@__PURE__*/getDefaultExportFromCjs(fallbackProvider);
- var browserIpcProvider = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.IpcProvider = void 0;
- var IpcProvider = null;
- exports.IpcProvider = IpcProvider;
- });
- var browserIpcProvider$1 = /*@__PURE__*/getDefaultExportFromCjs(browserIpcProvider);
- var infuraProvider = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.InfuraProvider = exports.InfuraWebSocketProvider = void 0;
- var logger = new lib.Logger(_version$I.version);
- var defaultProjectId = "84842078b09946638c03157f83405213";
- var InfuraWebSocketProvider = /** @class */ (function (_super) {
- __extends(InfuraWebSocketProvider, _super);
- function InfuraWebSocketProvider(network, apiKey) {
- var _this = this;
- var provider = new InfuraProvider(network, apiKey);
- var connection = provider.connection;
- if (connection.password) {
- logger.throwError("INFURA WebSocket project secrets unsupported", lib.Logger.errors.UNSUPPORTED_OPERATION, {
- operation: "InfuraProvider.getWebSocketProvider()"
- });
- }
- var url = connection.url.replace(/^http/i, "ws").replace("/v3/", "/ws/v3/");
- _this = _super.call(this, url, network) || this;
- (0, lib$3.defineReadOnly)(_this, "apiKey", provider.projectId);
- (0, lib$3.defineReadOnly)(_this, "projectId", provider.projectId);
- (0, lib$3.defineReadOnly)(_this, "projectSecret", provider.projectSecret);
- return _this;
- }
- InfuraWebSocketProvider.prototype.isCommunityResource = function () {
- return (this.projectId === defaultProjectId);
- };
- return InfuraWebSocketProvider;
- }(websocketProvider.WebSocketProvider));
- exports.InfuraWebSocketProvider = InfuraWebSocketProvider;
- var InfuraProvider = /** @class */ (function (_super) {
- __extends(InfuraProvider, _super);
- function InfuraProvider() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- InfuraProvider.getWebSocketProvider = function (network, apiKey) {
- return new InfuraWebSocketProvider(network, apiKey);
- };
- InfuraProvider.getApiKey = function (apiKey) {
- var apiKeyObj = {
- apiKey: defaultProjectId,
- projectId: defaultProjectId,
- projectSecret: null
- };
- if (apiKey == null) {
- return apiKeyObj;
- }
- if (typeof (apiKey) === "string") {
- apiKeyObj.projectId = apiKey;
- }
- else if (apiKey.projectSecret != null) {
- logger.assertArgument((typeof (apiKey.projectId) === "string"), "projectSecret requires a projectId", "projectId", apiKey.projectId);
- logger.assertArgument((typeof (apiKey.projectSecret) === "string"), "invalid projectSecret", "projectSecret", "[REDACTED]");
- apiKeyObj.projectId = apiKey.projectId;
- apiKeyObj.projectSecret = apiKey.projectSecret;
- }
- else if (apiKey.projectId) {
- apiKeyObj.projectId = apiKey.projectId;
- }
- apiKeyObj.apiKey = apiKeyObj.projectId;
- return apiKeyObj;
- };
- InfuraProvider.getUrl = function (network, apiKey) {
- var host = null;
- switch (network ? network.name : "unknown") {
- case "homestead":
- host = "mainnet.infura.io";
- break;
- case "ropsten":
- host = "ropsten.infura.io";
- break;
- case "rinkeby":
- host = "rinkeby.infura.io";
- break;
- case "kovan":
- host = "kovan.infura.io";
- break;
- case "goerli":
- host = "goerli.infura.io";
- break;
- case "matic":
- host = "polygon-mainnet.infura.io";
- break;
- case "maticmum":
- host = "polygon-mumbai.infura.io";
- break;
- case "optimism":
- host = "optimism-mainnet.infura.io";
- break;
- case "optimism-kovan":
- host = "optimism-kovan.infura.io";
- break;
- case "arbitrum":
- host = "arbitrum-mainnet.infura.io";
- break;
- case "arbitrum-rinkeby":
- host = "arbitrum-rinkeby.infura.io";
- break;
- default:
- logger.throwError("unsupported network", lib.Logger.errors.INVALID_ARGUMENT, {
- argument: "network",
- value: network
- });
- }
- var connection = {
- allowGzip: true,
- url: ("https:/" + "/" + host + "/v3/" + apiKey.projectId),
- throttleCallback: function (attempt, url) {
- if (apiKey.projectId === defaultProjectId) {
- (0, formatter.showThrottleMessage)();
- }
- return Promise.resolve(true);
- }
- };
- if (apiKey.projectSecret != null) {
- connection.user = "";
- connection.password = apiKey.projectSecret;
- }
- return connection;
- };
- InfuraProvider.prototype.isCommunityResource = function () {
- return (this.projectId === defaultProjectId);
- };
- return InfuraProvider;
- }(urlJsonRpcProvider.UrlJsonRpcProvider));
- exports.InfuraProvider = InfuraProvider;
- });
- var infuraProvider$1 = /*@__PURE__*/getDefaultExportFromCjs(infuraProvider);
- var jsonRpcBatchProvider = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.JsonRpcBatchProvider = void 0;
- // Experimental
- var JsonRpcBatchProvider = /** @class */ (function (_super) {
- __extends(JsonRpcBatchProvider, _super);
- function JsonRpcBatchProvider() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- JsonRpcBatchProvider.prototype.send = function (method, params) {
- var _this = this;
- var request = {
- method: method,
- params: params,
- id: (this._nextId++),
- jsonrpc: "2.0"
- };
- if (this._pendingBatch == null) {
- this._pendingBatch = [];
- }
- var inflightRequest = { request: request, resolve: null, reject: null };
- var promise = new Promise(function (resolve, reject) {
- inflightRequest.resolve = resolve;
- inflightRequest.reject = reject;
- });
- this._pendingBatch.push(inflightRequest);
- if (!this._pendingBatchAggregator) {
- // Schedule batch for next event loop + short duration
- this._pendingBatchAggregator = setTimeout(function () {
- // Get teh current batch and clear it, so new requests
- // go into the next batch
- var batch = _this._pendingBatch;
- _this._pendingBatch = null;
- _this._pendingBatchAggregator = null;
- // Get the request as an array of requests
- var request = batch.map(function (inflight) { return inflight.request; });
- _this.emit("debug", {
- action: "requestBatch",
- request: (0, lib$3.deepCopy)(request),
- provider: _this
- });
- return (0, lib$q.fetchJson)(_this.connection, JSON.stringify(request)).then(function (result) {
- _this.emit("debug", {
- action: "response",
- request: request,
- response: result,
- provider: _this
- });
- // For each result, feed it to the correct Promise, depending
- // on whether it was a success or error
- batch.forEach(function (inflightRequest, index) {
- var payload = result[index];
- if (payload.error) {
- var error = new Error(payload.error.message);
- error.code = payload.error.code;
- error.data = payload.error.data;
- inflightRequest.reject(error);
- }
- else {
- inflightRequest.resolve(payload.result);
- }
- });
- }, function (error) {
- _this.emit("debug", {
- action: "response",
- error: error,
- request: request,
- provider: _this
- });
- batch.forEach(function (inflightRequest) {
- inflightRequest.reject(error);
- });
- });
- }, 10);
- }
- return promise;
- };
- return JsonRpcBatchProvider;
- }(jsonRpcProvider.JsonRpcProvider));
- exports.JsonRpcBatchProvider = JsonRpcBatchProvider;
- });
- var jsonRpcBatchProvider$1 = /*@__PURE__*/getDefaultExportFromCjs(jsonRpcBatchProvider);
- var nodesmithProvider = createCommonjsModule(function (module, exports) {
- /* istanbul ignore file */
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.NodesmithProvider = void 0;
- var logger = new lib.Logger(_version$I.version);
- // Special API key provided by Nodesmith for ethers.js
- var defaultApiKey = "ETHERS_JS_SHARED";
- var NodesmithProvider = /** @class */ (function (_super) {
- __extends(NodesmithProvider, _super);
- function NodesmithProvider() {
- return _super !== null && _super.apply(this, arguments) || this;
- }
- NodesmithProvider.getApiKey = function (apiKey) {
- if (apiKey && typeof (apiKey) !== "string") {
- logger.throwArgumentError("invalid apiKey", "apiKey", apiKey);
- }
- return apiKey || defaultApiKey;
- };
- NodesmithProvider.getUrl = function (network, apiKey) {
- logger.warn("NodeSmith will be discontinued on 2019-12-20; please migrate to another platform.");
- var host = null;
- switch (network.name) {
- case "homestead":
- host = "https://ethereum.api.nodesmith.io/v1/mainnet/jsonrpc";
- break;
- case "ropsten":
- host = "https://ethereum.api.nodesmith.io/v1/ropsten/jsonrpc";
- break;
- case "rinkeby":
- host = "https://ethereum.api.nodesmith.io/v1/rinkeby/jsonrpc";
- break;
- case "goerli":
- host = "https://ethereum.api.nodesmith.io/v1/goerli/jsonrpc";
- break;
- case "kovan":
- host = "https://ethereum.api.nodesmith.io/v1/kovan/jsonrpc";
- break;
- default:
- logger.throwArgumentError("unsupported network", "network", arguments[0]);
- }
- return (host + "?apiKey=" + apiKey);
- };
- return NodesmithProvider;
- }(urlJsonRpcProvider.UrlJsonRpcProvider));
- exports.NodesmithProvider = NodesmithProvider;
- });
- var nodesmithProvider$1 = /*@__PURE__*/getDefaultExportFromCjs(nodesmithProvider);
- var pocketProvider = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.PocketProvider = void 0;
- var logger = new lib.Logger(_version$I.version);
- // These are load-balancer-based application IDs
- var defaultApplicationIds = {
- homestead: "6004bcd10040261633ade990",
- ropsten: "6004bd4d0040261633ade991",
- rinkeby: "6004bda20040261633ade994",
- goerli: "6004bd860040261633ade992",
- };
- var PocketProvider = /** @class */ (function (_super) {
- __extends(PocketProvider, _super);
- function PocketProvider(network, apiKey) {
- // We need a bit of creativity in the constructor because
- // Pocket uses different default API keys based on the network
- var _newTarget = this.constructor;
- var _this = this;
- if (apiKey == null) {
- var n = (0, lib$3.getStatic)(_newTarget, "getNetwork")(network);
- if (n) {
- var applicationId = defaultApplicationIds[n.name];
- if (applicationId) {
- apiKey = {
- applicationId: applicationId,
- loadBalancer: true
- };
- }
- }
- // If there was any issue above, we don't know this network
- if (apiKey == null) {
- logger.throwError("unsupported network", lib.Logger.errors.INVALID_ARGUMENT, {
- argument: "network",
- value: network
- });
- }
- }
- _this = _super.call(this, network, apiKey) || this;
- return _this;
- }
- PocketProvider.getApiKey = function (apiKey) {
- // Most API Providers allow null to get the default configuration, but
- // Pocket requires the network to decide the default provider, so we
- // rely on hijacking the constructor to add a sensible default for us
- if (apiKey == null) {
- logger.throwArgumentError("PocketProvider.getApiKey does not support null apiKey", "apiKey", apiKey);
- }
- var apiKeyObj = {
- applicationId: null,
- loadBalancer: false,
- applicationSecretKey: null
- };
- // Parse applicationId and applicationSecretKey
- if (typeof (apiKey) === "string") {
- apiKeyObj.applicationId = apiKey;
- }
- else if (apiKey.applicationSecretKey != null) {
- logger.assertArgument((typeof (apiKey.applicationId) === "string"), "applicationSecretKey requires an applicationId", "applicationId", apiKey.applicationId);
- logger.assertArgument((typeof (apiKey.applicationSecretKey) === "string"), "invalid applicationSecretKey", "applicationSecretKey", "[REDACTED]");
- apiKeyObj.applicationId = apiKey.applicationId;
- apiKeyObj.applicationSecretKey = apiKey.applicationSecretKey;
- apiKeyObj.loadBalancer = !!apiKey.loadBalancer;
- }
- else if (apiKey.applicationId) {
- logger.assertArgument((typeof (apiKey.applicationId) === "string"), "apiKey.applicationId must be a string", "apiKey.applicationId", apiKey.applicationId);
- apiKeyObj.applicationId = apiKey.applicationId;
- apiKeyObj.loadBalancer = !!apiKey.loadBalancer;
- }
- else {
- logger.throwArgumentError("unsupported PocketProvider apiKey", "apiKey", apiKey);
- }
- return apiKeyObj;
- };
- PocketProvider.getUrl = function (network, apiKey) {
- var host = null;
- switch (network ? network.name : "unknown") {
- case "homestead":
- host = "eth-mainnet.gateway.pokt.network";
- break;
- case "ropsten":
- host = "eth-ropsten.gateway.pokt.network";
- break;
- case "rinkeby":
- host = "eth-rinkeby.gateway.pokt.network";
- break;
- case "goerli":
- host = "eth-goerli.gateway.pokt.network";
- break;
- default:
- logger.throwError("unsupported network", lib.Logger.errors.INVALID_ARGUMENT, {
- argument: "network",
- value: network
- });
- }
- var url = null;
- if (apiKey.loadBalancer) {
- url = "https://" + host + "/v1/lb/" + apiKey.applicationId;
- }
- else {
- url = "https://" + host + "/v1/" + apiKey.applicationId;
- }
- var connection = { url: url };
- // Initialize empty headers
- connection.headers = {};
- // Apply application secret key
- if (apiKey.applicationSecretKey != null) {
- connection.user = "";
- connection.password = apiKey.applicationSecretKey;
- }
- return connection;
- };
- PocketProvider.prototype.isCommunityResource = function () {
- return (this.applicationId === defaultApplicationIds[this.network.name]);
- };
- return PocketProvider;
- }(urlJsonRpcProvider.UrlJsonRpcProvider));
- exports.PocketProvider = PocketProvider;
- });
- var pocketProvider$1 = /*@__PURE__*/getDefaultExportFromCjs(pocketProvider);
- var web3Provider = createCommonjsModule(function (module, exports) {
- "use strict";
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
- var extendStatics = function (d, b) {
- extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- return extendStatics(d, b);
- };
- return function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
- })();
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Web3Provider = void 0;
- var logger = new lib.Logger(_version$I.version);
- var _nextId = 1;
- function buildWeb3LegacyFetcher(provider, sendFunc) {
- var fetcher = "Web3LegacyFetcher";
- return function (method, params) {
- var _this = this;
- var request = {
- method: method,
- params: params,
- id: (_nextId++),
- jsonrpc: "2.0"
- };
- return new Promise(function (resolve, reject) {
- _this.emit("debug", {
- action: "request",
- fetcher: fetcher,
- request: (0, lib$3.deepCopy)(request),
- provider: _this
- });
- sendFunc(request, function (error, response) {
- if (error) {
- _this.emit("debug", {
- action: "response",
- fetcher: fetcher,
- error: error,
- request: request,
- provider: _this
- });
- return reject(error);
- }
- _this.emit("debug", {
- action: "response",
- fetcher: fetcher,
- request: request,
- response: response,
- provider: _this
- });
- if (response.error) {
- var error_1 = new Error(response.error.message);
- error_1.code = response.error.code;
- error_1.data = response.error.data;
- return reject(error_1);
- }
- resolve(response.result);
- });
- });
- };
- }
- function buildEip1193Fetcher(provider) {
- return function (method, params) {
- var _this = this;
- if (params == null) {
- params = [];
- }
- var request = { method: method, params: params };
- this.emit("debug", {
- action: "request",
- fetcher: "Eip1193Fetcher",
- request: (0, lib$3.deepCopy)(request),
- provider: this
- });
- return provider.request(request).then(function (response) {
- _this.emit("debug", {
- action: "response",
- fetcher: "Eip1193Fetcher",
- request: request,
- response: response,
- provider: _this
- });
- return response;
- }, function (error) {
- _this.emit("debug", {
- action: "response",
- fetcher: "Eip1193Fetcher",
- request: request,
- error: error,
- provider: _this
- });
- throw error;
- });
- };
- }
- var Web3Provider = /** @class */ (function (_super) {
- __extends(Web3Provider, _super);
- function Web3Provider(provider, network) {
- var _newTarget = this.constructor;
- var _this = this;
- logger.checkNew(_newTarget, Web3Provider);
- if (provider == null) {
- logger.throwArgumentError("missing provider", "provider", provider);
- }
- var path = null;
- var jsonRpcFetchFunc = null;
- var subprovider = null;
- if (typeof (provider) === "function") {
- path = "unknown:";
- jsonRpcFetchFunc = provider;
- }
- else {
- path = provider.host || provider.path || "";
- if (!path && provider.isMetaMask) {
- path = "metamask";
- }
- subprovider = provider;
- if (provider.request) {
- if (path === "") {
- path = "eip-1193:";
- }
- jsonRpcFetchFunc = buildEip1193Fetcher(provider);
- }
- else if (provider.sendAsync) {
- jsonRpcFetchFunc = buildWeb3LegacyFetcher(provider, provider.sendAsync.bind(provider));
- }
- else if (provider.send) {
- jsonRpcFetchFunc = buildWeb3LegacyFetcher(provider, provider.send.bind(provider));
- }
- else {
- logger.throwArgumentError("unsupported provider", "provider", provider);
- }
- if (!path) {
- path = "unknown:";
- }
- }
- _this = _super.call(this, path, network) || this;
- (0, lib$3.defineReadOnly)(_this, "jsonRpcFetchFunc", jsonRpcFetchFunc);
- (0, lib$3.defineReadOnly)(_this, "provider", subprovider);
- return _this;
- }
- Web3Provider.prototype.send = function (method, params) {
- return this.jsonRpcFetchFunc(method, params);
- };
- return Web3Provider;
- }(jsonRpcProvider.JsonRpcProvider));
- exports.Web3Provider = Web3Provider;
- });
- var web3Provider$1 = /*@__PURE__*/getDefaultExportFromCjs(web3Provider);
- var lib$r = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Formatter = exports.showThrottleMessage = exports.isCommunityResourcable = exports.isCommunityResource = exports.getNetwork = exports.getDefaultProvider = exports.JsonRpcSigner = exports.IpcProvider = exports.WebSocketProvider = exports.Web3Provider = exports.StaticJsonRpcProvider = exports.PocketProvider = exports.NodesmithProvider = exports.JsonRpcBatchProvider = exports.JsonRpcProvider = exports.InfuraWebSocketProvider = exports.InfuraProvider = exports.EtherscanProvider = exports.CloudflareProvider = exports.AlchemyWebSocketProvider = exports.AlchemyProvider = exports.FallbackProvider = exports.UrlJsonRpcProvider = exports.Resolver = exports.BaseProvider = exports.Provider = void 0;
- Object.defineProperty(exports, "Provider", { enumerable: true, get: function () { return lib$b.Provider; } });
- Object.defineProperty(exports, "getNetwork", { enumerable: true, get: function () { return lib$o.getNetwork; } });
- Object.defineProperty(exports, "BaseProvider", { enumerable: true, get: function () { return baseProvider.BaseProvider; } });
- Object.defineProperty(exports, "Resolver", { enumerable: true, get: function () { return baseProvider.Resolver; } });
- Object.defineProperty(exports, "AlchemyProvider", { enumerable: true, get: function () { return alchemyProvider.AlchemyProvider; } });
- Object.defineProperty(exports, "AlchemyWebSocketProvider", { enumerable: true, get: function () { return alchemyProvider.AlchemyWebSocketProvider; } });
- Object.defineProperty(exports, "CloudflareProvider", { enumerable: true, get: function () { return cloudflareProvider.CloudflareProvider; } });
- Object.defineProperty(exports, "EtherscanProvider", { enumerable: true, get: function () { return etherscanProvider.EtherscanProvider; } });
- Object.defineProperty(exports, "FallbackProvider", { enumerable: true, get: function () { return fallbackProvider.FallbackProvider; } });
- Object.defineProperty(exports, "IpcProvider", { enumerable: true, get: function () { return browserIpcProvider.IpcProvider; } });
- Object.defineProperty(exports, "InfuraProvider", { enumerable: true, get: function () { return infuraProvider.InfuraProvider; } });
- Object.defineProperty(exports, "InfuraWebSocketProvider", { enumerable: true, get: function () { return infuraProvider.InfuraWebSocketProvider; } });
- Object.defineProperty(exports, "JsonRpcProvider", { enumerable: true, get: function () { return jsonRpcProvider.JsonRpcProvider; } });
- Object.defineProperty(exports, "JsonRpcSigner", { enumerable: true, get: function () { return jsonRpcProvider.JsonRpcSigner; } });
- Object.defineProperty(exports, "JsonRpcBatchProvider", { enumerable: true, get: function () { return jsonRpcBatchProvider.JsonRpcBatchProvider; } });
- Object.defineProperty(exports, "NodesmithProvider", { enumerable: true, get: function () { return nodesmithProvider.NodesmithProvider; } });
- Object.defineProperty(exports, "PocketProvider", { enumerable: true, get: function () { return pocketProvider.PocketProvider; } });
- Object.defineProperty(exports, "StaticJsonRpcProvider", { enumerable: true, get: function () { return urlJsonRpcProvider.StaticJsonRpcProvider; } });
- Object.defineProperty(exports, "UrlJsonRpcProvider", { enumerable: true, get: function () { return urlJsonRpcProvider.UrlJsonRpcProvider; } });
- Object.defineProperty(exports, "Web3Provider", { enumerable: true, get: function () { return web3Provider.Web3Provider; } });
- Object.defineProperty(exports, "WebSocketProvider", { enumerable: true, get: function () { return websocketProvider.WebSocketProvider; } });
- Object.defineProperty(exports, "Formatter", { enumerable: true, get: function () { return formatter.Formatter; } });
- Object.defineProperty(exports, "isCommunityResourcable", { enumerable: true, get: function () { return formatter.isCommunityResourcable; } });
- Object.defineProperty(exports, "isCommunityResource", { enumerable: true, get: function () { return formatter.isCommunityResource; } });
- Object.defineProperty(exports, "showThrottleMessage", { enumerable: true, get: function () { return formatter.showThrottleMessage; } });
- var logger = new lib.Logger(_version$I.version);
- ////////////////////////
- // Helper Functions
- function getDefaultProvider(network, options) {
- if (network == null) {
- network = "homestead";
- }
- // If passed a URL, figure out the right type of provider based on the scheme
- if (typeof (network) === "string") {
- // @TODO: Add support for IpcProvider; maybe if it ends in ".ipc"?
- // Handle http and ws (and their secure variants)
- var match = network.match(/^(ws|http)s?:/i);
- if (match) {
- switch (match[1]) {
- case "http":
- return new jsonRpcProvider.JsonRpcProvider(network);
- case "ws":
- return new websocketProvider.WebSocketProvider(network);
- default:
- logger.throwArgumentError("unsupported URL scheme", "network", network);
- }
- }
- }
- var n = (0, lib$o.getNetwork)(network);
- if (!n || !n._defaultProvider) {
- logger.throwError("unsupported getDefaultProvider network", lib.Logger.errors.NETWORK_ERROR, {
- operation: "getDefaultProvider",
- network: network
- });
- }
- return n._defaultProvider({
- FallbackProvider: fallbackProvider.FallbackProvider,
- AlchemyProvider: alchemyProvider.AlchemyProvider,
- CloudflareProvider: cloudflareProvider.CloudflareProvider,
- EtherscanProvider: etherscanProvider.EtherscanProvider,
- InfuraProvider: infuraProvider.InfuraProvider,
- JsonRpcProvider: jsonRpcProvider.JsonRpcProvider,
- NodesmithProvider: nodesmithProvider.NodesmithProvider,
- PocketProvider: pocketProvider.PocketProvider,
- Web3Provider: web3Provider.Web3Provider,
- IpcProvider: browserIpcProvider.IpcProvider,
- }, options);
- }
- exports.getDefaultProvider = getDefaultProvider;
- });
- var index$r = /*@__PURE__*/getDefaultExportFromCjs(lib$r);
- var _version$K = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "solidity/5.6.0";
- });
- var _version$L = /*@__PURE__*/getDefaultExportFromCjs(_version$K);
- var lib$s = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.sha256 = exports.keccak256 = exports.pack = void 0;
- var regexBytes = new RegExp("^bytes([0-9]+)$");
- var regexNumber = new RegExp("^(u?int)([0-9]*)$");
- var regexArray = new RegExp("^(.*)\\[([0-9]*)\\]$");
- var Zeros = "0000000000000000000000000000000000000000000000000000000000000000";
- var logger = new lib.Logger(_version$K.version);
- function _pack(type, value, isArray) {
- switch (type) {
- case "address":
- if (isArray) {
- return (0, lib$1.zeroPad)(value, 32);
- }
- return (0, lib$1.arrayify)(value);
- case "string":
- return (0, lib$8.toUtf8Bytes)(value);
- case "bytes":
- return (0, lib$1.arrayify)(value);
- case "bool":
- value = (value ? "0x01" : "0x00");
- if (isArray) {
- return (0, lib$1.zeroPad)(value, 32);
- }
- return (0, lib$1.arrayify)(value);
- }
- var match = type.match(regexNumber);
- if (match) {
- //let signed = (match[1] === "int")
- var size = parseInt(match[2] || "256");
- if ((match[2] && String(size) !== match[2]) || (size % 8 !== 0) || size === 0 || size > 256) {
- logger.throwArgumentError("invalid number type", "type", type);
- }
- if (isArray) {
- size = 256;
- }
- value = lib$2.BigNumber.from(value).toTwos(size);
- return (0, lib$1.zeroPad)(value, size / 8);
- }
- match = type.match(regexBytes);
- if (match) {
- var size = parseInt(match[1]);
- if (String(size) !== match[1] || size === 0 || size > 32) {
- logger.throwArgumentError("invalid bytes type", "type", type);
- }
- if ((0, lib$1.arrayify)(value).byteLength !== size) {
- logger.throwArgumentError("invalid value for " + type, "value", value);
- }
- if (isArray) {
- return (0, lib$1.arrayify)((value + Zeros).substring(0, 66));
- }
- return value;
- }
- match = type.match(regexArray);
- if (match && Array.isArray(value)) {
- var baseType_1 = match[1];
- var count = parseInt(match[2] || String(value.length));
- if (count != value.length) {
- logger.throwArgumentError("invalid array length for " + type, "value", value);
- }
- var result_1 = [];
- value.forEach(function (value) {
- result_1.push(_pack(baseType_1, value, true));
- });
- return (0, lib$1.concat)(result_1);
- }
- return logger.throwArgumentError("invalid type", "type", type);
- }
- // @TODO: Array Enum
- function pack(types, values) {
- if (types.length != values.length) {
- logger.throwArgumentError("wrong number of values; expected ${ types.length }", "values", values);
- }
- var tight = [];
- types.forEach(function (type, index) {
- tight.push(_pack(type, values[index]));
- });
- return (0, lib$1.hexlify)((0, lib$1.concat)(tight));
- }
- exports.pack = pack;
- function keccak256(types, values) {
- return (0, lib$4.keccak256)(pack(types, values));
- }
- exports.keccak256 = keccak256;
- function sha256(types, values) {
- return (0, lib$h.sha256)(pack(types, values));
- }
- exports.sha256 = sha256;
- });
- var index$s = /*@__PURE__*/getDefaultExportFromCjs(lib$s);
- var _version$M = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "units/5.6.0";
- });
- var _version$N = /*@__PURE__*/getDefaultExportFromCjs(_version$M);
- var lib$t = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.parseEther = exports.formatEther = exports.parseUnits = exports.formatUnits = exports.commify = void 0;
- var logger = new lib.Logger(_version$M.version);
- var names = [
- "wei",
- "kwei",
- "mwei",
- "gwei",
- "szabo",
- "finney",
- "ether",
- ];
- // Some environments have issues with RegEx that contain back-tracking, so we cannot
- // use them.
- function commify(value) {
- var comps = String(value).split(".");
- if (comps.length > 2 || !comps[0].match(/^-?[0-9]*$/) || (comps[1] && !comps[1].match(/^[0-9]*$/)) || value === "." || value === "-.") {
- logger.throwArgumentError("invalid value", "value", value);
- }
- // Make sure we have at least one whole digit (0 if none)
- var whole = comps[0];
- var negative = "";
- if (whole.substring(0, 1) === "-") {
- negative = "-";
- whole = whole.substring(1);
- }
- // Make sure we have at least 1 whole digit with no leading zeros
- while (whole.substring(0, 1) === "0") {
- whole = whole.substring(1);
- }
- if (whole === "") {
- whole = "0";
- }
- var suffix = "";
- if (comps.length === 2) {
- suffix = "." + (comps[1] || "0");
- }
- while (suffix.length > 2 && suffix[suffix.length - 1] === "0") {
- suffix = suffix.substring(0, suffix.length - 1);
- }
- var formatted = [];
- while (whole.length) {
- if (whole.length <= 3) {
- formatted.unshift(whole);
- break;
- }
- else {
- var index = whole.length - 3;
- formatted.unshift(whole.substring(index));
- whole = whole.substring(0, index);
- }
- }
- return negative + formatted.join(",") + suffix;
- }
- exports.commify = commify;
- function formatUnits(value, unitName) {
- if (typeof (unitName) === "string") {
- var index = names.indexOf(unitName);
- if (index !== -1) {
- unitName = 3 * index;
- }
- }
- return (0, lib$2.formatFixed)(value, (unitName != null) ? unitName : 18);
- }
- exports.formatUnits = formatUnits;
- function parseUnits(value, unitName) {
- if (typeof (value) !== "string") {
- logger.throwArgumentError("value must be a string", "value", value);
- }
- if (typeof (unitName) === "string") {
- var index = names.indexOf(unitName);
- if (index !== -1) {
- unitName = 3 * index;
- }
- }
- return (0, lib$2.parseFixed)(value, (unitName != null) ? unitName : 18);
- }
- exports.parseUnits = parseUnits;
- function formatEther(wei) {
- return formatUnits(wei, 18);
- }
- exports.formatEther = formatEther;
- function parseEther(ether) {
- return parseUnits(ether, 18);
- }
- exports.parseEther = parseEther;
- });
- var index$t = /*@__PURE__*/getDefaultExportFromCjs(lib$t);
- var utils$3 = createCommonjsModule(function (module, exports) {
- "use strict";
- var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.formatBytes32String = exports.Utf8ErrorFuncs = exports.toUtf8String = exports.toUtf8CodePoints = exports.toUtf8Bytes = exports._toEscapedUtf8String = exports.nameprep = exports.hexDataSlice = exports.hexDataLength = exports.hexZeroPad = exports.hexValue = exports.hexStripZeros = exports.hexConcat = exports.isHexString = exports.hexlify = exports.base64 = exports.base58 = exports.TransactionDescription = exports.LogDescription = exports.Interface = exports.SigningKey = exports.HDNode = exports.defaultPath = exports.isBytesLike = exports.isBytes = exports.zeroPad = exports.stripZeros = exports.concat = exports.arrayify = exports.shallowCopy = exports.resolveProperties = exports.getStatic = exports.defineReadOnly = exports.deepCopy = exports.checkProperties = exports.poll = exports.fetchJson = exports._fetchData = exports.RLP = exports.Logger = exports.checkResultErrors = exports.FormatTypes = exports.ParamType = exports.FunctionFragment = exports.EventFragment = exports.ErrorFragment = exports.ConstructorFragment = exports.Fragment = exports.defaultAbiCoder = exports.AbiCoder = void 0;
- exports.Indexed = exports.Utf8ErrorReason = exports.UnicodeNormalizationForm = exports.SupportedAlgorithm = exports.mnemonicToSeed = exports.isValidMnemonic = exports.entropyToMnemonic = exports.mnemonicToEntropy = exports.getAccountPath = exports.verifyTypedData = exports.verifyMessage = exports.recoverPublicKey = exports.computePublicKey = exports.recoverAddress = exports.computeAddress = exports.getJsonWalletAddress = exports.TransactionTypes = exports.serializeTransaction = exports.parseTransaction = exports.accessListify = exports.joinSignature = exports.splitSignature = exports.soliditySha256 = exports.solidityKeccak256 = exports.solidityPack = exports.shuffled = exports.randomBytes = exports.sha512 = exports.sha256 = exports.ripemd160 = exports.keccak256 = exports.computeHmac = exports.commify = exports.parseUnits = exports.formatUnits = exports.parseEther = exports.formatEther = exports.isAddress = exports.getCreate2Address = exports.getContractAddress = exports.getIcapAddress = exports.getAddress = exports._TypedDataEncoder = exports.id = exports.isValidName = exports.namehash = exports.hashMessage = exports.dnsEncode = exports.parseBytes32String = void 0;
- Object.defineProperty(exports, "AbiCoder", { enumerable: true, get: function () { return lib$a.AbiCoder; } });
- Object.defineProperty(exports, "checkResultErrors", { enumerable: true, get: function () { return lib$a.checkResultErrors; } });
- Object.defineProperty(exports, "ConstructorFragment", { enumerable: true, get: function () { return lib$a.ConstructorFragment; } });
- Object.defineProperty(exports, "defaultAbiCoder", { enumerable: true, get: function () { return lib$a.defaultAbiCoder; } });
- Object.defineProperty(exports, "ErrorFragment", { enumerable: true, get: function () { return lib$a.ErrorFragment; } });
- Object.defineProperty(exports, "EventFragment", { enumerable: true, get: function () { return lib$a.EventFragment; } });
- Object.defineProperty(exports, "FormatTypes", { enumerable: true, get: function () { return lib$a.FormatTypes; } });
- Object.defineProperty(exports, "Fragment", { enumerable: true, get: function () { return lib$a.Fragment; } });
- Object.defineProperty(exports, "FunctionFragment", { enumerable: true, get: function () { return lib$a.FunctionFragment; } });
- Object.defineProperty(exports, "Indexed", { enumerable: true, get: function () { return lib$a.Indexed; } });
- Object.defineProperty(exports, "Interface", { enumerable: true, get: function () { return lib$a.Interface; } });
- Object.defineProperty(exports, "LogDescription", { enumerable: true, get: function () { return lib$a.LogDescription; } });
- Object.defineProperty(exports, "ParamType", { enumerable: true, get: function () { return lib$a.ParamType; } });
- Object.defineProperty(exports, "TransactionDescription", { enumerable: true, get: function () { return lib$a.TransactionDescription; } });
- Object.defineProperty(exports, "getAddress", { enumerable: true, get: function () { return lib$6.getAddress; } });
- Object.defineProperty(exports, "getCreate2Address", { enumerable: true, get: function () { return lib$6.getCreate2Address; } });
- Object.defineProperty(exports, "getContractAddress", { enumerable: true, get: function () { return lib$6.getContractAddress; } });
- Object.defineProperty(exports, "getIcapAddress", { enumerable: true, get: function () { return lib$6.getIcapAddress; } });
- Object.defineProperty(exports, "isAddress", { enumerable: true, get: function () { return lib$6.isAddress; } });
- var base64 = __importStar(lib$p);
- exports.base64 = base64;
- Object.defineProperty(exports, "base58", { enumerable: true, get: function () { return lib$g.Base58; } });
- Object.defineProperty(exports, "arrayify", { enumerable: true, get: function () { return lib$1.arrayify; } });
- Object.defineProperty(exports, "concat", { enumerable: true, get: function () { return lib$1.concat; } });
- Object.defineProperty(exports, "hexConcat", { enumerable: true, get: function () { return lib$1.hexConcat; } });
- Object.defineProperty(exports, "hexDataSlice", { enumerable: true, get: function () { return lib$1.hexDataSlice; } });
- Object.defineProperty(exports, "hexDataLength", { enumerable: true, get: function () { return lib$1.hexDataLength; } });
- Object.defineProperty(exports, "hexlify", { enumerable: true, get: function () { return lib$1.hexlify; } });
- Object.defineProperty(exports, "hexStripZeros", { enumerable: true, get: function () { return lib$1.hexStripZeros; } });
- Object.defineProperty(exports, "hexValue", { enumerable: true, get: function () { return lib$1.hexValue; } });
- Object.defineProperty(exports, "hexZeroPad", { enumerable: true, get: function () { return lib$1.hexZeroPad; } });
- Object.defineProperty(exports, "isBytes", { enumerable: true, get: function () { return lib$1.isBytes; } });
- Object.defineProperty(exports, "isBytesLike", { enumerable: true, get: function () { return lib$1.isBytesLike; } });
- Object.defineProperty(exports, "isHexString", { enumerable: true, get: function () { return lib$1.isHexString; } });
- Object.defineProperty(exports, "joinSignature", { enumerable: true, get: function () { return lib$1.joinSignature; } });
- Object.defineProperty(exports, "zeroPad", { enumerable: true, get: function () { return lib$1.zeroPad; } });
- Object.defineProperty(exports, "splitSignature", { enumerable: true, get: function () { return lib$1.splitSignature; } });
- Object.defineProperty(exports, "stripZeros", { enumerable: true, get: function () { return lib$1.stripZeros; } });
- Object.defineProperty(exports, "_TypedDataEncoder", { enumerable: true, get: function () { return lib$9._TypedDataEncoder; } });
- Object.defineProperty(exports, "dnsEncode", { enumerable: true, get: function () { return lib$9.dnsEncode; } });
- Object.defineProperty(exports, "hashMessage", { enumerable: true, get: function () { return lib$9.hashMessage; } });
- Object.defineProperty(exports, "id", { enumerable: true, get: function () { return lib$9.id; } });
- Object.defineProperty(exports, "isValidName", { enumerable: true, get: function () { return lib$9.isValidName; } });
- Object.defineProperty(exports, "namehash", { enumerable: true, get: function () { return lib$9.namehash; } });
- Object.defineProperty(exports, "defaultPath", { enumerable: true, get: function () { return lib$k.defaultPath; } });
- Object.defineProperty(exports, "entropyToMnemonic", { enumerable: true, get: function () { return lib$k.entropyToMnemonic; } });
- Object.defineProperty(exports, "getAccountPath", { enumerable: true, get: function () { return lib$k.getAccountPath; } });
- Object.defineProperty(exports, "HDNode", { enumerable: true, get: function () { return lib$k.HDNode; } });
- Object.defineProperty(exports, "isValidMnemonic", { enumerable: true, get: function () { return lib$k.isValidMnemonic; } });
- Object.defineProperty(exports, "mnemonicToEntropy", { enumerable: true, get: function () { return lib$k.mnemonicToEntropy; } });
- Object.defineProperty(exports, "mnemonicToSeed", { enumerable: true, get: function () { return lib$k.mnemonicToSeed; } });
- Object.defineProperty(exports, "getJsonWalletAddress", { enumerable: true, get: function () { return lib$m.getJsonWalletAddress; } });
- Object.defineProperty(exports, "keccak256", { enumerable: true, get: function () { return lib$4.keccak256; } });
- Object.defineProperty(exports, "Logger", { enumerable: true, get: function () { return lib.Logger; } });
- Object.defineProperty(exports, "computeHmac", { enumerable: true, get: function () { return lib$h.computeHmac; } });
- Object.defineProperty(exports, "ripemd160", { enumerable: true, get: function () { return lib$h.ripemd160; } });
- Object.defineProperty(exports, "sha256", { enumerable: true, get: function () { return lib$h.sha256; } });
- Object.defineProperty(exports, "sha512", { enumerable: true, get: function () { return lib$h.sha512; } });
- Object.defineProperty(exports, "solidityKeccak256", { enumerable: true, get: function () { return lib$s.keccak256; } });
- Object.defineProperty(exports, "solidityPack", { enumerable: true, get: function () { return lib$s.pack; } });
- Object.defineProperty(exports, "soliditySha256", { enumerable: true, get: function () { return lib$s.sha256; } });
- Object.defineProperty(exports, "randomBytes", { enumerable: true, get: function () { return lib$l.randomBytes; } });
- Object.defineProperty(exports, "shuffled", { enumerable: true, get: function () { return lib$l.shuffled; } });
- Object.defineProperty(exports, "checkProperties", { enumerable: true, get: function () { return lib$3.checkProperties; } });
- Object.defineProperty(exports, "deepCopy", { enumerable: true, get: function () { return lib$3.deepCopy; } });
- Object.defineProperty(exports, "defineReadOnly", { enumerable: true, get: function () { return lib$3.defineReadOnly; } });
- Object.defineProperty(exports, "getStatic", { enumerable: true, get: function () { return lib$3.getStatic; } });
- Object.defineProperty(exports, "resolveProperties", { enumerable: true, get: function () { return lib$3.resolveProperties; } });
- Object.defineProperty(exports, "shallowCopy", { enumerable: true, get: function () { return lib$3.shallowCopy; } });
- var RLP = __importStar(lib$5);
- exports.RLP = RLP;
- Object.defineProperty(exports, "computePublicKey", { enumerable: true, get: function () { return lib$d.computePublicKey; } });
- Object.defineProperty(exports, "recoverPublicKey", { enumerable: true, get: function () { return lib$d.recoverPublicKey; } });
- Object.defineProperty(exports, "SigningKey", { enumerable: true, get: function () { return lib$d.SigningKey; } });
- Object.defineProperty(exports, "formatBytes32String", { enumerable: true, get: function () { return lib$8.formatBytes32String; } });
- Object.defineProperty(exports, "nameprep", { enumerable: true, get: function () { return lib$8.nameprep; } });
- Object.defineProperty(exports, "parseBytes32String", { enumerable: true, get: function () { return lib$8.parseBytes32String; } });
- Object.defineProperty(exports, "_toEscapedUtf8String", { enumerable: true, get: function () { return lib$8._toEscapedUtf8String; } });
- Object.defineProperty(exports, "toUtf8Bytes", { enumerable: true, get: function () { return lib$8.toUtf8Bytes; } });
- Object.defineProperty(exports, "toUtf8CodePoints", { enumerable: true, get: function () { return lib$8.toUtf8CodePoints; } });
- Object.defineProperty(exports, "toUtf8String", { enumerable: true, get: function () { return lib$8.toUtf8String; } });
- Object.defineProperty(exports, "Utf8ErrorFuncs", { enumerable: true, get: function () { return lib$8.Utf8ErrorFuncs; } });
- Object.defineProperty(exports, "accessListify", { enumerable: true, get: function () { return lib$e.accessListify; } });
- Object.defineProperty(exports, "computeAddress", { enumerable: true, get: function () { return lib$e.computeAddress; } });
- Object.defineProperty(exports, "parseTransaction", { enumerable: true, get: function () { return lib$e.parse; } });
- Object.defineProperty(exports, "recoverAddress", { enumerable: true, get: function () { return lib$e.recoverAddress; } });
- Object.defineProperty(exports, "serializeTransaction", { enumerable: true, get: function () { return lib$e.serialize; } });
- Object.defineProperty(exports, "TransactionTypes", { enumerable: true, get: function () { return lib$e.TransactionTypes; } });
- Object.defineProperty(exports, "commify", { enumerable: true, get: function () { return lib$t.commify; } });
- Object.defineProperty(exports, "formatEther", { enumerable: true, get: function () { return lib$t.formatEther; } });
- Object.defineProperty(exports, "parseEther", { enumerable: true, get: function () { return lib$t.parseEther; } });
- Object.defineProperty(exports, "formatUnits", { enumerable: true, get: function () { return lib$t.formatUnits; } });
- Object.defineProperty(exports, "parseUnits", { enumerable: true, get: function () { return lib$t.parseUnits; } });
- Object.defineProperty(exports, "verifyMessage", { enumerable: true, get: function () { return lib$n.verifyMessage; } });
- Object.defineProperty(exports, "verifyTypedData", { enumerable: true, get: function () { return lib$n.verifyTypedData; } });
- Object.defineProperty(exports, "_fetchData", { enumerable: true, get: function () { return lib$q._fetchData; } });
- Object.defineProperty(exports, "fetchJson", { enumerable: true, get: function () { return lib$q.fetchJson; } });
- Object.defineProperty(exports, "poll", { enumerable: true, get: function () { return lib$q.poll; } });
- ////////////////////////
- // Enums
- var sha2_2 = lib$h;
- Object.defineProperty(exports, "SupportedAlgorithm", { enumerable: true, get: function () { return sha2_2.SupportedAlgorithm; } });
- var strings_2 = lib$8;
- Object.defineProperty(exports, "UnicodeNormalizationForm", { enumerable: true, get: function () { return strings_2.UnicodeNormalizationForm; } });
- Object.defineProperty(exports, "Utf8ErrorReason", { enumerable: true, get: function () { return strings_2.Utf8ErrorReason; } });
- });
- var utils$4 = /*@__PURE__*/getDefaultExportFromCjs(utils$3);
- var _version$O = createCommonjsModule(function (module, exports) {
- "use strict";
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.version = void 0;
- exports.version = "ethers/5.6.0";
- });
- var _version$P = /*@__PURE__*/getDefaultExportFromCjs(_version$O);
- var ethers = createCommonjsModule(function (module, exports) {
- "use strict";
- var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Wordlist = exports.version = exports.wordlists = exports.utils = exports.logger = exports.errors = exports.constants = exports.FixedNumber = exports.BigNumber = exports.ContractFactory = exports.Contract = exports.BaseContract = exports.providers = exports.getDefaultProvider = exports.VoidSigner = exports.Wallet = exports.Signer = void 0;
- Object.defineProperty(exports, "BaseContract", { enumerable: true, get: function () { return lib$f.BaseContract; } });
- Object.defineProperty(exports, "Contract", { enumerable: true, get: function () { return lib$f.Contract; } });
- Object.defineProperty(exports, "ContractFactory", { enumerable: true, get: function () { return lib$f.ContractFactory; } });
- Object.defineProperty(exports, "BigNumber", { enumerable: true, get: function () { return lib$2.BigNumber; } });
- Object.defineProperty(exports, "FixedNumber", { enumerable: true, get: function () { return lib$2.FixedNumber; } });
- Object.defineProperty(exports, "Signer", { enumerable: true, get: function () { return lib$c.Signer; } });
- Object.defineProperty(exports, "VoidSigner", { enumerable: true, get: function () { return lib$c.VoidSigner; } });
- Object.defineProperty(exports, "Wallet", { enumerable: true, get: function () { return lib$n.Wallet; } });
- var constants = __importStar(lib$7);
- exports.constants = constants;
- var providers = __importStar(lib$r);
- exports.providers = providers;
- var providers_1 = lib$r;
- Object.defineProperty(exports, "getDefaultProvider", { enumerable: true, get: function () { return providers_1.getDefaultProvider; } });
- Object.defineProperty(exports, "Wordlist", { enumerable: true, get: function () { return lib$j.Wordlist; } });
- Object.defineProperty(exports, "wordlists", { enumerable: true, get: function () { return lib$j.wordlists; } });
- var utils = __importStar(utils$3);
- exports.utils = utils;
- Object.defineProperty(exports, "errors", { enumerable: true, get: function () { return lib.ErrorCode; } });
- ////////////////////////
- // Compile-Time Constants
- // This is generated by "npm run dist"
- Object.defineProperty(exports, "version", { enumerable: true, get: function () { return _version$O.version; } });
- var logger = new lib.Logger(_version$O.version);
- exports.logger = logger;
- });
- var ethers$1 = /*@__PURE__*/getDefaultExportFromCjs(ethers);
- var lib$u = createCommonjsModule(function (module, exports) {
- "use strict";
- var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
- };
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.Wordlist = exports.version = exports.wordlists = exports.utils = exports.logger = exports.errors = exports.constants = exports.FixedNumber = exports.BigNumber = exports.ContractFactory = exports.Contract = exports.BaseContract = exports.providers = exports.getDefaultProvider = exports.VoidSigner = exports.Wallet = exports.Signer = exports.ethers = void 0;
- // To modify this file, you must update ./misc/admin/lib/cmds/update-exports.js
- var ethers$1 = __importStar(ethers);
- exports.ethers = ethers$1;
- try {
- var anyGlobal = window;
- if (anyGlobal._ethers == null) {
- anyGlobal._ethers = ethers$1;
- }
- }
- catch (error) { }
- var ethers_1 = ethers;
- Object.defineProperty(exports, "Signer", { enumerable: true, get: function () { return ethers_1.Signer; } });
- Object.defineProperty(exports, "Wallet", { enumerable: true, get: function () { return ethers_1.Wallet; } });
- Object.defineProperty(exports, "VoidSigner", { enumerable: true, get: function () { return ethers_1.VoidSigner; } });
- Object.defineProperty(exports, "getDefaultProvider", { enumerable: true, get: function () { return ethers_1.getDefaultProvider; } });
- Object.defineProperty(exports, "providers", { enumerable: true, get: function () { return ethers_1.providers; } });
- Object.defineProperty(exports, "BaseContract", { enumerable: true, get: function () { return ethers_1.BaseContract; } });
- Object.defineProperty(exports, "Contract", { enumerable: true, get: function () { return ethers_1.Contract; } });
- Object.defineProperty(exports, "ContractFactory", { enumerable: true, get: function () { return ethers_1.ContractFactory; } });
- Object.defineProperty(exports, "BigNumber", { enumerable: true, get: function () { return ethers_1.BigNumber; } });
- Object.defineProperty(exports, "FixedNumber", { enumerable: true, get: function () { return ethers_1.FixedNumber; } });
- Object.defineProperty(exports, "constants", { enumerable: true, get: function () { return ethers_1.constants; } });
- Object.defineProperty(exports, "errors", { enumerable: true, get: function () { return ethers_1.errors; } });
- Object.defineProperty(exports, "logger", { enumerable: true, get: function () { return ethers_1.logger; } });
- Object.defineProperty(exports, "utils", { enumerable: true, get: function () { return ethers_1.utils; } });
- Object.defineProperty(exports, "wordlists", { enumerable: true, get: function () { return ethers_1.wordlists; } });
- ////////////////////////
- // Compile-Time Constants
- Object.defineProperty(exports, "version", { enumerable: true, get: function () { return ethers_1.version; } });
- Object.defineProperty(exports, "Wordlist", { enumerable: true, get: function () { return ethers_1.Wordlist; } });
- });
- var index$u = /*@__PURE__*/getDefaultExportFromCjs(lib$u);
- return index$u;
- })));
- //# sourceMappingURL=ethers.umd.js.map
|