ethereum_js.go 169 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package jsre
  17. const Web3_JS = `
  18. require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  19. /*
  20. This file is part of ethereum.js.
  21. ethereum.js is free software: you can redistribute it and/or modify
  22. it under the terms of the GNU Lesser General Public License as published by
  23. the Free Software Foundation, either version 3 of the License, or
  24. (at your option) any later version.
  25. ethereum.js is distributed in the hope that it will be useful,
  26. but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. GNU Lesser General Public License for more details.
  29. You should have received a copy of the GNU Lesser General Public License
  30. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  31. */
  32. /**
  33. * @file coder.js
  34. * @author Marek Kotewicz <marek@ethdev.com>
  35. * @date 2015
  36. */
  37. var BigNumber = require('bignumber.js');
  38. var utils = require('../utils/utils');
  39. var f = require('./formatters');
  40. var SolidityParam = require('./param');
  41. /**
  42. * Should be used to check if a type is an array type
  43. *
  44. * @method isArrayType
  45. * @param {String} type
  46. * @return {Bool} true is the type is an array, otherwise false
  47. */
  48. var isArrayType = function (type) {
  49. return type.slice(-2) === '[]';
  50. };
  51. /**
  52. * SolidityType prototype is used to encode/decode solidity params of certain type
  53. */
  54. var SolidityType = function (config) {
  55. this._name = config.name;
  56. this._match = config.match;
  57. this._mode = config.mode;
  58. this._inputFormatter = config.inputFormatter;
  59. this._outputFormatter = config.outputFormatter;
  60. };
  61. /**
  62. * Should be used to determine if this SolidityType do match given type
  63. *
  64. * @method isType
  65. * @param {String} name
  66. * @return {Bool} true if type match this SolidityType, otherwise false
  67. */
  68. SolidityType.prototype.isType = function (name) {
  69. if (this._match === 'strict') {
  70. return this._name === name || (name.indexOf(this._name) === 0 && name.slice(this._name.length) === '[]');
  71. } else if (this._match === 'prefix') {
  72. // TODO better type detection!
  73. return name.indexOf(this._name) === 0;
  74. }
  75. };
  76. /**
  77. * Should be used to transform plain param to SolidityParam object
  78. *
  79. * @method formatInput
  80. * @param {Object} param - plain object, or an array of objects
  81. * @param {Bool} arrayType - true if a param should be encoded as an array
  82. * @return {SolidityParam} encoded param wrapped in SolidityParam object
  83. */
  84. SolidityType.prototype.formatInput = function (param, arrayType) {
  85. if (utils.isArray(param) && arrayType) { // TODO: should fail if this two are not the same
  86. var self = this;
  87. return param.map(function (p) {
  88. return self._inputFormatter(p);
  89. }).reduce(function (acc, current) {
  90. return acc.combine(current);
  91. }, f.formatInputInt(param.length)).withOffset(32);
  92. }
  93. return this._inputFormatter(param);
  94. };
  95. /**
  96. * Should be used to transoform SolidityParam to plain param
  97. *
  98. * @method formatOutput
  99. * @param {SolidityParam} byteArray
  100. * @param {Bool} arrayType - true if a param should be decoded as an array
  101. * @return {Object} plain decoded param
  102. */
  103. SolidityType.prototype.formatOutput = function (param, arrayType) {
  104. if (arrayType) {
  105. // let's assume, that we solidity will never return long arrays :P
  106. var result = [];
  107. var length = new BigNumber(param.dynamicPart().slice(0, 64), 16);
  108. for (var i = 0; i < length * 64; i += 64) {
  109. result.push(this._outputFormatter(new SolidityParam(param.dynamicPart().substr(i + 64, 64))));
  110. }
  111. return result;
  112. }
  113. return this._outputFormatter(param);
  114. };
  115. /**
  116. * Should be used to slice single param from bytes
  117. *
  118. * @method sliceParam
  119. * @param {String} bytes
  120. * @param {Number} index of param to slice
  121. * @param {String} type
  122. * @returns {SolidityParam} param
  123. */
  124. SolidityType.prototype.sliceParam = function (bytes, index, type) {
  125. if (this._mode === 'bytes') {
  126. return SolidityParam.decodeBytes(bytes, index);
  127. } else if (isArrayType(type)) {
  128. return SolidityParam.decodeArray(bytes, index);
  129. }
  130. return SolidityParam.decodeParam(bytes, index);
  131. };
  132. /**
  133. * SolidityCoder prototype should be used to encode/decode solidity params of any type
  134. */
  135. var SolidityCoder = function (types) {
  136. this._types = types;
  137. };
  138. /**
  139. * This method should be used to transform type to SolidityType
  140. *
  141. * @method _requireType
  142. * @param {String} type
  143. * @returns {SolidityType}
  144. * @throws {Error} throws if no matching type is found
  145. */
  146. SolidityCoder.prototype._requireType = function (type) {
  147. var solidityType = this._types.filter(function (t) {
  148. return t.isType(type);
  149. })[0];
  150. if (!solidityType) {
  151. throw Error('invalid solidity type!: ' + type);
  152. }
  153. return solidityType;
  154. };
  155. /**
  156. * Should be used to transform plain param of given type to SolidityParam
  157. *
  158. * @method _formatInput
  159. * @param {String} type of param
  160. * @param {Object} plain param
  161. * @return {SolidityParam}
  162. */
  163. SolidityCoder.prototype._formatInput = function (type, param) {
  164. return this._requireType(type).formatInput(param, isArrayType(type));
  165. };
  166. /**
  167. * Should be used to encode plain param
  168. *
  169. * @method encodeParam
  170. * @param {String} type
  171. * @param {Object} plain param
  172. * @return {String} encoded plain param
  173. */
  174. SolidityCoder.prototype.encodeParam = function (type, param) {
  175. return this._formatInput(type, param).encode();
  176. };
  177. /**
  178. * Should be used to encode list of params
  179. *
  180. * @method encodeParams
  181. * @param {Array} types
  182. * @param {Array} params
  183. * @return {String} encoded list of params
  184. */
  185. SolidityCoder.prototype.encodeParams = function (types, params) {
  186. var self = this;
  187. var solidityParams = types.map(function (type, index) {
  188. return self._formatInput(type, params[index]);
  189. });
  190. return SolidityParam.encodeList(solidityParams);
  191. };
  192. /**
  193. * Should be used to decode bytes to plain param
  194. *
  195. * @method decodeParam
  196. * @param {String} type
  197. * @param {String} bytes
  198. * @return {Object} plain param
  199. */
  200. SolidityCoder.prototype.decodeParam = function (type, bytes) {
  201. return this.decodeParams([type], bytes)[0];
  202. };
  203. /**
  204. * Should be used to decode list of params
  205. *
  206. * @method decodeParam
  207. * @param {Array} types
  208. * @param {String} bytes
  209. * @return {Array} array of plain params
  210. */
  211. SolidityCoder.prototype.decodeParams = function (types, bytes) {
  212. var self = this;
  213. return types.map(function (type, index) {
  214. var solidityType = self._requireType(type);
  215. var p = solidityType.sliceParam(bytes, index, type);
  216. return solidityType.formatOutput(p, isArrayType(type));
  217. });
  218. };
  219. var coder = new SolidityCoder([
  220. new SolidityType({
  221. name: 'address',
  222. match: 'strict',
  223. mode: 'value',
  224. inputFormatter: f.formatInputInt,
  225. outputFormatter: f.formatOutputAddress
  226. }),
  227. new SolidityType({
  228. name: 'bool',
  229. match: 'strict',
  230. mode: 'value',
  231. inputFormatter: f.formatInputBool,
  232. outputFormatter: f.formatOutputBool
  233. }),
  234. new SolidityType({
  235. name: 'int',
  236. match: 'prefix',
  237. mode: 'value',
  238. inputFormatter: f.formatInputInt,
  239. outputFormatter: f.formatOutputInt,
  240. }),
  241. new SolidityType({
  242. name: 'uint',
  243. match: 'prefix',
  244. mode: 'value',
  245. inputFormatter: f.formatInputInt,
  246. outputFormatter: f.formatOutputUInt
  247. }),
  248. new SolidityType({
  249. name: 'bytes',
  250. match: 'strict',
  251. mode: 'bytes',
  252. inputFormatter: f.formatInputDynamicBytes,
  253. outputFormatter: f.formatOutputDynamicBytes
  254. }),
  255. new SolidityType({
  256. name: 'bytes',
  257. match: 'prefix',
  258. mode: 'value',
  259. inputFormatter: f.formatInputBytes,
  260. outputFormatter: f.formatOutputBytes
  261. }),
  262. new SolidityType({
  263. name: 'string',
  264. match: 'strict',
  265. mode: 'bytes',
  266. inputFormatter: f.formatInputString,
  267. outputFormatter: f.formatOutputString
  268. }),
  269. new SolidityType({
  270. name: 'real',
  271. match: 'prefix',
  272. mode: 'value',
  273. inputFormatter: f.formatInputReal,
  274. outputFormatter: f.formatOutputReal
  275. }),
  276. new SolidityType({
  277. name: 'ureal',
  278. match: 'prefix',
  279. mode: 'value',
  280. inputFormatter: f.formatInputReal,
  281. outputFormatter: f.formatOutputUReal
  282. })
  283. ]);
  284. module.exports = coder;
  285. },{"../utils/utils":7,"./formatters":2,"./param":3,"bignumber.js":"bignumber.js"}],2:[function(require,module,exports){
  286. /*
  287. This file is part of ethereum.js.
  288. ethereum.js is free software: you can redistribute it and/or modify
  289. it under the terms of the GNU Lesser General Public License as published by
  290. the Free Software Foundation, either version 3 of the License, or
  291. (at your option) any later version.
  292. ethereum.js is distributed in the hope that it will be useful,
  293. but WITHOUT ANY WARRANTY; without even the implied warranty of
  294. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  295. GNU Lesser General Public License for more details.
  296. You should have received a copy of the GNU Lesser General Public License
  297. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  298. */
  299. /**
  300. * @file formatters.js
  301. * @author Marek Kotewicz <marek@ethdev.com>
  302. * @date 2015
  303. */
  304. var BigNumber = require('bignumber.js');
  305. var utils = require('../utils/utils');
  306. var c = require('../utils/config');
  307. var SolidityParam = require('./param');
  308. /**
  309. * Formats input value to byte representation of int
  310. * If value is negative, return it's two's complement
  311. * If the value is floating point, round it down
  312. *
  313. * @method formatInputInt
  314. * @param {String|Number|BigNumber} value that needs to be formatted
  315. * @returns {SolidityParam}
  316. */
  317. var formatInputInt = function (value) {
  318. var padding = c.ETH_PADDING * 2;
  319. BigNumber.config(c.ETH_BIGNUMBER_ROUNDING_MODE);
  320. var result = utils.padLeft(utils.toTwosComplement(value).round().toString(16), padding);
  321. return new SolidityParam(result);
  322. };
  323. /**
  324. * Formats input bytes
  325. *
  326. * @method formatInputBytes
  327. * @param {String}
  328. * @returns {SolidityParam}
  329. */
  330. var formatInputBytes = function (value) {
  331. var result = utils.padRight(utils.toHex(value).substr(2), 64);
  332. return new SolidityParam(result);
  333. };
  334. /**
  335. * Formats input bytes
  336. *
  337. * @method formatDynamicInputBytes
  338. * @param {String}
  339. * @returns {SolidityParam}
  340. */
  341. var formatInputDynamicBytes = function (value) {
  342. value = utils.toHex(value).substr(2);
  343. var l = Math.floor((value.length + 63) / 64);
  344. var result = utils.padRight(value, l * 64);
  345. var length = Math.floor(value.length / 2);
  346. return new SolidityParam(formatInputInt(length).value + result, 32);
  347. };
  348. /**
  349. * Formats input value to byte representation of string
  350. *
  351. * @method formatInputString
  352. * @param {String}
  353. * @returns {SolidityParam}
  354. */
  355. var formatInputString = function (value) {
  356. var result = utils.fromAscii(value).substr(2);
  357. var l = Math.floor((result.length + 63) / 64);
  358. result = utils.padRight(result, l * 64);
  359. return new SolidityParam(formatInputInt(value.length).value + result, 32);
  360. };
  361. /**
  362. * Formats input value to byte representation of bool
  363. *
  364. * @method formatInputBool
  365. * @param {Boolean}
  366. * @returns {SolidityParam}
  367. */
  368. var formatInputBool = function (value) {
  369. var result = '000000000000000000000000000000000000000000000000000000000000000' + (value ? '1' : '0');
  370. return new SolidityParam(result);
  371. };
  372. /**
  373. * Formats input value to byte representation of real
  374. * Values are multiplied by 2^m and encoded as integers
  375. *
  376. * @method formatInputReal
  377. * @param {String|Number|BigNumber}
  378. * @returns {SolidityParam}
  379. */
  380. var formatInputReal = function (value) {
  381. return formatInputInt(new BigNumber(value).times(new BigNumber(2).pow(128)));
  382. };
  383. /**
  384. * Check if input value is negative
  385. *
  386. * @method signedIsNegative
  387. * @param {String} value is hex format
  388. * @returns {Boolean} true if it is negative, otherwise false
  389. */
  390. var signedIsNegative = function (value) {
  391. return (new BigNumber(value.substr(0, 1), 16).toString(2).substr(0, 1)) === '1';
  392. };
  393. /**
  394. * Formats right-aligned output bytes to int
  395. *
  396. * @method formatOutputInt
  397. * @param {SolidityParam} param
  398. * @returns {BigNumber} right-aligned output bytes formatted to big number
  399. */
  400. var formatOutputInt = function (param) {
  401. var value = param.staticPart() || "0";
  402. // check if it's negative number
  403. // it it is, return two's complement
  404. if (signedIsNegative(value)) {
  405. return new BigNumber(value, 16).minus(new BigNumber('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16)).minus(1);
  406. }
  407. return new BigNumber(value, 16);
  408. };
  409. /**
  410. * Formats right-aligned output bytes to uint
  411. *
  412. * @method formatOutputUInt
  413. * @param {SolidityParam}
  414. * @returns {BigNumeber} right-aligned output bytes formatted to uint
  415. */
  416. var formatOutputUInt = function (param) {
  417. var value = param.staticPart() || "0";
  418. return new BigNumber(value, 16);
  419. };
  420. /**
  421. * Formats right-aligned output bytes to real
  422. *
  423. * @method formatOutputReal
  424. * @param {SolidityParam}
  425. * @returns {BigNumber} input bytes formatted to real
  426. */
  427. var formatOutputReal = function (param) {
  428. return formatOutputInt(param).dividedBy(new BigNumber(2).pow(128));
  429. };
  430. /**
  431. * Formats right-aligned output bytes to ureal
  432. *
  433. * @method formatOutputUReal
  434. * @param {SolidityParam}
  435. * @returns {BigNumber} input bytes formatted to ureal
  436. */
  437. var formatOutputUReal = function (param) {
  438. return formatOutputUInt(param).dividedBy(new BigNumber(2).pow(128));
  439. };
  440. /**
  441. * Should be used to format output bool
  442. *
  443. * @method formatOutputBool
  444. * @param {SolidityParam}
  445. * @returns {Boolean} right-aligned input bytes formatted to bool
  446. */
  447. var formatOutputBool = function (param) {
  448. return param.staticPart() === '0000000000000000000000000000000000000000000000000000000000000001' ? true : false;
  449. };
  450. /**
  451. * Should be used to format output bytes
  452. *
  453. * @method formatOutputBytes
  454. * @param {SolidityParam} left-aligned hex representation of string
  455. * @returns {String} hex string
  456. */
  457. var formatOutputBytes = function (param) {
  458. return '0x' + param.staticPart();
  459. };
  460. /**
  461. * Should be used to format output bytes
  462. *
  463. * @method formatOutputDynamicBytes
  464. * @param {SolidityParam} left-aligned hex representation of string
  465. * @returns {String} hex string
  466. */
  467. var formatOutputDynamicBytes = function (param) {
  468. var length = (new BigNumber(param.dynamicPart().slice(0, 64), 16)).toNumber() * 2;
  469. return '0x' + param.dynamicPart().substr(64, length);
  470. };
  471. /**
  472. * Should be used to format output string
  473. *
  474. * @method formatOutputString
  475. * @param {SolidityParam} left-aligned hex representation of string
  476. * @returns {String} ascii string
  477. */
  478. var formatOutputString = function (param) {
  479. var length = (new BigNumber(param.dynamicPart().slice(0, 64), 16)).toNumber() * 2;
  480. return utils.toAscii(param.dynamicPart().substr(64, length));
  481. };
  482. /**
  483. * Should be used to format output address
  484. *
  485. * @method formatOutputAddress
  486. * @param {SolidityParam} right-aligned input bytes
  487. * @returns {String} address
  488. */
  489. var formatOutputAddress = function (param) {
  490. var value = param.staticPart();
  491. return "0x" + value.slice(value.length - 40, value.length);
  492. };
  493. module.exports = {
  494. formatInputInt: formatInputInt,
  495. formatInputBytes: formatInputBytes,
  496. formatInputDynamicBytes: formatInputDynamicBytes,
  497. formatInputString: formatInputString,
  498. formatInputBool: formatInputBool,
  499. formatInputReal: formatInputReal,
  500. formatOutputInt: formatOutputInt,
  501. formatOutputUInt: formatOutputUInt,
  502. formatOutputReal: formatOutputReal,
  503. formatOutputUReal: formatOutputUReal,
  504. formatOutputBool: formatOutputBool,
  505. formatOutputBytes: formatOutputBytes,
  506. formatOutputDynamicBytes: formatOutputDynamicBytes,
  507. formatOutputString: formatOutputString,
  508. formatOutputAddress: formatOutputAddress
  509. };
  510. },{"../utils/config":5,"../utils/utils":7,"./param":3,"bignumber.js":"bignumber.js"}],3:[function(require,module,exports){
  511. /*
  512. This file is part of ethereum.js.
  513. ethereum.js is free software: you can redistribute it and/or modify
  514. it under the terms of the GNU Lesser General Public License as published by
  515. the Free Software Foundation, either version 3 of the License, or
  516. (at your option) any later version.
  517. ethereum.js is distributed in the hope that it will be useful,
  518. but WITHOUT ANY WARRANTY; without even the implied warranty of
  519. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  520. GNU Lesser General Public License for more details.
  521. You should have received a copy of the GNU Lesser General Public License
  522. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  523. */
  524. /**
  525. * @file param.js
  526. * @author Marek Kotewicz <marek@ethdev.com>
  527. * @date 2015
  528. */
  529. var utils = require('../utils/utils');
  530. /**
  531. * SolidityParam object prototype.
  532. * Should be used when encoding, decoding solidity bytes
  533. */
  534. var SolidityParam = function (value, offset) {
  535. this.value = value || '';
  536. this.offset = offset; // offset in bytes
  537. };
  538. /**
  539. * This method should be used to get length of params's dynamic part
  540. *
  541. * @method dynamicPartLength
  542. * @returns {Number} length of dynamic part (in bytes)
  543. */
  544. SolidityParam.prototype.dynamicPartLength = function () {
  545. return this.dynamicPart().length / 2;
  546. };
  547. /**
  548. * This method should be used to create copy of solidity param with different offset
  549. *
  550. * @method withOffset
  551. * @param {Number} offset length in bytes
  552. * @returns {SolidityParam} new solidity param with applied offset
  553. */
  554. SolidityParam.prototype.withOffset = function (offset) {
  555. return new SolidityParam(this.value, offset);
  556. };
  557. /**
  558. * This method should be used to combine solidity params together
  559. * eg. when appending an array
  560. *
  561. * @method combine
  562. * @param {SolidityParam} param with which we should combine
  563. * @param {SolidityParam} result of combination
  564. */
  565. SolidityParam.prototype.combine = function (param) {
  566. return new SolidityParam(this.value + param.value);
  567. };
  568. /**
  569. * This method should be called to check if param has dynamic size.
  570. * If it has, it returns true, otherwise false
  571. *
  572. * @method isDynamic
  573. * @returns {Boolean}
  574. */
  575. SolidityParam.prototype.isDynamic = function () {
  576. return this.value.length > 64 || this.offset !== undefined;
  577. };
  578. /**
  579. * This method should be called to transform offset to bytes
  580. *
  581. * @method offsetAsBytes
  582. * @returns {String} bytes representation of offset
  583. */
  584. SolidityParam.prototype.offsetAsBytes = function () {
  585. return !this.isDynamic() ? '' : utils.padLeft(utils.toTwosComplement(this.offset).toString(16), 64);
  586. };
  587. /**
  588. * This method should be called to get static part of param
  589. *
  590. * @method staticPart
  591. * @returns {String} offset if it is a dynamic param, otherwise value
  592. */
  593. SolidityParam.prototype.staticPart = function () {
  594. if (!this.isDynamic()) {
  595. return this.value;
  596. }
  597. return this.offsetAsBytes();
  598. };
  599. /**
  600. * This method should be called to get dynamic part of param
  601. *
  602. * @method dynamicPart
  603. * @returns {String} returns a value if it is a dynamic param, otherwise empty string
  604. */
  605. SolidityParam.prototype.dynamicPart = function () {
  606. return this.isDynamic() ? this.value : '';
  607. };
  608. /**
  609. * This method should be called to encode param
  610. *
  611. * @method encode
  612. * @returns {String}
  613. */
  614. SolidityParam.prototype.encode = function () {
  615. return this.staticPart() + this.dynamicPart();
  616. };
  617. /**
  618. * This method should be called to encode array of params
  619. *
  620. * @method encodeList
  621. * @param {Array[SolidityParam]} params
  622. * @returns {String}
  623. */
  624. SolidityParam.encodeList = function (params) {
  625. // updating offsets
  626. var totalOffset = params.length * 32;
  627. var offsetParams = params.map(function (param) {
  628. if (!param.isDynamic()) {
  629. return param;
  630. }
  631. var offset = totalOffset;
  632. totalOffset += param.dynamicPartLength();
  633. return param.withOffset(offset);
  634. });
  635. // encode everything!
  636. return offsetParams.reduce(function (result, param) {
  637. return result + param.dynamicPart();
  638. }, offsetParams.reduce(function (result, param) {
  639. return result + param.staticPart();
  640. }, ''));
  641. };
  642. /**
  643. * This method should be used to decode plain (static) solidity param at given index
  644. *
  645. * @method decodeParam
  646. * @param {String} bytes
  647. * @param {Number} index
  648. * @returns {SolidityParam}
  649. */
  650. SolidityParam.decodeParam = function (bytes, index) {
  651. index = index || 0;
  652. return new SolidityParam(bytes.substr(index * 64, 64));
  653. };
  654. /**
  655. * This method should be called to get offset value from bytes at given index
  656. *
  657. * @method getOffset
  658. * @param {String} bytes
  659. * @param {Number} index
  660. * @returns {Number} offset as number
  661. */
  662. var getOffset = function (bytes, index) {
  663. // we can do this cause offset is rather small
  664. return parseInt('0x' + bytes.substr(index * 64, 64));
  665. };
  666. /**
  667. * This method should be called to decode solidity bytes param at given index
  668. *
  669. * @method decodeBytes
  670. * @param {String} bytes
  671. * @param {Number} index
  672. * @returns {SolidityParam}
  673. */
  674. SolidityParam.decodeBytes = function (bytes, index) {
  675. index = index || 0;
  676. var offset = getOffset(bytes, index);
  677. var l = parseInt('0x' + bytes.substr(offset * 2, 64));
  678. l = Math.floor((l + 31) / 32);
  679. // (1 + l) * , cause we also parse length
  680. return new SolidityParam(bytes.substr(offset * 2, (1 + l) * 64), 0);
  681. };
  682. /**
  683. * This method should be used to decode solidity array at given index
  684. *
  685. * @method decodeArray
  686. * @param {String} bytes
  687. * @param {Number} index
  688. * @returns {SolidityParam}
  689. */
  690. SolidityParam.decodeArray = function (bytes, index) {
  691. index = index || 0;
  692. var offset = getOffset(bytes, index);
  693. var length = parseInt('0x' + bytes.substr(offset * 2, 64));
  694. return new SolidityParam(bytes.substr(offset * 2, (length + 1) * 64), 0);
  695. };
  696. module.exports = SolidityParam;
  697. },{"../utils/utils":7}],4:[function(require,module,exports){
  698. 'use strict';
  699. // go env doesn't have and need XMLHttpRequest
  700. if (typeof XMLHttpRequest === 'undefined') {
  701. exports.XMLHttpRequest = {};
  702. } else {
  703. exports.XMLHttpRequest = XMLHttpRequest; // jshint ignore:line
  704. }
  705. },{}],5:[function(require,module,exports){
  706. /*
  707. This file is part of ethereum.js.
  708. ethereum.js is free software: you can redistribute it and/or modify
  709. it under the terms of the GNU Lesser General Public License as published by
  710. the Free Software Foundation, either version 3 of the License, or
  711. (at your option) any later version.
  712. ethereum.js is distributed in the hope that it will be useful,
  713. but WITHOUT ANY WARRANTY; without even the implied warranty of
  714. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  715. GNU Lesser General Public License for more details.
  716. You should have received a copy of the GNU Lesser General Public License
  717. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  718. */
  719. /** @file config.js
  720. * @authors:
  721. * Marek Kotewicz <marek@ethdev.com>
  722. * @date 2015
  723. */
  724. /**
  725. * Utils
  726. *
  727. * @module utils
  728. */
  729. /**
  730. * Utility functions
  731. *
  732. * @class [utils] config
  733. * @constructor
  734. */
  735. /// required to define ETH_BIGNUMBER_ROUNDING_MODE
  736. var BigNumber = require('bignumber.js');
  737. var ETH_UNITS = [
  738. 'wei',
  739. 'kwei',
  740. 'Mwei',
  741. 'Gwei',
  742. 'szabo',
  743. 'finney',
  744. 'femtoether',
  745. 'picoether',
  746. 'nanoether',
  747. 'microether',
  748. 'milliether',
  749. 'nano',
  750. 'micro',
  751. 'milli',
  752. 'ether',
  753. 'grand',
  754. 'Mether',
  755. 'Gether',
  756. 'Tether',
  757. 'Pether',
  758. 'Eether',
  759. 'Zether',
  760. 'Yether',
  761. 'Nether',
  762. 'Dether',
  763. 'Vether',
  764. 'Uether'
  765. ];
  766. module.exports = {
  767. ETH_PADDING: 32,
  768. ETH_SIGNATURE_LENGTH: 4,
  769. ETH_UNITS: ETH_UNITS,
  770. ETH_BIGNUMBER_ROUNDING_MODE: { ROUNDING_MODE: BigNumber.ROUND_DOWN },
  771. ETH_POLLING_TIMEOUT: 1000/2,
  772. defaultBlock: 'latest',
  773. defaultAccount: undefined
  774. };
  775. },{"bignumber.js":"bignumber.js"}],6:[function(require,module,exports){
  776. /*
  777. This file is part of ethereum.js.
  778. ethereum.js is free software: you can redistribute it and/or modify
  779. it under the terms of the GNU Lesser General Public License as published by
  780. the Free Software Foundation, either version 3 of the License, or
  781. (at your option) any later version.
  782. ethereum.js is distributed in the hope that it will be useful,
  783. but WITHOUT ANY WARRANTY; without even the implied warranty of
  784. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  785. GNU Lesser General Public License for more details.
  786. You should have received a copy of the GNU Lesser General Public License
  787. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  788. */
  789. /**
  790. * @file sha3.js
  791. * @author Marek Kotewicz <marek@ethdev.com>
  792. * @date 2015
  793. */
  794. var utils = require('./utils');
  795. var sha3 = require('crypto-js/sha3');
  796. module.exports = function (str, isNew) {
  797. if (str.substr(0, 2) === '0x' && !isNew) {
  798. console.warn('requirement of using web3.fromAscii before sha3 is deprecated');
  799. console.warn('new usage: \'web3.sha3("hello")\'');
  800. console.warn('see https://github.com/ethereum/web3.js/pull/205');
  801. console.warn('if you need to hash hex value, you can do \'sha3("0xfff", true)\'');
  802. str = utils.toAscii(str);
  803. }
  804. return sha3(str, {
  805. outputLength: 256
  806. }).toString();
  807. };
  808. },{"./utils":7,"crypto-js/sha3":34}],7:[function(require,module,exports){
  809. /*
  810. This file is part of ethereum.js.
  811. ethereum.js is free software: you can redistribute it and/or modify
  812. it under the terms of the GNU Lesser General Public License as published by
  813. the Free Software Foundation, either version 3 of the License, or
  814. (at your option) any later version.
  815. ethereum.js is distributed in the hope that it will be useful,
  816. but WITHOUT ANY WARRANTY; without even the implied warranty of
  817. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  818. GNU Lesser General Public License for more details.
  819. You should have received a copy of the GNU Lesser General Public License
  820. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  821. */
  822. /**
  823. * @file utils.js
  824. * @author Marek Kotewicz <marek@ethdev.com>
  825. * @date 2015
  826. */
  827. /**
  828. * Utils
  829. *
  830. * @module utils
  831. */
  832. /**
  833. * Utility functions
  834. *
  835. * @class [utils] utils
  836. * @constructor
  837. */
  838. var BigNumber = require('bignumber.js');
  839. var unitMap = {
  840. 'wei': '1',
  841. 'kwei': '1000',
  842. 'ada': '1000',
  843. 'femtoether': '1000',
  844. 'mwei': '1000000',
  845. 'babbage': '1000000',
  846. 'picoether': '1000000',
  847. 'gwei': '1000000000',
  848. 'shannon': '1000000000',
  849. 'nanoether': '1000000000',
  850. 'nano': '1000000000',
  851. 'szabo': '1000000000000',
  852. 'microether': '1000000000000',
  853. 'micro': '1000000000000',
  854. 'finney': '1000000000000000',
  855. 'milliether': '1000000000000000',
  856. 'milli': '1000000000000000',
  857. 'ether': '1000000000000000000',
  858. 'kether': '1000000000000000000000',
  859. 'grand': '1000000000000000000000',
  860. 'einstein': '1000000000000000000000',
  861. 'mether': '1000000000000000000000000',
  862. 'gether': '1000000000000000000000000000',
  863. 'tether': '1000000000000000000000000000000'
  864. };
  865. /**
  866. * Should be called to pad string to expected length
  867. *
  868. * @method padLeft
  869. * @param {String} string to be padded
  870. * @param {Number} characters that result string should have
  871. * @param {String} sign, by default 0
  872. * @returns {String} right aligned string
  873. */
  874. var padLeft = function (string, chars, sign) {
  875. return new Array(chars - string.length + 1).join(sign ? sign : "0") + string;
  876. };
  877. /**
  878. * Should be called to pad string to expected length
  879. *
  880. * @method padRight
  881. * @param {String} string to be padded
  882. * @param {Number} characters that result string should have
  883. * @param {String} sign, by default 0
  884. * @returns {String} right aligned string
  885. */
  886. var padRight = function (string, chars, sign) {
  887. return string + (new Array(chars - string.length + 1).join(sign ? sign : "0"));
  888. };
  889. /**
  890. * Should be called to get sting from it's hex representation
  891. *
  892. * @method toAscii
  893. * @param {String} string in hex
  894. * @returns {String} ascii string representation of hex value
  895. */
  896. var toAscii = function(hex) {
  897. // Find termination
  898. var str = "";
  899. var i = 0, l = hex.length;
  900. if (hex.substring(0, 2) === '0x') {
  901. i = 2;
  902. }
  903. for (; i < l; i+=2) {
  904. var code = parseInt(hex.substr(i, 2), 16);
  905. str += String.fromCharCode(code);
  906. }
  907. return str;
  908. };
  909. /**
  910. * Shold be called to get hex representation (prefixed by 0x) of ascii string
  911. *
  912. * @method toHexNative
  913. * @param {String} string
  914. * @returns {String} hex representation of input string
  915. */
  916. var toHexNative = function(str) {
  917. var hex = "";
  918. for(var i = 0; i < str.length; i++) {
  919. var n = str.charCodeAt(i).toString(16);
  920. hex += n.length < 2 ? '0' + n : n;
  921. }
  922. return hex;
  923. };
  924. /**
  925. * Shold be called to get hex representation (prefixed by 0x) of ascii string
  926. *
  927. * @method fromAscii
  928. * @param {String} string
  929. * @param {Number} optional padding
  930. * @returns {String} hex representation of input string
  931. */
  932. var fromAscii = function(str, pad) {
  933. pad = pad === undefined ? 0 : pad;
  934. var hex = toHexNative(str);
  935. while (hex.length < pad*2)
  936. hex += "00";
  937. return "0x" + hex;
  938. };
  939. /**
  940. * Should be used to create full function/event name from json abi
  941. *
  942. * @method transformToFullName
  943. * @param {Object} json-abi
  944. * @return {String} full fnction/event name
  945. */
  946. var transformToFullName = function (json) {
  947. if (json.name.indexOf('(') !== -1) {
  948. return json.name;
  949. }
  950. var typeName = json.inputs.map(function(i){return i.type; }).join();
  951. return json.name + '(' + typeName + ')';
  952. };
  953. /**
  954. * Should be called to get display name of contract function
  955. *
  956. * @method extractDisplayName
  957. * @param {String} name of function/event
  958. * @returns {String} display name for function/event eg. multiply(uint256) -> multiply
  959. */
  960. var extractDisplayName = function (name) {
  961. var length = name.indexOf('(');
  962. return length !== -1 ? name.substr(0, length) : name;
  963. };
  964. /// @returns overloaded part of function/event name
  965. var extractTypeName = function (name) {
  966. /// TODO: make it invulnerable
  967. var length = name.indexOf('(');
  968. return length !== -1 ? name.substr(length + 1, name.length - 1 - (length + 1)).replace(' ', '') : "";
  969. };
  970. /**
  971. * Converts value to it's decimal representation in string
  972. *
  973. * @method toDecimal
  974. * @param {String|Number|BigNumber}
  975. * @return {String}
  976. */
  977. var toDecimal = function (value) {
  978. return toBigNumber(value).toNumber();
  979. };
  980. /**
  981. * Converts value to it's hex representation
  982. *
  983. * @method fromDecimal
  984. * @param {String|Number|BigNumber}
  985. * @return {String}
  986. */
  987. var fromDecimal = function (value) {
  988. var number = toBigNumber(value);
  989. var result = number.toString(16);
  990. return number.lessThan(0) ? '-0x' + result.substr(1) : '0x' + result;
  991. };
  992. /**
  993. * Auto converts any given value into it's hex representation.
  994. *
  995. * And even stringifys objects before.
  996. *
  997. * @method toHex
  998. * @param {String|Number|BigNumber|Object}
  999. * @return {String}
  1000. */
  1001. var toHex = function (val) {
  1002. /*jshint maxcomplexity: 8 */
  1003. if (isBoolean(val))
  1004. return fromDecimal(+val);
  1005. if (isBigNumber(val))
  1006. return fromDecimal(val);
  1007. if (isObject(val))
  1008. return fromAscii(JSON.stringify(val));
  1009. // if its a negative number, pass it through fromDecimal
  1010. if (isString(val)) {
  1011. if (val.indexOf('-0x') === 0)
  1012. return fromDecimal(val);
  1013. else if (!isFinite(val))
  1014. return fromAscii(val);
  1015. else if(val.indexOf('0x') === 0)
  1016. return val;
  1017. }
  1018. return fromDecimal(val);
  1019. };
  1020. /**
  1021. * Returns value of unit in Wei
  1022. *
  1023. * @method getValueOfUnit
  1024. * @param {String} unit the unit to convert to, default ether
  1025. * @returns {BigNumber} value of the unit (in Wei)
  1026. * @throws error if the unit is not correct:w
  1027. */
  1028. var getValueOfUnit = function (unit) {
  1029. unit = unit ? unit.toLowerCase() : 'ether';
  1030. var unitValue = unitMap[unit];
  1031. if (unitValue === undefined) {
  1032. throw new Error('This unit doesn\'t exists, please use the one of the following units' + JSON.stringify(unitMap, null, 2));
  1033. }
  1034. return new BigNumber(unitValue, 10);
  1035. };
  1036. /**
  1037. * Takes a number of wei and converts it to any other ether unit.
  1038. *
  1039. * Possible units are:
  1040. * SI Short SI Full Effigy Other
  1041. * - kwei femtoether ada
  1042. * - mwei picoether babbage
  1043. * - gwei nanoether shannon nano
  1044. * - -- microether szabo micro
  1045. * - -- milliether finney milli
  1046. * - ether -- --
  1047. * - kether einstein grand
  1048. * - mether
  1049. * - gether
  1050. * - tether
  1051. *
  1052. * @method fromWei
  1053. * @param {Number|String} number can be a number, number string or a HEX of a decimal
  1054. * @param {String} unit the unit to convert to, default ether
  1055. * @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number
  1056. */
  1057. var fromWei = function(number, unit) {
  1058. var returnValue = toBigNumber(number).dividedBy(getValueOfUnit(unit));
  1059. return isBigNumber(number) ? returnValue : returnValue.toString(10);
  1060. };
  1061. /**
  1062. * Takes a number of a unit and converts it to wei.
  1063. *
  1064. * Possible units are:
  1065. * SI Short SI Full Effigy Other
  1066. * - kwei femtoether ada
  1067. * - mwei picoether babbage
  1068. * - gwei nanoether shannon nano
  1069. * - -- microether szabo micro
  1070. * - -- milliether finney milli
  1071. * - ether -- --
  1072. * - kether einstein grand
  1073. * - mether
  1074. * - gether
  1075. * - tether
  1076. *
  1077. * @method toWei
  1078. * @param {Number|String|BigNumber} number can be a number, number string or a HEX of a decimal
  1079. * @param {String} unit the unit to convert from, default ether
  1080. * @return {String|Object} When given a BigNumber object it returns one as well, otherwise a number
  1081. */
  1082. var toWei = function(number, unit) {
  1083. var returnValue = toBigNumber(number).times(getValueOfUnit(unit));
  1084. return isBigNumber(number) ? returnValue : returnValue.toString(10);
  1085. };
  1086. /**
  1087. * Takes an input and transforms it into an bignumber
  1088. *
  1089. * @method toBigNumber
  1090. * @param {Number|String|BigNumber} a number, string, HEX string or BigNumber
  1091. * @return {BigNumber} BigNumber
  1092. */
  1093. var toBigNumber = function(number) {
  1094. /*jshint maxcomplexity:5 */
  1095. number = number || 0;
  1096. if (isBigNumber(number))
  1097. return number;
  1098. if (isString(number) && (number.indexOf('0x') === 0 || number.indexOf('-0x') === 0)) {
  1099. return new BigNumber(number.replace('0x',''), 16);
  1100. }
  1101. return new BigNumber(number.toString(10), 10);
  1102. };
  1103. /**
  1104. * Takes and input transforms it into bignumber and if it is negative value, into two's complement
  1105. *
  1106. * @method toTwosComplement
  1107. * @param {Number|String|BigNumber}
  1108. * @return {BigNumber}
  1109. */
  1110. var toTwosComplement = function (number) {
  1111. var bigNumber = toBigNumber(number);
  1112. if (bigNumber.lessThan(0)) {
  1113. return new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).plus(bigNumber).plus(1);
  1114. }
  1115. return bigNumber;
  1116. };
  1117. /**
  1118. * Checks if the given string is strictly an address
  1119. *
  1120. * @method isStrictAddress
  1121. * @param {String} address the given HEX adress
  1122. * @return {Boolean}
  1123. */
  1124. var isStrictAddress = function (address) {
  1125. return /^0x[0-9a-f]{40}$/.test(address);
  1126. };
  1127. /**
  1128. * Checks if the given string is an address
  1129. *
  1130. * @method isAddress
  1131. * @param {String} address the given HEX adress
  1132. * @return {Boolean}
  1133. */
  1134. var isAddress = function (address) {
  1135. return /^(0x)?[0-9a-f]{40}$/.test(address);
  1136. };
  1137. /**
  1138. * Transforms given string to valid 20 bytes-length addres with 0x prefix
  1139. *
  1140. * @method toAddress
  1141. * @param {String} address
  1142. * @return {String} formatted address
  1143. */
  1144. var toAddress = function (address) {
  1145. if (isStrictAddress(address)) {
  1146. return address;
  1147. }
  1148. if (/^[0-9a-f]{40}$/.test(address)) {
  1149. return '0x' + address;
  1150. }
  1151. return '0x' + padLeft(toHex(address).substr(2), 40);
  1152. };
  1153. /**
  1154. * Returns true if object is BigNumber, otherwise false
  1155. *
  1156. * @method isBigNumber
  1157. * @param {Object}
  1158. * @return {Boolean}
  1159. */
  1160. var isBigNumber = function (object) {
  1161. return object instanceof BigNumber ||
  1162. (object && object.constructor && object.constructor.name === 'BigNumber');
  1163. };
  1164. /**
  1165. * Returns true if object is string, otherwise false
  1166. *
  1167. * @method isString
  1168. * @param {Object}
  1169. * @return {Boolean}
  1170. */
  1171. var isString = function (object) {
  1172. return typeof object === 'string' ||
  1173. (object && object.constructor && object.constructor.name === 'String');
  1174. };
  1175. /**
  1176. * Returns true if object is function, otherwise false
  1177. *
  1178. * @method isFunction
  1179. * @param {Object}
  1180. * @return {Boolean}
  1181. */
  1182. var isFunction = function (object) {
  1183. return typeof object === 'function';
  1184. };
  1185. /**
  1186. * Returns true if object is Objet, otherwise false
  1187. *
  1188. * @method isObject
  1189. * @param {Object}
  1190. * @return {Boolean}
  1191. */
  1192. var isObject = function (object) {
  1193. return typeof object === 'object';
  1194. };
  1195. /**
  1196. * Returns true if object is boolean, otherwise false
  1197. *
  1198. * @method isBoolean
  1199. * @param {Object}
  1200. * @return {Boolean}
  1201. */
  1202. var isBoolean = function (object) {
  1203. return typeof object === 'boolean';
  1204. };
  1205. /**
  1206. * Returns true if object is array, otherwise false
  1207. *
  1208. * @method isArray
  1209. * @param {Object}
  1210. * @return {Boolean}
  1211. */
  1212. var isArray = function (object) {
  1213. return object instanceof Array;
  1214. };
  1215. /**
  1216. * Returns true if given string is valid json object
  1217. *
  1218. * @method isJson
  1219. * @param {String}
  1220. * @return {Boolean}
  1221. */
  1222. var isJson = function (str) {
  1223. try {
  1224. return !!JSON.parse(str);
  1225. } catch (e) {
  1226. return false;
  1227. }
  1228. };
  1229. /**
  1230. * This method should be called to check if string is valid ethereum IBAN number
  1231. * Supports direct and indirect IBANs
  1232. *
  1233. * @method isIBAN
  1234. * @param {String}
  1235. * @return {Boolean}
  1236. */
  1237. var isIBAN = function (iban) {
  1238. return /^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30})$/.test(iban);
  1239. };
  1240. module.exports = {
  1241. padLeft: padLeft,
  1242. padRight: padRight,
  1243. toHex: toHex,
  1244. toDecimal: toDecimal,
  1245. fromDecimal: fromDecimal,
  1246. toAscii: toAscii,
  1247. fromAscii: fromAscii,
  1248. transformToFullName: transformToFullName,
  1249. extractDisplayName: extractDisplayName,
  1250. extractTypeName: extractTypeName,
  1251. toWei: toWei,
  1252. fromWei: fromWei,
  1253. toBigNumber: toBigNumber,
  1254. toTwosComplement: toTwosComplement,
  1255. toAddress: toAddress,
  1256. isBigNumber: isBigNumber,
  1257. isStrictAddress: isStrictAddress,
  1258. isAddress: isAddress,
  1259. isFunction: isFunction,
  1260. isString: isString,
  1261. isObject: isObject,
  1262. isBoolean: isBoolean,
  1263. isArray: isArray,
  1264. isJson: isJson,
  1265. isIBAN: isIBAN
  1266. };
  1267. },{"bignumber.js":"bignumber.js"}],8:[function(require,module,exports){
  1268. module.exports={
  1269. "version": "0.8.0"
  1270. }
  1271. },{}],9:[function(require,module,exports){
  1272. /*
  1273. This file is part of ethereum.js.
  1274. ethereum.js is free software: you can redistribute it and/or modify
  1275. it under the terms of the GNU Lesser General Public License as published by
  1276. the Free Software Foundation, either version 3 of the License, or
  1277. (at your option) any later version.
  1278. ethereum.js is distributed in the hope that it will be useful,
  1279. but WITHOUT ANY WARRANTY; without even the implied warranty of
  1280. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  1281. GNU Lesser General Public License for more details.
  1282. You should have received a copy of the GNU Lesser General Public License
  1283. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  1284. */
  1285. /** @file web3.js
  1286. * @authors:
  1287. * Jeffrey Wilcke <jeff@ethdev.com>
  1288. * Marek Kotewicz <marek@ethdev.com>
  1289. * Marian Oancea <marian@ethdev.com>
  1290. * Fabian Vogelsteller <fabian@ethdev.com>
  1291. * Gav Wood <g@ethdev.com>
  1292. * @date 2014
  1293. */
  1294. var version = require('./version.json');
  1295. var net = require('./web3/net');
  1296. var eth = require('./web3/eth');
  1297. var db = require('./web3/db');
  1298. var shh = require('./web3/shh');
  1299. var watches = require('./web3/watches');
  1300. var Filter = require('./web3/filter');
  1301. var utils = require('./utils/utils');
  1302. var formatters = require('./web3/formatters');
  1303. var RequestManager = require('./web3/requestmanager');
  1304. var c = require('./utils/config');
  1305. var Property = require('./web3/property');
  1306. var Batch = require('./web3/batch');
  1307. var sha3 = require('./utils/sha3');
  1308. var web3Properties = [
  1309. new Property({
  1310. name: 'version.client',
  1311. getter: 'web3_clientVersion'
  1312. }),
  1313. new Property({
  1314. name: 'version.network',
  1315. getter: 'net_version',
  1316. inputFormatter: utils.toDecimal
  1317. }),
  1318. new Property({
  1319. name: 'version.ethereum',
  1320. getter: 'eth_protocolVersion',
  1321. inputFormatter: utils.toDecimal
  1322. }),
  1323. new Property({
  1324. name: 'version.whisper',
  1325. getter: 'shh_version',
  1326. inputFormatter: utils.toDecimal
  1327. })
  1328. ];
  1329. /// creates methods in a given object based on method description on input
  1330. /// setups api calls for these methods
  1331. var setupMethods = function (obj, methods) {
  1332. methods.forEach(function (method) {
  1333. method.attachToObject(obj);
  1334. });
  1335. };
  1336. /// creates properties in a given object based on properties description on input
  1337. /// setups api calls for these properties
  1338. var setupProperties = function (obj, properties) {
  1339. properties.forEach(function (property) {
  1340. property.attachToObject(obj);
  1341. });
  1342. };
  1343. /// setups web3 object, and it's in-browser executed methods
  1344. var web3 = {};
  1345. web3.providers = {};
  1346. web3.currentProvider = null;
  1347. web3.version = {};
  1348. web3.version.api = version.version;
  1349. web3.eth = {};
  1350. /*jshint maxparams:4 */
  1351. web3.eth.filter = function (fil, callback) {
  1352. return new Filter(fil, watches.eth(), formatters.outputLogFormatter, callback);
  1353. };
  1354. /*jshint maxparams:3 */
  1355. web3.shh = {};
  1356. web3.shh.filter = function (fil, callback) {
  1357. return new Filter(fil, watches.shh(), formatters.outputPostFormatter, callback);
  1358. };
  1359. web3.net = {};
  1360. web3.db = {};
  1361. web3.setProvider = function (provider) {
  1362. this.currentProvider = provider;
  1363. RequestManager.getInstance().setProvider(provider);
  1364. };
  1365. web3.reset = function () {
  1366. RequestManager.getInstance().reset();
  1367. c.defaultBlock = 'latest';
  1368. c.defaultAccount = undefined;
  1369. };
  1370. web3.toHex = utils.toHex;
  1371. web3.toAscii = utils.toAscii;
  1372. web3.fromAscii = utils.fromAscii;
  1373. web3.toDecimal = utils.toDecimal;
  1374. web3.fromDecimal = utils.fromDecimal;
  1375. web3.toBigNumber = utils.toBigNumber;
  1376. web3.toWei = utils.toWei;
  1377. web3.fromWei = utils.fromWei;
  1378. web3.isAddress = utils.isAddress;
  1379. web3.isIBAN = utils.isIBAN;
  1380. web3.sha3 = sha3;
  1381. web3.createBatch = function () {
  1382. return new Batch();
  1383. };
  1384. // ADD defaultblock
  1385. Object.defineProperty(web3.eth, 'defaultBlock', {
  1386. get: function () {
  1387. return c.defaultBlock;
  1388. },
  1389. set: function (val) {
  1390. c.defaultBlock = val;
  1391. return val;
  1392. }
  1393. });
  1394. Object.defineProperty(web3.eth, 'defaultAccount', {
  1395. get: function () {
  1396. return c.defaultAccount;
  1397. },
  1398. set: function (val) {
  1399. c.defaultAccount = val;
  1400. return val;
  1401. }
  1402. });
  1403. // EXTEND
  1404. web3._extend = function(extension){
  1405. /*jshint maxcomplexity: 6 */
  1406. if(extension.property && !web3[extension.property])
  1407. web3[extension.property] = {};
  1408. setupMethods(web3[extension.property] || web3, extension.methods || []);
  1409. setupProperties(web3[extension.property] || web3, extension.properties || []);
  1410. };
  1411. web3._extend.formatters = formatters;
  1412. web3._extend.utils = utils;
  1413. web3._extend.Method = require('./web3/method');
  1414. web3._extend.Property = require('./web3/property');
  1415. /// setups all api methods
  1416. setupProperties(web3, web3Properties);
  1417. setupMethods(web3.net, net.methods);
  1418. setupProperties(web3.net, net.properties);
  1419. setupMethods(web3.eth, eth.methods);
  1420. setupProperties(web3.eth, eth.properties);
  1421. setupMethods(web3.db, db.methods);
  1422. setupMethods(web3.shh, shh.methods);
  1423. module.exports = web3;
  1424. },{"./utils/config":5,"./utils/sha3":6,"./utils/utils":7,"./version.json":8,"./web3/batch":11,"./web3/db":13,"./web3/eth":15,"./web3/filter":17,"./web3/formatters":18,"./web3/method":23,"./web3/net":25,"./web3/property":26,"./web3/requestmanager":28,"./web3/shh":29,"./web3/watches":31}],10:[function(require,module,exports){
  1425. /*
  1426. This file is part of ethereum.js.
  1427. ethereum.js is free software: you can redistribute it and/or modify
  1428. it under the terms of the GNU Lesser General Public License as published by
  1429. the Free Software Foundation, either version 3 of the License, or
  1430. (at your option) any later version.
  1431. ethereum.js is distributed in the hope that it will be useful,
  1432. but WITHOUT ANY WARRANTY; without even the implied warranty of
  1433. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  1434. GNU Lesser General Public License for more details.
  1435. You should have received a copy of the GNU Lesser General Public License
  1436. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  1437. */
  1438. /**
  1439. * @file allevents.js
  1440. * @author Marek Kotewicz <marek@ethdev.com>
  1441. * @date 2014
  1442. */
  1443. var sha3 = require('../utils/sha3');
  1444. var SolidityEvent = require('./event');
  1445. var formatters = require('./formatters');
  1446. var utils = require('../utils/utils');
  1447. var Filter = require('./filter');
  1448. var watches = require('./watches');
  1449. var AllSolidityEvents = function (json, address) {
  1450. this._json = json;
  1451. this._address = address;
  1452. };
  1453. AllSolidityEvents.prototype.encode = function (options) {
  1454. options = options || {};
  1455. var result = {};
  1456. ['fromBlock', 'toBlock'].filter(function (f) {
  1457. return options[f] !== undefined;
  1458. }).forEach(function (f) {
  1459. result[f] = formatters.inputBlockNumberFormatter(options[f]);
  1460. });
  1461. result.topics = [null, null, null, null, null]; // match all topics
  1462. result.address = this._address;
  1463. return result;
  1464. };
  1465. AllSolidityEvents.prototype.decode = function (data) {
  1466. data.data = data.data || '';
  1467. data.topics = data.topics || [];
  1468. var eventTopic = data.topics[0].slice(2);
  1469. var match = this._json.filter(function (j) {
  1470. return eventTopic === sha3(utils.transformToFullName(j));
  1471. })[0];
  1472. if (!match) { // cannot find matching event?
  1473. console.warn('cannot find event for log');
  1474. return data;
  1475. }
  1476. var event = new SolidityEvent(match, this._address);
  1477. return event.decode(data);
  1478. };
  1479. AllSolidityEvents.prototype.execute = function (options, callback) {
  1480. var o = this.encode(options);
  1481. var formatter = this.decode.bind(this);
  1482. return new Filter(o, watches.eth(), formatter, callback);
  1483. };
  1484. AllSolidityEvents.prototype.attachToContract = function (contract) {
  1485. var execute = this.execute.bind(this);
  1486. contract.allEvents = execute;
  1487. };
  1488. module.exports = AllSolidityEvents;
  1489. },{"../utils/sha3":6,"../utils/utils":7,"./event":16,"./filter":17,"./formatters":18,"./watches":31}],11:[function(require,module,exports){
  1490. /*
  1491. This file is part of ethereum.js.
  1492. ethereum.js is free software: you can redistribute it and/or modify
  1493. it under the terms of the GNU Lesser General Public License as published by
  1494. the Free Software Foundation, either version 3 of the License, or
  1495. (at your option) any later version.
  1496. ethereum.js is distributed in the hope that it will be useful,
  1497. but WITHOUT ANY WARRANTY; without even the implied warranty of
  1498. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  1499. GNU Lesser General Public License for more details.
  1500. You should have received a copy of the GNU Lesser General Public License
  1501. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  1502. */
  1503. /**
  1504. * @file batch.js
  1505. * @author Marek Kotewicz <marek@ethdev.com>
  1506. * @date 2015
  1507. */
  1508. var RequestManager = require('./requestmanager');
  1509. var Batch = function () {
  1510. this.requests = [];
  1511. };
  1512. /**
  1513. * Should be called to add create new request to batch request
  1514. *
  1515. * @method add
  1516. * @param {Object} jsonrpc requet object
  1517. */
  1518. Batch.prototype.add = function (request) {
  1519. this.requests.push(request);
  1520. };
  1521. /**
  1522. * Should be called to execute batch request
  1523. *
  1524. * @method execute
  1525. */
  1526. Batch.prototype.execute = function () {
  1527. var requests = this.requests;
  1528. RequestManager.getInstance().sendBatch(requests, function (err, results) {
  1529. results = results || [];
  1530. requests.map(function (request, index) {
  1531. return results[index] || {};
  1532. }).map(function (result, index) {
  1533. return requests[index].format ? requests[index].format(result.result) : result.result;
  1534. }).forEach(function (result, index) {
  1535. if (requests[index].callback) {
  1536. requests[index].callback(err, result);
  1537. }
  1538. });
  1539. });
  1540. };
  1541. module.exports = Batch;
  1542. },{"./requestmanager":28}],12:[function(require,module,exports){
  1543. /*
  1544. This file is part of ethereum.js.
  1545. ethereum.js is free software: you can redistribute it and/or modify
  1546. it under the terms of the GNU Lesser General Public License as published by
  1547. the Free Software Foundation, either version 3 of the License, or
  1548. (at your option) any later version.
  1549. ethereum.js is distributed in the hope that it will be useful,
  1550. but WITHOUT ANY WARRANTY; without even the implied warranty of
  1551. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  1552. GNU Lesser General Public License for more details.
  1553. You should have received a copy of the GNU Lesser General Public License
  1554. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  1555. */
  1556. /**
  1557. * @file contract.js
  1558. * @author Marek Kotewicz <marek@ethdev.com>
  1559. * @date 2014
  1560. */
  1561. var web3 = require('../web3');
  1562. var utils = require('../utils/utils');
  1563. var coder = require('../solidity/coder');
  1564. var SolidityEvent = require('./event');
  1565. var SolidityFunction = require('./function');
  1566. var AllEvents = require('./allevents');
  1567. /**
  1568. * Should be called to encode constructor params
  1569. *
  1570. * @method encodeConstructorParams
  1571. * @param {Array} abi
  1572. * @param {Array} constructor params
  1573. */
  1574. var encodeConstructorParams = function (abi, params) {
  1575. return abi.filter(function (json) {
  1576. return json.type === 'constructor' && json.inputs.length === params.length;
  1577. }).map(function (json) {
  1578. return json.inputs.map(function (input) {
  1579. return input.type;
  1580. });
  1581. }).map(function (types) {
  1582. return coder.encodeParams(types, params);
  1583. })[0] || '';
  1584. };
  1585. /**
  1586. * Should be called to add functions to contract object
  1587. *
  1588. * @method addFunctionsToContract
  1589. * @param {Contract} contract
  1590. * @param {Array} abi
  1591. */
  1592. var addFunctionsToContract = function (contract, abi) {
  1593. abi.filter(function (json) {
  1594. return json.type === 'function';
  1595. }).map(function (json) {
  1596. return new SolidityFunction(json, contract.address);
  1597. }).forEach(function (f) {
  1598. f.attachToContract(contract);
  1599. });
  1600. };
  1601. /**
  1602. * Should be called to add events to contract object
  1603. *
  1604. * @method addEventsToContract
  1605. * @param {Contract} contract
  1606. * @param {Array} abi
  1607. */
  1608. var addEventsToContract = function (contract, abi) {
  1609. var events = abi.filter(function (json) {
  1610. return json.type === 'event';
  1611. });
  1612. var All = new AllEvents(events, contract.address);
  1613. All.attachToContract(contract);
  1614. events.map(function (json) {
  1615. return new SolidityEvent(json, contract.address);
  1616. }).forEach(function (e) {
  1617. e.attachToContract(contract);
  1618. });
  1619. };
  1620. /**
  1621. * Should be called to create new ContractFactory
  1622. *
  1623. * @method contract
  1624. * @param {Array} abi
  1625. * @returns {ContractFactory} new contract factory
  1626. */
  1627. var contract = function (abi) {
  1628. return new ContractFactory(abi);
  1629. };
  1630. /**
  1631. * Should be called to create new ContractFactory
  1632. *
  1633. * @method checkForContractAddress
  1634. * @param {Object} contract
  1635. * @param {Function} callback
  1636. * @returns {Undefined}
  1637. */
  1638. var checkForContractAddress = function(contract, callback){
  1639. var count = 0;
  1640. // wait for receipt
  1641. var filter = web3.eth.filter('latest', function(e){
  1642. if(!e) {
  1643. count++;
  1644. // stop watching after 50 blocks (timeout)
  1645. if(count > 50) {
  1646. if(callback)
  1647. callback(new Error('Contract couldn\'t be deployed'));
  1648. filter.stopWatching();
  1649. } else {
  1650. web3.eth.getTransactionReceipt(contract.transactionHash, function(e, receipt){
  1651. if(receipt) {
  1652. web3.eth.getCode(receipt.contractAddress, function(e, code){
  1653. if(code.length > 2) {
  1654. contract.address = receipt.contractAddress;
  1655. if(callback)
  1656. callback(null, contract);
  1657. } else if(callback) {
  1658. callback(new Error('The contract code couldn\'t be stored'));
  1659. }
  1660. filter.stopWatching();
  1661. });
  1662. }
  1663. });
  1664. }
  1665. }
  1666. });
  1667. };
  1668. /**
  1669. * Should be called to create new ContractFactory instance
  1670. *
  1671. * @method ContractFactory
  1672. * @param {Array} abi
  1673. */
  1674. var ContractFactory = function (abi) {
  1675. this.abi = abi;
  1676. };
  1677. /**
  1678. * Should be called to create new contract on a blockchain
  1679. *
  1680. * @method new
  1681. * @param {Any} contract constructor param1 (optional)
  1682. * @param {Any} contract constructor param2 (optional)
  1683. * @param {Object} contract transaction object (required)
  1684. * @param {Function} callback
  1685. * @returns {Contract} returns contract instance
  1686. */
  1687. ContractFactory.prototype.new = function () {
  1688. var contract = new Contract(this.abi);
  1689. // parse arguments
  1690. var options = {}; // required!
  1691. var callback;
  1692. var args = Array.prototype.slice.call(arguments);
  1693. if (utils.isFunction(args[args.length - 1])) {
  1694. callback = args.pop();
  1695. }
  1696. var last = args[args.length - 1];
  1697. if (utils.isObject(last) && !utils.isArray(last)) {
  1698. options = args.pop();
  1699. }
  1700. // throw an error if there are no options
  1701. var bytes = encodeConstructorParams(this.abi, args);
  1702. options.data += bytes;
  1703. if(callback) {
  1704. // wait for the contract address adn check if the code was deployed
  1705. web3.eth.sendTransaction(options, function (err, hash) {
  1706. if (err) {
  1707. callback(err);
  1708. } else {
  1709. // add the transaction hash
  1710. contract.transactionHash = hash;
  1711. checkForContractAddress(contract, callback);
  1712. }
  1713. });
  1714. } else {
  1715. var hash = web3.eth.sendTransaction(options);
  1716. // add the transaction hash
  1717. contract.transactionHash = hash;
  1718. checkForContractAddress(contract);
  1719. }
  1720. return contract;
  1721. };
  1722. /**
  1723. * Should be called to get access to existing contract on a blockchain
  1724. *
  1725. * @method at
  1726. * @param {Address} contract address (required)
  1727. * @param {Function} callback {optional)
  1728. * @returns {Contract} returns contract if no callback was passed,
  1729. * otherwise calls callback function (err, contract)
  1730. */
  1731. ContractFactory.prototype.at = function (address, callback) {
  1732. // TODO: address is required
  1733. if (callback) {
  1734. callback(null, new Contract(this.abi, address));
  1735. }
  1736. return new Contract(this.abi, address);
  1737. };
  1738. /**
  1739. * Should be called to create new contract instance
  1740. *
  1741. * @method Contract
  1742. * @param {Array} abi
  1743. * @param {Address} contract address
  1744. */
  1745. var Contract = function (abi, address) {
  1746. this.address = address;
  1747. addFunctionsToContract(this, abi);
  1748. addEventsToContract(this, abi);
  1749. };
  1750. module.exports = contract;
  1751. },{"../solidity/coder":1,"../utils/utils":7,"../web3":9,"./allevents":10,"./event":16,"./function":19}],13:[function(require,module,exports){
  1752. /*
  1753. This file is part of ethereum.js.
  1754. ethereum.js is free software: you can redistribute it and/or modify
  1755. it under the terms of the GNU Lesser General Public License as published by
  1756. the Free Software Foundation, either version 3 of the License, or
  1757. (at your option) any later version.
  1758. ethereum.js is distributed in the hope that it will be useful,
  1759. but WITHOUT ANY WARRANTY; without even the implied warranty of
  1760. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  1761. GNU Lesser General Public License for more details.
  1762. You should have received a copy of the GNU Lesser General Public License
  1763. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  1764. */
  1765. /** @file db.js
  1766. * @authors:
  1767. * Marek Kotewicz <marek@ethdev.com>
  1768. * @date 2015
  1769. */
  1770. var Method = require('./method');
  1771. var putString = new Method({
  1772. name: 'putString',
  1773. call: 'db_putString',
  1774. params: 3
  1775. });
  1776. var getString = new Method({
  1777. name: 'getString',
  1778. call: 'db_getString',
  1779. params: 2
  1780. });
  1781. var putHex = new Method({
  1782. name: 'putHex',
  1783. call: 'db_putHex',
  1784. params: 3
  1785. });
  1786. var getHex = new Method({
  1787. name: 'getHex',
  1788. call: 'db_getHex',
  1789. params: 2
  1790. });
  1791. var methods = [
  1792. putString, getString, putHex, getHex
  1793. ];
  1794. module.exports = {
  1795. methods: methods
  1796. };
  1797. },{"./method":23}],14:[function(require,module,exports){
  1798. /*
  1799. This file is part of ethereum.js.
  1800. ethereum.js is free software: you can redistribute it and/or modify
  1801. it under the terms of the GNU Lesser General Public License as published by
  1802. the Free Software Foundation, either version 3 of the License, or
  1803. (at your option) any later version.
  1804. ethereum.js is distributed in the hope that it will be useful,
  1805. but WITHOUT ANY WARRANTY; without even the implied warranty of
  1806. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  1807. GNU Lesser General Public License for more details.
  1808. You should have received a copy of the GNU Lesser General Public License
  1809. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  1810. */
  1811. /**
  1812. * @file errors.js
  1813. * @author Marek Kotewicz <marek@ethdev.com>
  1814. * @date 2015
  1815. */
  1816. module.exports = {
  1817. InvalidNumberOfParams: function () {
  1818. return new Error('Invalid number of input parameters');
  1819. },
  1820. InvalidConnection: function (host){
  1821. return new Error('CONNECTION ERROR: Couldn\'t connect to node '+ host +', is it running?');
  1822. },
  1823. InvalidProvider: function () {
  1824. return new Error('Providor not set or invalid');
  1825. },
  1826. InvalidResponse: function (result){
  1827. var message = !!result && !!result.error && !!result.error.message ? result.error.message : 'Invalid JSON RPC response';
  1828. return new Error(message);
  1829. }
  1830. };
  1831. },{}],15:[function(require,module,exports){
  1832. /*
  1833. This file is part of ethereum.js.
  1834. ethereum.js is free software: you can redistribute it and/or modify
  1835. it under the terms of the GNU Lesser General Public License as published by
  1836. the Free Software Foundation, either version 3 of the License, or
  1837. (at your option) any later version.
  1838. ethereum.js is distributed in the hope that it will be useful,
  1839. but WITHOUT ANY WARRANTY; without even the implied warranty of
  1840. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  1841. GNU Lesser General Public License for more details.
  1842. You should have received a copy of the GNU Lesser General Public License
  1843. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  1844. */
  1845. /**
  1846. * @file eth.js
  1847. * @author Marek Kotewicz <marek@ethdev.com>
  1848. * @author Fabian Vogelsteller <fabian@ethdev.com>
  1849. * @date 2015
  1850. */
  1851. /**
  1852. * Web3
  1853. *
  1854. * @module web3
  1855. */
  1856. /**
  1857. * Eth methods and properties
  1858. *
  1859. * An example method object can look as follows:
  1860. *
  1861. * {
  1862. * name: 'getBlock',
  1863. * call: blockCall,
  1864. * params: 2,
  1865. * outputFormatter: formatters.outputBlockFormatter,
  1866. * inputFormatter: [ // can be a formatter funciton or an array of functions. Where each item in the array will be used for one parameter
  1867. * utils.toHex, // formats paramter 1
  1868. * function(param){ return !!param; } // formats paramter 2
  1869. * ]
  1870. * },
  1871. *
  1872. * @class [web3] eth
  1873. * @constructor
  1874. */
  1875. "use strict";
  1876. var formatters = require('./formatters');
  1877. var utils = require('../utils/utils');
  1878. var Method = require('./method');
  1879. var Property = require('./property');
  1880. var blockCall = function (args) {
  1881. return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? "eth_getBlockByHash" : "eth_getBlockByNumber";
  1882. };
  1883. var transactionFromBlockCall = function (args) {
  1884. return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getTransactionByBlockHashAndIndex' : 'eth_getTransactionByBlockNumberAndIndex';
  1885. };
  1886. var uncleCall = function (args) {
  1887. return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getUncleByBlockHashAndIndex' : 'eth_getUncleByBlockNumberAndIndex';
  1888. };
  1889. var getBlockTransactionCountCall = function (args) {
  1890. return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getBlockTransactionCountByHash' : 'eth_getBlockTransactionCountByNumber';
  1891. };
  1892. var uncleCountCall = function (args) {
  1893. return (utils.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getUncleCountByBlockHash' : 'eth_getUncleCountByBlockNumber';
  1894. };
  1895. /// @returns an array of objects describing web3.eth api methods
  1896. var getBalance = new Method({
  1897. name: 'getBalance',
  1898. call: 'eth_getBalance',
  1899. params: 2,
  1900. inputFormatter: [utils.toAddress, formatters.inputDefaultBlockNumberFormatter],
  1901. outputFormatter: formatters.outputBigNumberFormatter
  1902. });
  1903. var getStorageAt = new Method({
  1904. name: 'getStorageAt',
  1905. call: 'eth_getStorageAt',
  1906. params: 3,
  1907. inputFormatter: [null, utils.toHex, formatters.inputDefaultBlockNumberFormatter]
  1908. });
  1909. var getCode = new Method({
  1910. name: 'getCode',
  1911. call: 'eth_getCode',
  1912. params: 2,
  1913. inputFormatter: [utils.toAddress, formatters.inputDefaultBlockNumberFormatter]
  1914. });
  1915. var getBlock = new Method({
  1916. name: 'getBlock',
  1917. call: blockCall,
  1918. params: 2,
  1919. inputFormatter: [formatters.inputBlockNumberFormatter, function (val) { return !!val; }],
  1920. outputFormatter: formatters.outputBlockFormatter
  1921. });
  1922. var getUncle = new Method({
  1923. name: 'getUncle',
  1924. call: uncleCall,
  1925. params: 2,
  1926. inputFormatter: [formatters.inputBlockNumberFormatter, utils.toHex],
  1927. outputFormatter: formatters.outputBlockFormatter,
  1928. });
  1929. var getCompilers = new Method({
  1930. name: 'getCompilers',
  1931. call: 'eth_getCompilers',
  1932. params: 0
  1933. });
  1934. var getBlockTransactionCount = new Method({
  1935. name: 'getBlockTransactionCount',
  1936. call: getBlockTransactionCountCall,
  1937. params: 1,
  1938. inputFormatter: [formatters.inputBlockNumberFormatter],
  1939. outputFormatter: utils.toDecimal
  1940. });
  1941. var getBlockUncleCount = new Method({
  1942. name: 'getBlockUncleCount',
  1943. call: uncleCountCall,
  1944. params: 1,
  1945. inputFormatter: [formatters.inputBlockNumberFormatter],
  1946. outputFormatter: utils.toDecimal
  1947. });
  1948. var getTransaction = new Method({
  1949. name: 'getTransaction',
  1950. call: 'eth_getTransactionByHash',
  1951. params: 1,
  1952. outputFormatter: formatters.outputTransactionFormatter
  1953. });
  1954. var getTransactionFromBlock = new Method({
  1955. name: 'getTransactionFromBlock',
  1956. call: transactionFromBlockCall,
  1957. params: 2,
  1958. inputFormatter: [formatters.inputBlockNumberFormatter, utils.toHex],
  1959. outputFormatter: formatters.outputTransactionFormatter
  1960. });
  1961. var getTransactionReceipt = new Method({
  1962. name: 'getTransactionReceipt',
  1963. call: 'eth_getTransactionReceipt',
  1964. params: 1,
  1965. outputFormatter: formatters.outputTransactionReceiptFormatter
  1966. });
  1967. var getTransactionCount = new Method({
  1968. name: 'getTransactionCount',
  1969. call: 'eth_getTransactionCount',
  1970. params: 2,
  1971. inputFormatter: [null, formatters.inputDefaultBlockNumberFormatter],
  1972. outputFormatter: utils.toDecimal
  1973. });
  1974. var sendRawTransaction = new Method({
  1975. name: 'sendRawTransaction',
  1976. call: 'eth_sendRawTransaction',
  1977. params: 1,
  1978. inputFormatter: []
  1979. });
  1980. var sendTransaction = new Method({
  1981. name: 'sendTransaction',
  1982. call: 'eth_sendTransaction',
  1983. params: 1,
  1984. inputFormatter: [formatters.inputTransactionFormatter]
  1985. });
  1986. var call = new Method({
  1987. name: 'call',
  1988. call: 'eth_call',
  1989. params: 2,
  1990. inputFormatter: [formatters.inputTransactionFormatter, formatters.inputDefaultBlockNumberFormatter]
  1991. });
  1992. var estimateGas = new Method({
  1993. name: 'estimateGas',
  1994. call: 'eth_estimateGas',
  1995. params: 1,
  1996. inputFormatter: [formatters.inputTransactionFormatter],
  1997. outputFormatter: utils.toDecimal
  1998. });
  1999. var compileSolidity = new Method({
  2000. name: 'compile.solidity',
  2001. call: 'eth_compileSolidity',
  2002. params: 1
  2003. });
  2004. var compileLLL = new Method({
  2005. name: 'compile.lll',
  2006. call: 'eth_compileLLL',
  2007. params: 1
  2008. });
  2009. var compileSerpent = new Method({
  2010. name: 'compile.serpent',
  2011. call: 'eth_compileSerpent',
  2012. params: 1
  2013. });
  2014. var submitWork = new Method({
  2015. name: 'submitWork',
  2016. call: 'eth_submitWork',
  2017. params: 3
  2018. });
  2019. var getWork = new Method({
  2020. name: 'getWork',
  2021. call: 'eth_getWork',
  2022. params: 0
  2023. });
  2024. var methods = [
  2025. getBalance,
  2026. getStorageAt,
  2027. getCode,
  2028. getBlock,
  2029. getUncle,
  2030. getCompilers,
  2031. getBlockTransactionCount,
  2032. getBlockUncleCount,
  2033. getTransaction,
  2034. getTransactionFromBlock,
  2035. getTransactionReceipt,
  2036. getTransactionCount,
  2037. call,
  2038. estimateGas,
  2039. sendRawTransaction,
  2040. sendTransaction,
  2041. compileSolidity,
  2042. compileLLL,
  2043. compileSerpent,
  2044. submitWork,
  2045. getWork
  2046. ];
  2047. /// @returns an array of objects describing web3.eth api properties
  2048. var properties = [
  2049. new Property({
  2050. name: 'coinbase',
  2051. getter: 'eth_coinbase'
  2052. }),
  2053. new Property({
  2054. name: 'mining',
  2055. getter: 'eth_mining'
  2056. }),
  2057. new Property({
  2058. name: 'hashrate',
  2059. getter: 'eth_hashrate',
  2060. outputFormatter: utils.toDecimal
  2061. }),
  2062. new Property({
  2063. name: 'gasPrice',
  2064. getter: 'eth_gasPrice',
  2065. outputFormatter: formatters.outputBigNumberFormatter
  2066. }),
  2067. new Property({
  2068. name: 'accounts',
  2069. getter: 'eth_accounts'
  2070. }),
  2071. new Property({
  2072. name: 'blockNumber',
  2073. getter: 'eth_blockNumber',
  2074. outputFormatter: utils.toDecimal
  2075. })
  2076. ];
  2077. module.exports = {
  2078. methods: methods,
  2079. properties: properties
  2080. };
  2081. },{"../utils/utils":7,"./formatters":18,"./method":23,"./property":26}],16:[function(require,module,exports){
  2082. /*
  2083. This file is part of ethereum.js.
  2084. ethereum.js is free software: you can redistribute it and/or modify
  2085. it under the terms of the GNU Lesser General Public License as published by
  2086. the Free Software Foundation, either version 3 of the License, or
  2087. (at your option) any later version.
  2088. ethereum.js is distributed in the hope that it will be useful,
  2089. but WITHOUT ANY WARRANTY; without even the implied warranty of
  2090. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  2091. GNU Lesser General Public License for more details.
  2092. You should have received a copy of the GNU Lesser General Public License
  2093. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  2094. */
  2095. /**
  2096. * @file event.js
  2097. * @author Marek Kotewicz <marek@ethdev.com>
  2098. * @date 2014
  2099. */
  2100. var utils = require('../utils/utils');
  2101. var coder = require('../solidity/coder');
  2102. var formatters = require('./formatters');
  2103. var sha3 = require('../utils/sha3');
  2104. var Filter = require('./filter');
  2105. var watches = require('./watches');
  2106. /**
  2107. * This prototype should be used to create event filters
  2108. */
  2109. var SolidityEvent = function (json, address) {
  2110. this._params = json.inputs;
  2111. this._name = utils.transformToFullName(json);
  2112. this._address = address;
  2113. this._anonymous = json.anonymous;
  2114. };
  2115. /**
  2116. * Should be used to get filtered param types
  2117. *
  2118. * @method types
  2119. * @param {Bool} decide if returned typed should be indexed
  2120. * @return {Array} array of types
  2121. */
  2122. SolidityEvent.prototype.types = function (indexed) {
  2123. return this._params.filter(function (i) {
  2124. return i.indexed === indexed;
  2125. }).map(function (i) {
  2126. return i.type;
  2127. });
  2128. };
  2129. /**
  2130. * Should be used to get event display name
  2131. *
  2132. * @method displayName
  2133. * @return {String} event display name
  2134. */
  2135. SolidityEvent.prototype.displayName = function () {
  2136. return utils.extractDisplayName(this._name);
  2137. };
  2138. /**
  2139. * Should be used to get event type name
  2140. *
  2141. * @method typeName
  2142. * @return {String} event type name
  2143. */
  2144. SolidityEvent.prototype.typeName = function () {
  2145. return utils.extractTypeName(this._name);
  2146. };
  2147. /**
  2148. * Should be used to get event signature
  2149. *
  2150. * @method signature
  2151. * @return {String} event signature
  2152. */
  2153. SolidityEvent.prototype.signature = function () {
  2154. return sha3(this._name);
  2155. };
  2156. /**
  2157. * Should be used to encode indexed params and options to one final object
  2158. *
  2159. * @method encode
  2160. * @param {Object} indexed
  2161. * @param {Object} options
  2162. * @return {Object} everything combined together and encoded
  2163. */
  2164. SolidityEvent.prototype.encode = function (indexed, options) {
  2165. indexed = indexed || {};
  2166. options = options || {};
  2167. var result = {};
  2168. ['fromBlock', 'toBlock'].filter(function (f) {
  2169. return options[f] !== undefined;
  2170. }).forEach(function (f) {
  2171. result[f] = formatters.inputBlockNumberFormatter(options[f]);
  2172. });
  2173. result.topics = [];
  2174. if (!this._anonymous) {
  2175. result.address = this._address;
  2176. result.topics.push('0x' + this.signature());
  2177. }
  2178. var indexedTopics = this._params.filter(function (i) {
  2179. return i.indexed === true;
  2180. }).map(function (i) {
  2181. var value = indexed[i.name];
  2182. if (value === undefined || value === null) {
  2183. return null;
  2184. }
  2185. if (utils.isArray(value)) {
  2186. return value.map(function (v) {
  2187. return '0x' + coder.encodeParam(i.type, v);
  2188. });
  2189. }
  2190. return '0x' + coder.encodeParam(i.type, value);
  2191. });
  2192. result.topics = result.topics.concat(indexedTopics);
  2193. return result;
  2194. };
  2195. /**
  2196. * Should be used to decode indexed params and options
  2197. *
  2198. * @method decode
  2199. * @param {Object} data
  2200. * @return {Object} result object with decoded indexed && not indexed params
  2201. */
  2202. SolidityEvent.prototype.decode = function (data) {
  2203. data.data = data.data || '';
  2204. data.topics = data.topics || [];
  2205. var argTopics = this._anonymous ? data.topics : data.topics.slice(1);
  2206. var indexedData = argTopics.map(function (topics) { return topics.slice(2); }).join("");
  2207. var indexedParams = coder.decodeParams(this.types(true), indexedData);
  2208. var notIndexedData = data.data.slice(2);
  2209. var notIndexedParams = coder.decodeParams(this.types(false), notIndexedData);
  2210. var result = formatters.outputLogFormatter(data);
  2211. result.event = this.displayName();
  2212. result.address = data.address;
  2213. result.args = this._params.reduce(function (acc, current) {
  2214. acc[current.name] = current.indexed ? indexedParams.shift() : notIndexedParams.shift();
  2215. return acc;
  2216. }, {});
  2217. delete result.data;
  2218. delete result.topics;
  2219. return result;
  2220. };
  2221. /**
  2222. * Should be used to create new filter object from event
  2223. *
  2224. * @method execute
  2225. * @param {Object} indexed
  2226. * @param {Object} options
  2227. * @return {Object} filter object
  2228. */
  2229. SolidityEvent.prototype.execute = function (indexed, options, callback) {
  2230. if (utils.isFunction(arguments[arguments.length - 1])) {
  2231. callback = arguments[arguments.length - 1];
  2232. if(arguments.length === 2)
  2233. options = null;
  2234. if(arguments.length === 1) {
  2235. options = null;
  2236. indexed = {};
  2237. }
  2238. }
  2239. var o = this.encode(indexed, options);
  2240. var formatter = this.decode.bind(this);
  2241. return new Filter(o, watches.eth(), formatter, callback);
  2242. };
  2243. /**
  2244. * Should be used to attach event to contract object
  2245. *
  2246. * @method attachToContract
  2247. * @param {Contract}
  2248. */
  2249. SolidityEvent.prototype.attachToContract = function (contract) {
  2250. var execute = this.execute.bind(this);
  2251. var displayName = this.displayName();
  2252. if (!contract[displayName]) {
  2253. contract[displayName] = execute;
  2254. }
  2255. contract[displayName][this.typeName()] = this.execute.bind(this, contract);
  2256. };
  2257. module.exports = SolidityEvent;
  2258. },{"../solidity/coder":1,"../utils/sha3":6,"../utils/utils":7,"./filter":17,"./formatters":18,"./watches":31}],17:[function(require,module,exports){
  2259. /*
  2260. This file is part of ethereum.js.
  2261. ethereum.js is free software: you can redistribute it and/or modify
  2262. it under the terms of the GNU Lesser General Public License as published by
  2263. the Free Software Foundation, either version 3 of the License, or
  2264. (at your option) any later version.
  2265. ethereum.js is distributed in the hope that it will be useful,
  2266. but WITHOUT ANY WARRANTY; without even the implied warranty of
  2267. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  2268. GNU Lesser General Public License for more details.
  2269. You should have received a copy of the GNU Lesser General Public License
  2270. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  2271. */
  2272. /** @file filter.js
  2273. * @authors:
  2274. * Jeffrey Wilcke <jeff@ethdev.com>
  2275. * Marek Kotewicz <marek@ethdev.com>
  2276. * Marian Oancea <marian@ethdev.com>
  2277. * Fabian Vogelsteller <fabian@ethdev.com>
  2278. * Gav Wood <g@ethdev.com>
  2279. * @date 2014
  2280. */
  2281. var RequestManager = require('./requestmanager');
  2282. var formatters = require('./formatters');
  2283. var utils = require('../utils/utils');
  2284. /**
  2285. * Converts a given topic to a hex string, but also allows null values.
  2286. *
  2287. * @param {Mixed} value
  2288. * @return {String}
  2289. */
  2290. var toTopic = function(value){
  2291. if(value === null || typeof value === 'undefined')
  2292. return null;
  2293. value = String(value);
  2294. if(value.indexOf('0x') === 0)
  2295. return value;
  2296. else
  2297. return utils.fromAscii(value);
  2298. };
  2299. /// This method should be called on options object, to verify deprecated properties && lazy load dynamic ones
  2300. /// @param should be string or object
  2301. /// @returns options string or object
  2302. var getOptions = function (options) {
  2303. if (utils.isString(options)) {
  2304. return options;
  2305. }
  2306. options = options || {};
  2307. // make sure topics, get converted to hex
  2308. options.topics = options.topics || [];
  2309. options.topics = options.topics.map(function(topic){
  2310. return (utils.isArray(topic)) ? topic.map(toTopic) : toTopic(topic);
  2311. });
  2312. // lazy load
  2313. return {
  2314. topics: options.topics,
  2315. to: options.to,
  2316. address: options.address,
  2317. fromBlock: formatters.inputBlockNumberFormatter(options.fromBlock),
  2318. toBlock: formatters.inputBlockNumberFormatter(options.toBlock)
  2319. };
  2320. };
  2321. /**
  2322. Adds the callback and sets up the methods, to iterate over the results.
  2323. @method getLogsAtStart
  2324. @param {Object} self
  2325. @param {funciton}
  2326. */
  2327. var getLogsAtStart = function(self, callback){
  2328. // call getFilterLogs for the first watch callback start
  2329. if (!utils.isString(self.options)) {
  2330. self.get(function (err, messages) {
  2331. // don't send all the responses to all the watches again... just to self one
  2332. if (err) {
  2333. callback(err);
  2334. }
  2335. messages.forEach(function (message) {
  2336. callback(null, message);
  2337. });
  2338. });
  2339. }
  2340. };
  2341. /**
  2342. Adds the callback and sets up the methods, to iterate over the results.
  2343. @method pollFilter
  2344. @param {Object} self
  2345. */
  2346. var pollFilter = function(self) {
  2347. var onMessage = function (error, messages) {
  2348. if (error) {
  2349. return self.callbacks.forEach(function (callback) {
  2350. callback(error);
  2351. });
  2352. }
  2353. messages.forEach(function (message) {
  2354. message = self.formatter ? self.formatter(message) : message;
  2355. self.callbacks.forEach(function (callback) {
  2356. callback(null, message);
  2357. });
  2358. });
  2359. };
  2360. RequestManager.getInstance().startPolling({
  2361. method: self.implementation.poll.call,
  2362. params: [self.filterId],
  2363. }, self.filterId, onMessage, self.stopWatching.bind(self));
  2364. };
  2365. var Filter = function (options, methods, formatter, callback) {
  2366. var self = this;
  2367. var implementation = {};
  2368. methods.forEach(function (method) {
  2369. method.attachToObject(implementation);
  2370. });
  2371. this.options = getOptions(options);
  2372. this.implementation = implementation;
  2373. this.filterId = null;
  2374. this.callbacks = [];
  2375. this.pollFilters = [];
  2376. this.formatter = formatter;
  2377. this.implementation.newFilter(this.options, function(error, id){
  2378. if(error) {
  2379. self.callbacks.forEach(function(cb){
  2380. cb(error);
  2381. });
  2382. } else {
  2383. self.filterId = id;
  2384. // get filter logs for the already existing watch calls
  2385. self.callbacks.forEach(function(cb){
  2386. getLogsAtStart(self, cb);
  2387. });
  2388. if(self.callbacks.length > 0)
  2389. pollFilter(self);
  2390. // start to watch immediately
  2391. if(callback) {
  2392. return self.watch(callback);
  2393. }
  2394. }
  2395. });
  2396. };
  2397. Filter.prototype.watch = function (callback) {
  2398. this.callbacks.push(callback);
  2399. if(this.filterId) {
  2400. getLogsAtStart(this, callback);
  2401. pollFilter(this);
  2402. }
  2403. return this;
  2404. };
  2405. Filter.prototype.stopWatching = function () {
  2406. RequestManager.getInstance().stopPolling(this.filterId);
  2407. // remove filter async
  2408. this.implementation.uninstallFilter(this.filterId, function(){});
  2409. this.callbacks = [];
  2410. };
  2411. Filter.prototype.get = function (callback) {
  2412. var self = this;
  2413. if (utils.isFunction(callback)) {
  2414. this.implementation.getLogs(this.filterId, function(err, res){
  2415. if (err) {
  2416. callback(err);
  2417. } else {
  2418. callback(null, res.map(function (log) {
  2419. return self.formatter ? self.formatter(log) : log;
  2420. }));
  2421. }
  2422. });
  2423. } else {
  2424. var logs = this.implementation.getLogs(this.filterId);
  2425. return logs.map(function (log) {
  2426. return self.formatter ? self.formatter(log) : log;
  2427. });
  2428. }
  2429. return this;
  2430. };
  2431. module.exports = Filter;
  2432. },{"../utils/utils":7,"./formatters":18,"./requestmanager":28}],18:[function(require,module,exports){
  2433. /*
  2434. This file is part of ethereum.js.
  2435. ethereum.js is free software: you can redistribute it and/or modify
  2436. it under the terms of the GNU Lesser General Public License as published by
  2437. the Free Software Foundation, either version 3 of the License, or
  2438. (at your option) any later version.
  2439. ethereum.js is distributed in the hope that it will be useful,
  2440. but WITHOUT ANY WARRANTY; without even the implied warranty of
  2441. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  2442. GNU Lesser General Public License for more details.
  2443. You should have received a copy of the GNU Lesser General Public License
  2444. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  2445. */
  2446. /**
  2447. * @file formatters.js
  2448. * @author Marek Kotewicz <marek@ethdev.com>
  2449. * @author Fabian Vogelsteller <fabian@ethdev.com>
  2450. * @date 2015
  2451. */
  2452. var utils = require('../utils/utils');
  2453. var config = require('../utils/config');
  2454. /**
  2455. * Should the format output to a big number
  2456. *
  2457. * @method outputBigNumberFormatter
  2458. * @param {String|Number|BigNumber}
  2459. * @returns {BigNumber} object
  2460. */
  2461. var outputBigNumberFormatter = function (number) {
  2462. return utils.toBigNumber(number);
  2463. };
  2464. var isPredefinedBlockNumber = function (blockNumber) {
  2465. return blockNumber === 'latest' || blockNumber === 'pending' || blockNumber === 'earliest';
  2466. };
  2467. var inputDefaultBlockNumberFormatter = function (blockNumber) {
  2468. if (blockNumber === undefined) {
  2469. return config.defaultBlock;
  2470. }
  2471. return inputBlockNumberFormatter(blockNumber);
  2472. };
  2473. var inputBlockNumberFormatter = function (blockNumber) {
  2474. if (blockNumber === undefined) {
  2475. return undefined;
  2476. } else if (isPredefinedBlockNumber(blockNumber)) {
  2477. return blockNumber;
  2478. }
  2479. return utils.toHex(blockNumber);
  2480. };
  2481. /**
  2482. * Formats the input of a transaction and converts all values to HEX
  2483. *
  2484. * @method inputTransactionFormatter
  2485. * @param {Object} transaction options
  2486. * @returns object
  2487. */
  2488. var inputTransactionFormatter = function (options){
  2489. options.from = options.from || config.defaultAccount;
  2490. // make code -> data
  2491. if (options.code) {
  2492. options.data = options.code;
  2493. delete options.code;
  2494. }
  2495. ['gasPrice', 'gas', 'value', 'nonce'].filter(function (key) {
  2496. return options[key] !== undefined;
  2497. }).forEach(function(key){
  2498. options[key] = utils.fromDecimal(options[key]);
  2499. });
  2500. return options;
  2501. };
  2502. /**
  2503. * Formats the output of a transaction to its proper values
  2504. *
  2505. * @method outputTransactionFormatter
  2506. * @param {Object} tx
  2507. * @returns {Object}
  2508. */
  2509. var outputTransactionFormatter = function (tx){
  2510. if(tx.blockNumber !== null)
  2511. tx.blockNumber = utils.toDecimal(tx.blockNumber);
  2512. if(tx.transactionIndex !== null)
  2513. tx.transactionIndex = utils.toDecimal(tx.transactionIndex);
  2514. tx.nonce = utils.toDecimal(tx.nonce);
  2515. tx.gas = utils.toDecimal(tx.gas);
  2516. tx.gasPrice = utils.toBigNumber(tx.gasPrice);
  2517. tx.value = utils.toBigNumber(tx.value);
  2518. return tx;
  2519. };
  2520. /**
  2521. * Formats the output of a transaction receipt to its proper values
  2522. *
  2523. * @method outputTransactionReceiptFormatter
  2524. * @param {Object} receipt
  2525. * @returns {Object}
  2526. */
  2527. var outputTransactionReceiptFormatter = function (receipt){
  2528. if(receipt.blockNumber !== null)
  2529. receipt.blockNumber = utils.toDecimal(receipt.blockNumber);
  2530. if(receipt.transactionIndex !== null)
  2531. receipt.transactionIndex = utils.toDecimal(receipt.transactionIndex);
  2532. receipt.cumulativeGasUsed = utils.toDecimal(receipt.cumulativeGasUsed);
  2533. receipt.gasUsed = utils.toDecimal(receipt.gasUsed);
  2534. if(utils.isArray(receipt.logs)) {
  2535. receipt.logs = receipt.logs.map(function(log){
  2536. return outputLogFormatter(log);
  2537. });
  2538. }
  2539. return receipt;
  2540. };
  2541. /**
  2542. * Formats the output of a block to its proper values
  2543. *
  2544. * @method outputBlockFormatter
  2545. * @param {Object} block
  2546. * @returns {Object}
  2547. */
  2548. var outputBlockFormatter = function(block) {
  2549. // transform to number
  2550. block.gasLimit = utils.toDecimal(block.gasLimit);
  2551. block.gasUsed = utils.toDecimal(block.gasUsed);
  2552. block.size = utils.toDecimal(block.size);
  2553. block.timestamp = utils.toDecimal(block.timestamp);
  2554. if(block.number !== null)
  2555. block.number = utils.toDecimal(block.number);
  2556. block.difficulty = utils.toBigNumber(block.difficulty);
  2557. block.totalDifficulty = utils.toBigNumber(block.totalDifficulty);
  2558. if (utils.isArray(block.transactions)) {
  2559. block.transactions.forEach(function(item){
  2560. if(!utils.isString(item))
  2561. return outputTransactionFormatter(item);
  2562. });
  2563. }
  2564. return block;
  2565. };
  2566. /**
  2567. * Formats the output of a log
  2568. *
  2569. * @method outputLogFormatter
  2570. * @param {Object} log object
  2571. * @returns {Object} log
  2572. */
  2573. var outputLogFormatter = function(log) {
  2574. if(log.blockNumber !== null)
  2575. log.blockNumber = utils.toDecimal(log.blockNumber);
  2576. if(log.transactionIndex !== null)
  2577. log.transactionIndex = utils.toDecimal(log.transactionIndex);
  2578. if(log.logIndex !== null)
  2579. log.logIndex = utils.toDecimal(log.logIndex);
  2580. return log;
  2581. };
  2582. /**
  2583. * Formats the input of a whisper post and converts all values to HEX
  2584. *
  2585. * @method inputPostFormatter
  2586. * @param {Object} transaction object
  2587. * @returns {Object}
  2588. */
  2589. var inputPostFormatter = function(post) {
  2590. post.payload = utils.toHex(post.payload);
  2591. post.ttl = utils.fromDecimal(post.ttl);
  2592. post.workToProve = utils.fromDecimal(post.workToProve);
  2593. post.priority = utils.fromDecimal(post.priority);
  2594. // fallback
  2595. if (!utils.isArray(post.topics)) {
  2596. post.topics = post.topics ? [post.topics] : [];
  2597. }
  2598. // format the following options
  2599. post.topics = post.topics.map(function(topic){
  2600. return utils.fromAscii(topic);
  2601. });
  2602. return post;
  2603. };
  2604. /**
  2605. * Formats the output of a received post message
  2606. *
  2607. * @method outputPostFormatter
  2608. * @param {Object}
  2609. * @returns {Object}
  2610. */
  2611. var outputPostFormatter = function(post){
  2612. post.expiry = utils.toDecimal(post.expiry);
  2613. post.sent = utils.toDecimal(post.sent);
  2614. post.ttl = utils.toDecimal(post.ttl);
  2615. post.workProved = utils.toDecimal(post.workProved);
  2616. post.payloadRaw = post.payload;
  2617. post.payload = utils.toAscii(post.payload);
  2618. if (utils.isJson(post.payload)) {
  2619. post.payload = JSON.parse(post.payload);
  2620. }
  2621. // format the following options
  2622. if (!post.topics) {
  2623. post.topics = [];
  2624. }
  2625. post.topics = post.topics.map(function(topic){
  2626. return utils.toAscii(topic);
  2627. });
  2628. return post;
  2629. };
  2630. module.exports = {
  2631. inputDefaultBlockNumberFormatter: inputDefaultBlockNumberFormatter,
  2632. inputBlockNumberFormatter: inputBlockNumberFormatter,
  2633. inputTransactionFormatter: inputTransactionFormatter,
  2634. inputPostFormatter: inputPostFormatter,
  2635. outputBigNumberFormatter: outputBigNumberFormatter,
  2636. outputTransactionFormatter: outputTransactionFormatter,
  2637. outputTransactionReceiptFormatter: outputTransactionReceiptFormatter,
  2638. outputBlockFormatter: outputBlockFormatter,
  2639. outputLogFormatter: outputLogFormatter,
  2640. outputPostFormatter: outputPostFormatter
  2641. };
  2642. },{"../utils/config":5,"../utils/utils":7}],19:[function(require,module,exports){
  2643. /*
  2644. This file is part of ethereum.js.
  2645. ethereum.js is free software: you can redistribute it and/or modify
  2646. it under the terms of the GNU Lesser General Public License as published by
  2647. the Free Software Foundation, either version 3 of the License, or
  2648. (at your option) any later version.
  2649. ethereum.js is distributed in the hope that it will be useful,
  2650. but WITHOUT ANY WARRANTY; without even the implied warranty of
  2651. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  2652. GNU Lesser General Public License for more details.
  2653. You should have received a copy of the GNU Lesser General Public License
  2654. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  2655. */
  2656. /**
  2657. * @file function.js
  2658. * @author Marek Kotewicz <marek@ethdev.com>
  2659. * @date 2015
  2660. */
  2661. var web3 = require('../web3');
  2662. var coder = require('../solidity/coder');
  2663. var utils = require('../utils/utils');
  2664. var formatters = require('./formatters');
  2665. var sha3 = require('../utils/sha3');
  2666. /**
  2667. * This prototype should be used to call/sendTransaction to solidity functions
  2668. */
  2669. var SolidityFunction = function (json, address) {
  2670. this._inputTypes = json.inputs.map(function (i) {
  2671. return i.type;
  2672. });
  2673. this._outputTypes = json.outputs.map(function (i) {
  2674. return i.type;
  2675. });
  2676. this._constant = json.constant;
  2677. this._name = utils.transformToFullName(json);
  2678. this._address = address;
  2679. };
  2680. SolidityFunction.prototype.extractCallback = function (args) {
  2681. if (utils.isFunction(args[args.length - 1])) {
  2682. return args.pop(); // modify the args array!
  2683. }
  2684. };
  2685. SolidityFunction.prototype.extractDefaultBlock = function (args) {
  2686. if (args.length > this._inputTypes.length && !utils.isObject(args[args.length -1])) {
  2687. return formatters.inputDefaultBlockNumberFormatter(args.pop()); // modify the args array!
  2688. }
  2689. };
  2690. /**
  2691. * Should be used to create payload from arguments
  2692. *
  2693. * @method toPayload
  2694. * @param {Array} solidity function params
  2695. * @param {Object} optional payload options
  2696. */
  2697. SolidityFunction.prototype.toPayload = function (args) {
  2698. var options = {};
  2699. if (args.length > this._inputTypes.length && utils.isObject(args[args.length -1])) {
  2700. options = args[args.length - 1];
  2701. }
  2702. options.to = this._address;
  2703. options.data = '0x' + this.signature() + coder.encodeParams(this._inputTypes, args);
  2704. return options;
  2705. };
  2706. /**
  2707. * Should be used to get function signature
  2708. *
  2709. * @method signature
  2710. * @return {String} function signature
  2711. */
  2712. SolidityFunction.prototype.signature = function () {
  2713. return sha3(this._name).slice(0, 8);
  2714. };
  2715. SolidityFunction.prototype.unpackOutput = function (output) {
  2716. if (!output) {
  2717. return;
  2718. }
  2719. output = output.length >= 2 ? output.slice(2) : output;
  2720. var result = coder.decodeParams(this._outputTypes, output);
  2721. return result.length === 1 ? result[0] : result;
  2722. };
  2723. /**
  2724. * Calls a contract function.
  2725. *
  2726. * @method call
  2727. * @param {...Object} Contract function arguments
  2728. * @param {function} If the last argument is a function, the contract function
  2729. * call will be asynchronous, and the callback will be passed the
  2730. * error and result.
  2731. * @return {String} output bytes
  2732. */
  2733. SolidityFunction.prototype.call = function () {
  2734. var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; });
  2735. var callback = this.extractCallback(args);
  2736. var defaultBlock = this.extractDefaultBlock(args);
  2737. var payload = this.toPayload(args);
  2738. if (!callback) {
  2739. var output = web3.eth.call(payload, defaultBlock);
  2740. return this.unpackOutput(output);
  2741. }
  2742. var self = this;
  2743. web3.eth.call(payload, defaultBlock, function (error, output) {
  2744. callback(error, self.unpackOutput(output));
  2745. });
  2746. };
  2747. /**
  2748. * Should be used to sendTransaction to solidity function
  2749. *
  2750. * @method sendTransaction
  2751. * @param {Object} options
  2752. */
  2753. SolidityFunction.prototype.sendTransaction = function () {
  2754. var args = Array.prototype.slice.call(arguments).filter(function (a) {return a !== undefined; });
  2755. var callback = this.extractCallback(args);
  2756. var payload = this.toPayload(args);
  2757. if (!callback) {
  2758. return web3.eth.sendTransaction(payload);
  2759. }
  2760. web3.eth.sendTransaction(payload, callback);
  2761. };
  2762. /**
  2763. * Should be used to estimateGas of solidity function
  2764. *
  2765. * @method estimateGas
  2766. * @param {Object} options
  2767. */
  2768. SolidityFunction.prototype.estimateGas = function () {
  2769. var args = Array.prototype.slice.call(arguments);
  2770. var callback = this.extractCallback(args);
  2771. var payload = this.toPayload(args);
  2772. if (!callback) {
  2773. return web3.eth.estimateGas(payload);
  2774. }
  2775. web3.eth.estimateGas(payload, callback);
  2776. };
  2777. /**
  2778. * Should be used to get function display name
  2779. *
  2780. * @method displayName
  2781. * @return {String} display name of the function
  2782. */
  2783. SolidityFunction.prototype.displayName = function () {
  2784. return utils.extractDisplayName(this._name);
  2785. };
  2786. /**
  2787. * Should be used to get function type name
  2788. *
  2789. * @method typeName
  2790. * @return {String} type name of the function
  2791. */
  2792. SolidityFunction.prototype.typeName = function () {
  2793. return utils.extractTypeName(this._name);
  2794. };
  2795. /**
  2796. * Should be called to get rpc requests from solidity function
  2797. *
  2798. * @method request
  2799. * @returns {Object}
  2800. */
  2801. SolidityFunction.prototype.request = function () {
  2802. var args = Array.prototype.slice.call(arguments);
  2803. var callback = this.extractCallback(args);
  2804. var payload = this.toPayload(args);
  2805. var format = this.unpackOutput.bind(this);
  2806. return {
  2807. method: this._constant ? 'eth_call' : 'eth_sendTransaction',
  2808. callback: callback,
  2809. params: [payload],
  2810. format: format
  2811. };
  2812. };
  2813. /**
  2814. * Should be called to execute function
  2815. *
  2816. * @method execute
  2817. */
  2818. SolidityFunction.prototype.execute = function () {
  2819. var transaction = !this._constant;
  2820. // send transaction
  2821. if (transaction) {
  2822. return this.sendTransaction.apply(this, Array.prototype.slice.call(arguments));
  2823. }
  2824. // call
  2825. return this.call.apply(this, Array.prototype.slice.call(arguments));
  2826. };
  2827. /**
  2828. * Should be called to attach function to contract
  2829. *
  2830. * @method attachToContract
  2831. * @param {Contract}
  2832. */
  2833. SolidityFunction.prototype.attachToContract = function (contract) {
  2834. var execute = this.execute.bind(this);
  2835. execute.request = this.request.bind(this);
  2836. execute.call = this.call.bind(this);
  2837. execute.sendTransaction = this.sendTransaction.bind(this);
  2838. execute.estimateGas = this.estimateGas.bind(this);
  2839. var displayName = this.displayName();
  2840. if (!contract[displayName]) {
  2841. contract[displayName] = execute;
  2842. }
  2843. contract[displayName][this.typeName()] = execute; // circular!!!!
  2844. };
  2845. module.exports = SolidityFunction;
  2846. },{"../solidity/coder":1,"../utils/sha3":6,"../utils/utils":7,"../web3":9,"./formatters":18}],20:[function(require,module,exports){
  2847. /*
  2848. This file is part of ethereum.js.
  2849. ethereum.js is free software: you can redistribute it and/or modify
  2850. it under the terms of the GNU Lesser General Public License as published by
  2851. the Free Software Foundation, either version 3 of the License, or
  2852. (at your option) any later version.
  2853. ethereum.js is distributed in the hope that it will be useful,
  2854. but WITHOUT ANY WARRANTY; without even the implied warranty of
  2855. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  2856. GNU Lesser General Public License for more details.
  2857. You should have received a copy of the GNU Lesser General Public License
  2858. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  2859. */
  2860. /** @file httpprovider.js
  2861. * @authors:
  2862. * Marek Kotewicz <marek@ethdev.com>
  2863. * Marian Oancea <marian@ethdev.com>
  2864. * Fabian Vogelsteller <fabian@ethdev.com>
  2865. * @date 2014
  2866. */
  2867. "use strict";
  2868. // resolves the problem for electron/atom shell environments, which use node integration, but have no process variable available
  2869. var XMLHttpRequest = (typeof window !== 'undefined' && window.XMLHttpRequest) ? window.XMLHttpRequest : require('xmlhttprequest').XMLHttpRequest; // jshint ignore:line
  2870. var errors = require('./errors');
  2871. var HttpProvider = function (host) {
  2872. this.host = host || 'http://localhost:8545';
  2873. };
  2874. HttpProvider.prototype.send = function (payload) {
  2875. var request = new XMLHttpRequest();
  2876. request.open('POST', this.host, false);
  2877. request.setRequestHeader('Content-type','application/json');
  2878. try {
  2879. request.send(JSON.stringify(payload));
  2880. } catch(error) {
  2881. throw errors.InvalidConnection(this.host);
  2882. }
  2883. // check request.status
  2884. // TODO: throw an error here! it cannot silently fail!!!
  2885. //if (request.status !== 200) {
  2886. //return;
  2887. //}
  2888. var result = request.responseText;
  2889. try {
  2890. result = JSON.parse(result);
  2891. } catch(e) {
  2892. throw errors.InvalidResponse(result);
  2893. }
  2894. return result;
  2895. };
  2896. HttpProvider.prototype.sendAsync = function (payload, callback) {
  2897. var request = new XMLHttpRequest();
  2898. request.onreadystatechange = function() {
  2899. if (request.readyState === 4) {
  2900. var result = request.responseText;
  2901. var error = null;
  2902. try {
  2903. result = JSON.parse(result);
  2904. } catch(e) {
  2905. error = errors.InvalidResponse(result);
  2906. }
  2907. callback(error, result);
  2908. }
  2909. };
  2910. request.open('POST', this.host, true);
  2911. request.setRequestHeader('Content-type','application/json');
  2912. try {
  2913. request.send(JSON.stringify(payload));
  2914. } catch(error) {
  2915. callback(errors.InvalidConnection(this.host));
  2916. }
  2917. };
  2918. module.exports = HttpProvider;
  2919. },{"./errors":14,"xmlhttprequest":4}],21:[function(require,module,exports){
  2920. /*
  2921. This file is part of ethereum.js.
  2922. ethereum.js is free software: you can redistribute it and/or modify
  2923. it under the terms of the GNU Lesser General Public License as published by
  2924. the Free Software Foundation, either version 3 of the License, or
  2925. (at your option) any later version.
  2926. ethereum.js is distributed in the hope that it will be useful,
  2927. but WITHOUT ANY WARRANTY; without even the implied warranty of
  2928. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  2929. GNU Lesser General Public License for more details.
  2930. You should have received a copy of the GNU Lesser General Public License
  2931. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  2932. */
  2933. /**
  2934. * @file icap.js
  2935. * @author Marek Kotewicz <marek@ethdev.com>
  2936. * @date 2015
  2937. */
  2938. var utils = require('../utils/utils');
  2939. /**
  2940. * This prototype should be used to extract necessary information from iban address
  2941. *
  2942. * @param {String} iban
  2943. */
  2944. var ICAP = function (iban) {
  2945. this._iban = iban;
  2946. };
  2947. /**
  2948. * Should be called to check if icap is correct
  2949. *
  2950. * @method isValid
  2951. * @returns {Boolean} true if it is, otherwise false
  2952. */
  2953. ICAP.prototype.isValid = function () {
  2954. return utils.isIBAN(this._iban);
  2955. };
  2956. /**
  2957. * Should be called to check if iban number is direct
  2958. *
  2959. * @method isDirect
  2960. * @returns {Boolean} true if it is, otherwise false
  2961. */
  2962. ICAP.prototype.isDirect = function () {
  2963. return this._iban.length === 34;
  2964. };
  2965. /**
  2966. * Should be called to check if iban number if indirect
  2967. *
  2968. * @method isIndirect
  2969. * @returns {Boolean} true if it is, otherwise false
  2970. */
  2971. ICAP.prototype.isIndirect = function () {
  2972. return this._iban.length === 20;
  2973. };
  2974. /**
  2975. * Should be called to get iban checksum
  2976. * Uses the mod-97-10 checksumming protocol (ISO/IEC 7064:2003)
  2977. *
  2978. * @method checksum
  2979. * @returns {String} checksum
  2980. */
  2981. ICAP.prototype.checksum = function () {
  2982. return this._iban.substr(2, 2);
  2983. };
  2984. /**
  2985. * Should be called to get institution identifier
  2986. * eg. XREG
  2987. *
  2988. * @method institution
  2989. * @returns {String} institution identifier
  2990. */
  2991. ICAP.prototype.institution = function () {
  2992. return this.isIndirect() ? this._iban.substr(7, 4) : '';
  2993. };
  2994. /**
  2995. * Should be called to get client identifier within institution
  2996. * eg. GAVOFYORK
  2997. *
  2998. * @method client
  2999. * @returns {String} client identifier
  3000. */
  3001. ICAP.prototype.client = function () {
  3002. return this.isIndirect() ? this._iban.substr(11) : '';
  3003. };
  3004. /**
  3005. * Should be called to get client direct address
  3006. *
  3007. * @method address
  3008. * @returns {String} client direct address
  3009. */
  3010. ICAP.prototype.address = function () {
  3011. return this.isDirect() ? this._iban.substr(4) : '';
  3012. };
  3013. module.exports = ICAP;
  3014. },{"../utils/utils":7}],22:[function(require,module,exports){
  3015. /*
  3016. This file is part of ethereum.js.
  3017. ethereum.js is free software: you can redistribute it and/or modify
  3018. it under the terms of the GNU Lesser General Public License as published by
  3019. the Free Software Foundation, either version 3 of the License, or
  3020. (at your option) any later version.
  3021. ethereum.js is distributed in the hope that it will be useful,
  3022. but WITHOUT ANY WARRANTY; without even the implied warranty of
  3023. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  3024. GNU Lesser General Public License for more details.
  3025. You should have received a copy of the GNU Lesser General Public License
  3026. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  3027. */
  3028. /** @file jsonrpc.js
  3029. * @authors:
  3030. * Marek Kotewicz <marek@ethdev.com>
  3031. * @date 2015
  3032. */
  3033. var Jsonrpc = function () {
  3034. // singleton pattern
  3035. if (arguments.callee._singletonInstance) {
  3036. return arguments.callee._singletonInstance;
  3037. }
  3038. arguments.callee._singletonInstance = this;
  3039. this.messageId = 1;
  3040. };
  3041. /**
  3042. * @return {Jsonrpc} singleton
  3043. */
  3044. Jsonrpc.getInstance = function () {
  3045. var instance = new Jsonrpc();
  3046. return instance;
  3047. };
  3048. /**
  3049. * Should be called to valid json create payload object
  3050. *
  3051. * @method toPayload
  3052. * @param {Function} method of jsonrpc call, required
  3053. * @param {Array} params, an array of method params, optional
  3054. * @returns {Object} valid jsonrpc payload object
  3055. */
  3056. Jsonrpc.prototype.toPayload = function (method, params) {
  3057. if (!method)
  3058. console.error('jsonrpc method should be specified!');
  3059. return {
  3060. jsonrpc: '2.0',
  3061. method: method,
  3062. params: params || [],
  3063. id: this.messageId++
  3064. };
  3065. };
  3066. /**
  3067. * Should be called to check if jsonrpc response is valid
  3068. *
  3069. * @method isValidResponse
  3070. * @param {Object}
  3071. * @returns {Boolean} true if response is valid, otherwise false
  3072. */
  3073. Jsonrpc.prototype.isValidResponse = function (response) {
  3074. return !!response &&
  3075. !response.error &&
  3076. response.jsonrpc === '2.0' &&
  3077. typeof response.id === 'number' &&
  3078. response.result !== undefined; // only undefined is not valid json object
  3079. };
  3080. /**
  3081. * Should be called to create batch payload object
  3082. *
  3083. * @method toBatchPayload
  3084. * @param {Array} messages, an array of objects with method (required) and params (optional) fields
  3085. * @returns {Array} batch payload
  3086. */
  3087. Jsonrpc.prototype.toBatchPayload = function (messages) {
  3088. var self = this;
  3089. return messages.map(function (message) {
  3090. return self.toPayload(message.method, message.params);
  3091. });
  3092. };
  3093. module.exports = Jsonrpc;
  3094. },{}],23:[function(require,module,exports){
  3095. /*
  3096. This file is part of ethereum.js.
  3097. ethereum.js is free software: you can redistribute it and/or modify
  3098. it under the terms of the GNU Lesser General Public License as published by
  3099. the Free Software Foundation, either version 3 of the License, or
  3100. (at your option) any later version.
  3101. ethereum.js is distributed in the hope that it will be useful,
  3102. but WITHOUT ANY WARRANTY; without even the implied warranty of
  3103. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  3104. GNU Lesser General Public License for more details.
  3105. You should have received a copy of the GNU Lesser General Public License
  3106. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  3107. */
  3108. /**
  3109. * @file method.js
  3110. * @author Marek Kotewicz <marek@ethdev.com>
  3111. * @date 2015
  3112. */
  3113. var RequestManager = require('./requestmanager');
  3114. var utils = require('../utils/utils');
  3115. var errors = require('./errors');
  3116. var Method = function (options) {
  3117. this.name = options.name;
  3118. this.call = options.call;
  3119. this.params = options.params || 0;
  3120. this.inputFormatter = options.inputFormatter;
  3121. this.outputFormatter = options.outputFormatter;
  3122. };
  3123. /**
  3124. * Should be used to determine name of the jsonrpc method based on arguments
  3125. *
  3126. * @method getCall
  3127. * @param {Array} arguments
  3128. * @return {String} name of jsonrpc method
  3129. */
  3130. Method.prototype.getCall = function (args) {
  3131. return utils.isFunction(this.call) ? this.call(args) : this.call;
  3132. };
  3133. /**
  3134. * Should be used to extract callback from array of arguments. Modifies input param
  3135. *
  3136. * @method extractCallback
  3137. * @param {Array} arguments
  3138. * @return {Function|Null} callback, if exists
  3139. */
  3140. Method.prototype.extractCallback = function (args) {
  3141. if (utils.isFunction(args[args.length - 1])) {
  3142. return args.pop(); // modify the args array!
  3143. }
  3144. };
  3145. /**
  3146. * Should be called to check if the number of arguments is correct
  3147. *
  3148. * @method validateArgs
  3149. * @param {Array} arguments
  3150. * @throws {Error} if it is not
  3151. */
  3152. Method.prototype.validateArgs = function (args) {
  3153. if (args.length !== this.params) {
  3154. throw errors.InvalidNumberOfParams();
  3155. }
  3156. };
  3157. /**
  3158. * Should be called to format input args of method
  3159. *
  3160. * @method formatInput
  3161. * @param {Array}
  3162. * @return {Array}
  3163. */
  3164. Method.prototype.formatInput = function (args) {
  3165. if (!this.inputFormatter) {
  3166. return args;
  3167. }
  3168. return this.inputFormatter.map(function (formatter, index) {
  3169. return formatter ? formatter(args[index]) : args[index];
  3170. });
  3171. };
  3172. /**
  3173. * Should be called to format output(result) of method
  3174. *
  3175. * @method formatOutput
  3176. * @param {Object}
  3177. * @return {Object}
  3178. */
  3179. Method.prototype.formatOutput = function (result) {
  3180. return this.outputFormatter && result !== null ? this.outputFormatter(result) : result;
  3181. };
  3182. /**
  3183. * Should attach function to method
  3184. *
  3185. * @method attachToObject
  3186. * @param {Object}
  3187. * @param {Function}
  3188. */
  3189. Method.prototype.attachToObject = function (obj) {
  3190. var func = this.send.bind(this);
  3191. func.request = this.request.bind(this);
  3192. func.call = this.call; // that's ugly. filter.js uses it
  3193. var name = this.name.split('.');
  3194. if (name.length > 1) {
  3195. obj[name[0]] = obj[name[0]] || {};
  3196. obj[name[0]][name[1]] = func;
  3197. } else {
  3198. obj[name[0]] = func;
  3199. }
  3200. };
  3201. /**
  3202. * Should create payload from given input args
  3203. *
  3204. * @method toPayload
  3205. * @param {Array} args
  3206. * @return {Object}
  3207. */
  3208. Method.prototype.toPayload = function (args) {
  3209. var call = this.getCall(args);
  3210. var callback = this.extractCallback(args);
  3211. var params = this.formatInput(args);
  3212. this.validateArgs(params);
  3213. return {
  3214. method: call,
  3215. params: params,
  3216. callback: callback
  3217. };
  3218. };
  3219. /**
  3220. * Should be called to create pure JSONRPC request which can be used in batch request
  3221. *
  3222. * @method request
  3223. * @param {...} params
  3224. * @return {Object} jsonrpc request
  3225. */
  3226. Method.prototype.request = function () {
  3227. var payload = this.toPayload(Array.prototype.slice.call(arguments));
  3228. payload.format = this.formatOutput.bind(this);
  3229. return payload;
  3230. };
  3231. /**
  3232. * Should send request to the API
  3233. *
  3234. * @method send
  3235. * @param list of params
  3236. * @return result
  3237. */
  3238. Method.prototype.send = function () {
  3239. var payload = this.toPayload(Array.prototype.slice.call(arguments));
  3240. if (payload.callback) {
  3241. var self = this;
  3242. return RequestManager.getInstance().sendAsync(payload, function (err, result) {
  3243. payload.callback(err, self.formatOutput(result));
  3244. });
  3245. }
  3246. return this.formatOutput(RequestManager.getInstance().send(payload));
  3247. };
  3248. module.exports = Method;
  3249. },{"../utils/utils":7,"./errors":14,"./requestmanager":28}],24:[function(require,module,exports){
  3250. /*
  3251. This file is part of ethereum.js.
  3252. ethereum.js is free software: you can redistribute it and/or modify
  3253. it under the terms of the GNU Lesser General Public License as published by
  3254. the Free Software Foundation, either version 3 of the License, or
  3255. (at your option) any later version.
  3256. ethereum.js is distributed in the hope that it will be useful,
  3257. but WITHOUT ANY WARRANTY; without even the implied warranty of
  3258. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  3259. GNU Lesser General Public License for more details.
  3260. You should have received a copy of the GNU Lesser General Public License
  3261. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  3262. */
  3263. /**
  3264. * @file namereg.js
  3265. * @author Marek Kotewicz <marek@ethdev.com>
  3266. * @date 2015
  3267. */
  3268. var contract = require('./contract');
  3269. var address = '0xc6d9d2cd449a754c494264e1809c50e34d64562b';
  3270. var abi = [
  3271. {"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"name","outputs":[{"name":"o_name","type":"bytes32"}],"type":"function"},
  3272. {"constant":true,"inputs":[{"name":"_name","type":"bytes32"}],"name":"owner","outputs":[{"name":"","type":"address"}],"type":"function"},
  3273. {"constant":true,"inputs":[{"name":"_name","type":"bytes32"}],"name":"content","outputs":[{"name":"","type":"bytes32"}],"type":"function"},
  3274. {"constant":true,"inputs":[{"name":"_name","type":"bytes32"}],"name":"addr","outputs":[{"name":"","type":"address"}],"type":"function"},
  3275. {"constant":false,"inputs":[{"name":"_name","type":"bytes32"}],"name":"reserve","outputs":[],"type":"function"},
  3276. {"constant":true,"inputs":[{"name":"_name","type":"bytes32"}],"name":"subRegistrar","outputs":[{"name":"o_subRegistrar","type":"address"}],"type":"function"},
  3277. {"constant":false,"inputs":[{"name":"_name","type":"bytes32"},{"name":"_newOwner","type":"address"}],"name":"transfer","outputs":[],"type":"function"},
  3278. {"constant":false,"inputs":[{"name":"_name","type":"bytes32"},{"name":"_registrar","type":"address"}],"name":"setSubRegistrar","outputs":[],"type":"function"},
  3279. {"constant":false,"inputs":[],"name":"Registrar","outputs":[],"type":"function"},
  3280. {"constant":false,"inputs":[{"name":"_name","type":"bytes32"},{"name":"_a","type":"address"},{"name":"_primary","type":"bool"}],"name":"setAddress","outputs":[],"type":"function"},
  3281. {"constant":false,"inputs":[{"name":"_name","type":"bytes32"},{"name":"_content","type":"bytes32"}],"name":"setContent","outputs":[],"type":"function"},
  3282. {"constant":false,"inputs":[{"name":"_name","type":"bytes32"}],"name":"disown","outputs":[],"type":"function"},
  3283. {"constant":true,"inputs":[{"name":"_name","type":"bytes32"}],"name":"register","outputs":[{"name":"","type":"address"}],"type":"function"},
  3284. {"anonymous":false,"inputs":[{"indexed":true,"name":"name","type":"bytes32"}],"name":"Changed","type":"event"},
  3285. {"anonymous":false,"inputs":[{"indexed":true,"name":"name","type":"bytes32"},{"indexed":true,"name":"addr","type":"address"}],"name":"PrimaryChanged","type":"event"}
  3286. ];
  3287. module.exports = contract(abi).at(address);
  3288. },{"./contract":12}],25:[function(require,module,exports){
  3289. /*
  3290. This file is part of ethereum.js.
  3291. ethereum.js is free software: you can redistribute it and/or modify
  3292. it under the terms of the GNU Lesser General Public License as published by
  3293. the Free Software Foundation, either version 3 of the License, or
  3294. (at your option) any later version.
  3295. ethereum.js is distributed in the hope that it will be useful,
  3296. but WITHOUT ANY WARRANTY; without even the implied warranty of
  3297. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  3298. GNU Lesser General Public License for more details.
  3299. You should have received a copy of the GNU Lesser General Public License
  3300. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  3301. */
  3302. /** @file eth.js
  3303. * @authors:
  3304. * Marek Kotewicz <marek@ethdev.com>
  3305. * @date 2015
  3306. */
  3307. var utils = require('../utils/utils');
  3308. var Property = require('./property');
  3309. /// @returns an array of objects describing web3.eth api methods
  3310. var methods = [
  3311. ];
  3312. /// @returns an array of objects describing web3.eth api properties
  3313. var properties = [
  3314. new Property({
  3315. name: 'listening',
  3316. getter: 'net_listening'
  3317. }),
  3318. new Property({
  3319. name: 'peerCount',
  3320. getter: 'net_peerCount',
  3321. outputFormatter: utils.toDecimal
  3322. })
  3323. ];
  3324. module.exports = {
  3325. methods: methods,
  3326. properties: properties
  3327. };
  3328. },{"../utils/utils":7,"./property":26}],26:[function(require,module,exports){
  3329. /*
  3330. This file is part of ethereum.js.
  3331. ethereum.js is free software: you can redistribute it and/or modify
  3332. it under the terms of the GNU Lesser General Public License as published by
  3333. the Free Software Foundation, either version 3 of the License, or
  3334. (at your option) any later version.
  3335. ethereum.js is distributed in the hope that it will be useful,
  3336. but WITHOUT ANY WARRANTY; without even the implied warranty of
  3337. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  3338. GNU Lesser General Public License for more details.
  3339. You should have received a copy of the GNU Lesser General Public License
  3340. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  3341. */
  3342. /**
  3343. * @file property.js
  3344. * @author Fabian Vogelsteller <fabian@frozeman.de>
  3345. * @author Marek Kotewicz <marek@ethdev.com>
  3346. * @date 2015
  3347. */
  3348. var RequestManager = require('./requestmanager');
  3349. var Property = function (options) {
  3350. this.name = options.name;
  3351. this.getter = options.getter;
  3352. this.setter = options.setter;
  3353. this.outputFormatter = options.outputFormatter;
  3354. this.inputFormatter = options.inputFormatter;
  3355. };
  3356. /**
  3357. * Should be called to format input args of method
  3358. *
  3359. * @method formatInput
  3360. * @param {Array}
  3361. * @return {Array}
  3362. */
  3363. Property.prototype.formatInput = function (arg) {
  3364. return this.inputFormatter ? this.inputFormatter(arg) : arg;
  3365. };
  3366. /**
  3367. * Should be called to format output(result) of method
  3368. *
  3369. * @method formatOutput
  3370. * @param {Object}
  3371. * @return {Object}
  3372. */
  3373. Property.prototype.formatOutput = function (result) {
  3374. return this.outputFormatter && result !== null ? this.outputFormatter(result) : result;
  3375. };
  3376. /**
  3377. * Should attach function to method
  3378. *
  3379. * @method attachToObject
  3380. * @param {Object}
  3381. * @param {Function}
  3382. */
  3383. Property.prototype.attachToObject = function (obj) {
  3384. var proto = {
  3385. get: this.get.bind(this),
  3386. };
  3387. var names = this.name.split('.');
  3388. var name = names[0];
  3389. if (names.length > 1) {
  3390. obj[names[0]] = obj[names[0]] || {};
  3391. obj = obj[names[0]];
  3392. name = names[1];
  3393. }
  3394. Object.defineProperty(obj, name, proto);
  3395. var toAsyncName = function (prefix, name) {
  3396. return prefix + name.charAt(0).toUpperCase() + name.slice(1);
  3397. };
  3398. obj[toAsyncName('get', name)] = this.getAsync.bind(this);
  3399. };
  3400. /**
  3401. * Should be used to get value of the property
  3402. *
  3403. * @method get
  3404. * @return {Object} value of the property
  3405. */
  3406. Property.prototype.get = function () {
  3407. return this.formatOutput(RequestManager.getInstance().send({
  3408. method: this.getter
  3409. }));
  3410. };
  3411. /**
  3412. * Should be used to asynchrounously get value of property
  3413. *
  3414. * @method getAsync
  3415. * @param {Function}
  3416. */
  3417. Property.prototype.getAsync = function (callback) {
  3418. var self = this;
  3419. RequestManager.getInstance().sendAsync({
  3420. method: this.getter
  3421. }, function (err, result) {
  3422. if (err) {
  3423. return callback(err);
  3424. }
  3425. callback(err, self.formatOutput(result));
  3426. });
  3427. };
  3428. module.exports = Property;
  3429. },{"./requestmanager":28}],27:[function(require,module,exports){
  3430. /*
  3431. This file is part of ethereum.js.
  3432. ethereum.js is free software: you can redistribute it and/or modify
  3433. it under the terms of the GNU Lesser General Public License as published by
  3434. the Free Software Foundation, either version 3 of the License, or
  3435. (at your option) any later version.
  3436. ethereum.js is distributed in the hope that it will be useful,
  3437. but WITHOUT ANY WARRANTY; without even the implied warranty of
  3438. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  3439. GNU Lesser General Public License for more details.
  3440. You should have received a copy of the GNU Lesser General Public License
  3441. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  3442. */
  3443. /** @file qtsync.js
  3444. * @authors:
  3445. * Marek Kotewicz <marek@ethdev.com>
  3446. * Marian Oancea <marian@ethdev.com>
  3447. * @date 2014
  3448. */
  3449. var QtSyncProvider = function () {
  3450. };
  3451. QtSyncProvider.prototype.send = function (payload) {
  3452. var result = navigator.qt.callMethod(JSON.stringify(payload));
  3453. return JSON.parse(result);
  3454. };
  3455. module.exports = QtSyncProvider;
  3456. },{}],28:[function(require,module,exports){
  3457. /*
  3458. This file is part of ethereum.js.
  3459. ethereum.js is free software: you can redistribute it and/or modify
  3460. it under the terms of the GNU Lesser General Public License as published by
  3461. the Free Software Foundation, either version 3 of the License, or
  3462. (at your option) any later version.
  3463. ethereum.js is distributed in the hope that it will be useful,
  3464. but WITHOUT ANY WARRANTY; without even the implied warranty of
  3465. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  3466. GNU Lesser General Public License for more details.
  3467. You should have received a copy of the GNU Lesser General Public License
  3468. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  3469. */
  3470. /**
  3471. * @file requestmanager.js
  3472. * @author Jeffrey Wilcke <jeff@ethdev.com>
  3473. * @author Marek Kotewicz <marek@ethdev.com>
  3474. * @author Marian Oancea <marian@ethdev.com>
  3475. * @author Fabian Vogelsteller <fabian@ethdev.com>
  3476. * @author Gav Wood <g@ethdev.com>
  3477. * @date 2014
  3478. */
  3479. var Jsonrpc = require('./jsonrpc');
  3480. var utils = require('../utils/utils');
  3481. var c = require('../utils/config');
  3482. var errors = require('./errors');
  3483. /**
  3484. * It's responsible for passing messages to providers
  3485. * It's also responsible for polling the ethereum node for incoming messages
  3486. * Default poll timeout is 1 second
  3487. * Singleton
  3488. */
  3489. var RequestManager = function (provider) {
  3490. // singleton pattern
  3491. if (arguments.callee._singletonInstance) {
  3492. return arguments.callee._singletonInstance;
  3493. }
  3494. arguments.callee._singletonInstance = this;
  3495. this.provider = provider;
  3496. this.polls = {};
  3497. this.timeout = null;
  3498. this.isPolling = false;
  3499. };
  3500. /**
  3501. * @return {RequestManager} singleton
  3502. */
  3503. RequestManager.getInstance = function () {
  3504. var instance = new RequestManager();
  3505. return instance;
  3506. };
  3507. /**
  3508. * Should be used to synchronously send request
  3509. *
  3510. * @method send
  3511. * @param {Object} data
  3512. * @return {Object}
  3513. */
  3514. RequestManager.prototype.send = function (data) {
  3515. if (!this.provider) {
  3516. console.error(errors.InvalidProvider());
  3517. return null;
  3518. }
  3519. var payload = Jsonrpc.getInstance().toPayload(data.method, data.params);
  3520. var result = this.provider.send(payload);
  3521. if (!Jsonrpc.getInstance().isValidResponse(result)) {
  3522. throw errors.InvalidResponse(result);
  3523. }
  3524. return result.result;
  3525. };
  3526. /**
  3527. * Should be used to asynchronously send request
  3528. *
  3529. * @method sendAsync
  3530. * @param {Object} data
  3531. * @param {Function} callback
  3532. */
  3533. RequestManager.prototype.sendAsync = function (data, callback) {
  3534. if (!this.provider) {
  3535. return callback(errors.InvalidProvider());
  3536. }
  3537. var payload = Jsonrpc.getInstance().toPayload(data.method, data.params);
  3538. this.provider.sendAsync(payload, function (err, result) {
  3539. if (err) {
  3540. return callback(err);
  3541. }
  3542. if (!Jsonrpc.getInstance().isValidResponse(result)) {
  3543. return callback(errors.InvalidResponse(result));
  3544. }
  3545. callback(null, result.result);
  3546. });
  3547. };
  3548. /**
  3549. * Should be called to asynchronously send batch request
  3550. *
  3551. * @method sendBatch
  3552. * @param {Array} batch data
  3553. * @param {Function} callback
  3554. */
  3555. RequestManager.prototype.sendBatch = function (data, callback) {
  3556. if (!this.provider) {
  3557. return callback(errors.InvalidProvider());
  3558. }
  3559. var payload = Jsonrpc.getInstance().toBatchPayload(data);
  3560. this.provider.sendAsync(payload, function (err, results) {
  3561. if (err) {
  3562. return callback(err);
  3563. }
  3564. if (!utils.isArray(results)) {
  3565. return callback(errors.InvalidResponse(results));
  3566. }
  3567. callback(err, results);
  3568. });
  3569. };
  3570. /**
  3571. * Should be used to set provider of request manager
  3572. *
  3573. * @method setProvider
  3574. * @param {Object}
  3575. */
  3576. RequestManager.prototype.setProvider = function (p) {
  3577. this.provider = p;
  3578. if (this.provider && !this.isPolling) {
  3579. this.poll();
  3580. this.isPolling = true;
  3581. }
  3582. };
  3583. /*jshint maxparams:4 */
  3584. /**
  3585. * Should be used to start polling
  3586. *
  3587. * @method startPolling
  3588. * @param {Object} data
  3589. * @param {Number} pollId
  3590. * @param {Function} callback
  3591. * @param {Function} uninstall
  3592. *
  3593. * @todo cleanup number of params
  3594. */
  3595. RequestManager.prototype.startPolling = function (data, pollId, callback, uninstall) {
  3596. this.polls['poll_'+ pollId] = {data: data, id: pollId, callback: callback, uninstall: uninstall};
  3597. };
  3598. /*jshint maxparams:3 */
  3599. /**
  3600. * Should be used to stop polling for filter with given id
  3601. *
  3602. * @method stopPolling
  3603. * @param {Number} pollId
  3604. */
  3605. RequestManager.prototype.stopPolling = function (pollId) {
  3606. delete this.polls['poll_'+ pollId];
  3607. };
  3608. /**
  3609. * Should be called to reset the polling mechanism of the request manager
  3610. *
  3611. * @method reset
  3612. */
  3613. RequestManager.prototype.reset = function () {
  3614. for (var key in this.polls) {
  3615. this.polls[key].uninstall();
  3616. }
  3617. this.polls = {};
  3618. if (this.timeout) {
  3619. clearTimeout(this.timeout);
  3620. this.timeout = null;
  3621. }
  3622. this.poll();
  3623. };
  3624. /**
  3625. * Should be called to poll for changes on filter with given id
  3626. *
  3627. * @method poll
  3628. */
  3629. RequestManager.prototype.poll = function () {
  3630. /*jshint maxcomplexity: 6 */
  3631. this.timeout = setTimeout(this.poll.bind(this), c.ETH_POLLING_TIMEOUT);
  3632. if (Object.keys(this.polls).length === 0) {
  3633. return;
  3634. }
  3635. if (!this.provider) {
  3636. console.error(errors.InvalidProvider());
  3637. return;
  3638. }
  3639. var pollsData = [];
  3640. var pollsKeys = [];
  3641. for (var key in this.polls) {
  3642. pollsData.push(this.polls[key].data);
  3643. pollsKeys.push(key);
  3644. }
  3645. if (pollsData.length === 0) {
  3646. return;
  3647. }
  3648. var payload = Jsonrpc.getInstance().toBatchPayload(pollsData);
  3649. var self = this;
  3650. this.provider.sendAsync(payload, function (error, results) {
  3651. // TODO: console log?
  3652. if (error) {
  3653. return;
  3654. }
  3655. if (!utils.isArray(results)) {
  3656. throw errors.InvalidResponse(results);
  3657. }
  3658. results.map(function (result, index) {
  3659. var key = pollsKeys[index];
  3660. // make sure the filter is still installed after arrival of the request
  3661. if (self.polls[key]) {
  3662. result.callback = self.polls[key].callback;
  3663. return result;
  3664. } else
  3665. return false;
  3666. }).filter(function (result) {
  3667. return !!result;
  3668. }).filter(function (result) {
  3669. var valid = Jsonrpc.getInstance().isValidResponse(result);
  3670. if (!valid) {
  3671. result.callback(errors.InvalidResponse(result));
  3672. }
  3673. return valid;
  3674. }).filter(function (result) {
  3675. return utils.isArray(result.result) && result.result.length > 0;
  3676. }).forEach(function (result) {
  3677. result.callback(null, result.result);
  3678. });
  3679. });
  3680. };
  3681. module.exports = RequestManager;
  3682. },{"../utils/config":5,"../utils/utils":7,"./errors":14,"./jsonrpc":22}],29:[function(require,module,exports){
  3683. /*
  3684. This file is part of ethereum.js.
  3685. ethereum.js is free software: you can redistribute it and/or modify
  3686. it under the terms of the GNU Lesser General Public License as published by
  3687. the Free Software Foundation, either version 3 of the License, or
  3688. (at your option) any later version.
  3689. ethereum.js is distributed in the hope that it will be useful,
  3690. but WITHOUT ANY WARRANTY; without even the implied warranty of
  3691. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  3692. GNU Lesser General Public License for more details.
  3693. You should have received a copy of the GNU Lesser General Public License
  3694. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  3695. */
  3696. /** @file shh.js
  3697. * @authors:
  3698. * Marek Kotewicz <marek@ethdev.com>
  3699. * @date 2015
  3700. */
  3701. var Method = require('./method');
  3702. var formatters = require('./formatters');
  3703. var post = new Method({
  3704. name: 'post',
  3705. call: 'shh_post',
  3706. params: 1,
  3707. inputFormatter: [formatters.inputPostFormatter]
  3708. });
  3709. var newIdentity = new Method({
  3710. name: 'newIdentity',
  3711. call: 'shh_newIdentity',
  3712. params: 0
  3713. });
  3714. var hasIdentity = new Method({
  3715. name: 'hasIdentity',
  3716. call: 'shh_hasIdentity',
  3717. params: 1
  3718. });
  3719. var newGroup = new Method({
  3720. name: 'newGroup',
  3721. call: 'shh_newGroup',
  3722. params: 0
  3723. });
  3724. var addToGroup = new Method({
  3725. name: 'addToGroup',
  3726. call: 'shh_addToGroup',
  3727. params: 0
  3728. });
  3729. var methods = [
  3730. post,
  3731. newIdentity,
  3732. hasIdentity,
  3733. newGroup,
  3734. addToGroup
  3735. ];
  3736. module.exports = {
  3737. methods: methods
  3738. };
  3739. },{"./formatters":18,"./method":23}],30:[function(require,module,exports){
  3740. /*
  3741. This file is part of ethereum.js.
  3742. ethereum.js is free software: you can redistribute it and/or modify
  3743. it under the terms of the GNU Lesser General Public License as published by
  3744. the Free Software Foundation, either version 3 of the License, or
  3745. (at your option) any later version.
  3746. ethereum.js is distributed in the hope that it will be useful,
  3747. but WITHOUT ANY WARRANTY; without even the implied warranty of
  3748. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  3749. GNU Lesser General Public License for more details.
  3750. You should have received a copy of the GNU Lesser General Public License
  3751. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  3752. */
  3753. /**
  3754. * @file transfer.js
  3755. * @author Marek Kotewicz <marek@ethdev.com>
  3756. * @date 2015
  3757. */
  3758. var web3 = require('../web3');
  3759. var ICAP = require('./icap');
  3760. var namereg = require('./namereg');
  3761. var contract = require('./contract');
  3762. /**
  3763. * Should be used to make ICAP transfer
  3764. *
  3765. * @method transfer
  3766. * @param {String} iban number
  3767. * @param {String} from (address)
  3768. * @param {Value} value to be tranfered
  3769. * @param {Function} callback, callback
  3770. */
  3771. var transfer = function (from, iban, value, callback) {
  3772. var icap = new ICAP(iban);
  3773. if (!icap.isValid()) {
  3774. throw new Error('invalid iban address');
  3775. }
  3776. if (icap.isDirect()) {
  3777. return transferToAddress(from, icap.address(), value, callback);
  3778. }
  3779. if (!callback) {
  3780. var address = namereg.addr(icap.institution());
  3781. return deposit(from, address, value, icap.client());
  3782. }
  3783. namereg.addr(icap.insitution(), function (err, address) {
  3784. return deposit(from, address, value, icap.client(), callback);
  3785. });
  3786. };
  3787. /**
  3788. * Should be used to transfer funds to certain address
  3789. *
  3790. * @method transferToAddress
  3791. * @param {String} address
  3792. * @param {String} from (address)
  3793. * @param {Value} value to be tranfered
  3794. * @param {Function} callback, callback
  3795. */
  3796. var transferToAddress = function (from, address, value, callback) {
  3797. return web3.eth.sendTransaction({
  3798. address: address,
  3799. from: from,
  3800. value: value
  3801. }, callback);
  3802. };
  3803. /**
  3804. * Should be used to deposit funds to generic Exchange contract (must implement deposit(bytes32) method!)
  3805. *
  3806. * @method deposit
  3807. * @param {String} address
  3808. * @param {String} from (address)
  3809. * @param {Value} value to be tranfered
  3810. * @param {String} client unique identifier
  3811. * @param {Function} callback, callback
  3812. */
  3813. var deposit = function (from, address, value, client, callback) {
  3814. var abi = [{"constant":false,"inputs":[{"name":"name","type":"bytes32"}],"name":"deposit","outputs":[],"type":"function"}];
  3815. return contract(abi).at(address).deposit(client, {
  3816. from: from,
  3817. value: value
  3818. }, callback);
  3819. };
  3820. module.exports = transfer;
  3821. },{"../web3":9,"./contract":12,"./icap":21,"./namereg":24}],31:[function(require,module,exports){
  3822. /*
  3823. This file is part of ethereum.js.
  3824. ethereum.js is free software: you can redistribute it and/or modify
  3825. it under the terms of the GNU Lesser General Public License as published by
  3826. the Free Software Foundation, either version 3 of the License, or
  3827. (at your option) any later version.
  3828. ethereum.js is distributed in the hope that it will be useful,
  3829. but WITHOUT ANY WARRANTY; without even the implied warranty of
  3830. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  3831. GNU Lesser General Public License for more details.
  3832. You should have received a copy of the GNU Lesser General Public License
  3833. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  3834. */
  3835. /** @file watches.js
  3836. * @authors:
  3837. * Marek Kotewicz <marek@ethdev.com>
  3838. * @date 2015
  3839. */
  3840. var Method = require('./method');
  3841. /// @returns an array of objects describing web3.eth.filter api methods
  3842. var eth = function () {
  3843. var newFilterCall = function (args) {
  3844. var type = args[0];
  3845. switch(type) {
  3846. case 'latest':
  3847. args.shift();
  3848. this.params = 0;
  3849. return 'eth_newBlockFilter';
  3850. case 'pending':
  3851. args.shift();
  3852. this.params = 0;
  3853. return 'eth_newPendingTransactionFilter';
  3854. default:
  3855. return 'eth_newFilter';
  3856. }
  3857. };
  3858. var newFilter = new Method({
  3859. name: 'newFilter',
  3860. call: newFilterCall,
  3861. params: 1
  3862. });
  3863. var uninstallFilter = new Method({
  3864. name: 'uninstallFilter',
  3865. call: 'eth_uninstallFilter',
  3866. params: 1
  3867. });
  3868. var getLogs = new Method({
  3869. name: 'getLogs',
  3870. call: 'eth_getFilterLogs',
  3871. params: 1
  3872. });
  3873. var poll = new Method({
  3874. name: 'poll',
  3875. call: 'eth_getFilterChanges',
  3876. params: 1
  3877. });
  3878. return [
  3879. newFilter,
  3880. uninstallFilter,
  3881. getLogs,
  3882. poll
  3883. ];
  3884. };
  3885. /// @returns an array of objects describing web3.shh.watch api methods
  3886. var shh = function () {
  3887. var newFilter = new Method({
  3888. name: 'newFilter',
  3889. call: 'shh_newFilter',
  3890. params: 1
  3891. });
  3892. var uninstallFilter = new Method({
  3893. name: 'uninstallFilter',
  3894. call: 'shh_uninstallFilter',
  3895. params: 1
  3896. });
  3897. var getLogs = new Method({
  3898. name: 'getLogs',
  3899. call: 'shh_getMessages',
  3900. params: 1
  3901. });
  3902. var poll = new Method({
  3903. name: 'poll',
  3904. call: 'shh_getFilterChanges',
  3905. params: 1
  3906. });
  3907. return [
  3908. newFilter,
  3909. uninstallFilter,
  3910. getLogs,
  3911. poll
  3912. ];
  3913. };
  3914. module.exports = {
  3915. eth: eth,
  3916. shh: shh
  3917. };
  3918. },{"./method":23}],32:[function(require,module,exports){
  3919. },{}],33:[function(require,module,exports){
  3920. ;(function (root, factory) {
  3921. if (typeof exports === "object") {
  3922. // CommonJS
  3923. module.exports = exports = factory();
  3924. }
  3925. else if (typeof define === "function" && define.amd) {
  3926. // AMD
  3927. define([], factory);
  3928. }
  3929. else {
  3930. // Global (browser)
  3931. root.CryptoJS = factory();
  3932. }
  3933. }(this, function () {
  3934. /**
  3935. * CryptoJS core components.
  3936. */
  3937. var CryptoJS = CryptoJS || (function (Math, undefined) {
  3938. /**
  3939. * CryptoJS namespace.
  3940. */
  3941. var C = {};
  3942. /**
  3943. * Library namespace.
  3944. */
  3945. var C_lib = C.lib = {};
  3946. /**
  3947. * Base object for prototypal inheritance.
  3948. */
  3949. var Base = C_lib.Base = (function () {
  3950. function F() {}
  3951. return {
  3952. /**
  3953. * Creates a new object that inherits from this object.
  3954. *
  3955. * @param {Object} overrides Properties to copy into the new object.
  3956. *
  3957. * @return {Object} The new object.
  3958. *
  3959. * @static
  3960. *
  3961. * @example
  3962. *
  3963. * var MyType = CryptoJS.lib.Base.extend({
  3964. * field: 'value',
  3965. *
  3966. * method: function () {
  3967. * }
  3968. * });
  3969. */
  3970. extend: function (overrides) {
  3971. // Spawn
  3972. F.prototype = this;
  3973. var subtype = new F();
  3974. // Augment
  3975. if (overrides) {
  3976. subtype.mixIn(overrides);
  3977. }
  3978. // Create default initializer
  3979. if (!subtype.hasOwnProperty('init')) {
  3980. subtype.init = function () {
  3981. subtype.$super.init.apply(this, arguments);
  3982. };
  3983. }
  3984. // Initializer's prototype is the subtype object
  3985. subtype.init.prototype = subtype;
  3986. // Reference supertype
  3987. subtype.$super = this;
  3988. return subtype;
  3989. },
  3990. /**
  3991. * Extends this object and runs the init method.
  3992. * Arguments to create() will be passed to init().
  3993. *
  3994. * @return {Object} The new object.
  3995. *
  3996. * @static
  3997. *
  3998. * @example
  3999. *
  4000. * var instance = MyType.create();
  4001. */
  4002. create: function () {
  4003. var instance = this.extend();
  4004. instance.init.apply(instance, arguments);
  4005. return instance;
  4006. },
  4007. /**
  4008. * Initializes a newly created object.
  4009. * Override this method to add some logic when your objects are created.
  4010. *
  4011. * @example
  4012. *
  4013. * var MyType = CryptoJS.lib.Base.extend({
  4014. * init: function () {
  4015. * // ...
  4016. * }
  4017. * });
  4018. */
  4019. init: function () {
  4020. },
  4021. /**
  4022. * Copies properties into this object.
  4023. *
  4024. * @param {Object} properties The properties to mix in.
  4025. *
  4026. * @example
  4027. *
  4028. * MyType.mixIn({
  4029. * field: 'value'
  4030. * });
  4031. */
  4032. mixIn: function (properties) {
  4033. for (var propertyName in properties) {
  4034. if (properties.hasOwnProperty(propertyName)) {
  4035. this[propertyName] = properties[propertyName];
  4036. }
  4037. }
  4038. // IE won't copy toString using the loop above
  4039. if (properties.hasOwnProperty('toString')) {
  4040. this.toString = properties.toString;
  4041. }
  4042. },
  4043. /**
  4044. * Creates a copy of this object.
  4045. *
  4046. * @return {Object} The clone.
  4047. *
  4048. * @example
  4049. *
  4050. * var clone = instance.clone();
  4051. */
  4052. clone: function () {
  4053. return this.init.prototype.extend(this);
  4054. }
  4055. };
  4056. }());
  4057. /**
  4058. * An array of 32-bit words.
  4059. *
  4060. * @property {Array} words The array of 32-bit words.
  4061. * @property {number} sigBytes The number of significant bytes in this word array.
  4062. */
  4063. var WordArray = C_lib.WordArray = Base.extend({
  4064. /**
  4065. * Initializes a newly created word array.
  4066. *
  4067. * @param {Array} words (Optional) An array of 32-bit words.
  4068. * @param {number} sigBytes (Optional) The number of significant bytes in the words.
  4069. *
  4070. * @example
  4071. *
  4072. * var wordArray = CryptoJS.lib.WordArray.create();
  4073. * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
  4074. * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
  4075. */
  4076. init: function (words, sigBytes) {
  4077. words = this.words = words || [];
  4078. if (sigBytes != undefined) {
  4079. this.sigBytes = sigBytes;
  4080. } else {
  4081. this.sigBytes = words.length * 4;
  4082. }
  4083. },
  4084. /**
  4085. * Converts this word array to a string.
  4086. *
  4087. * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
  4088. *
  4089. * @return {string} The stringified word array.
  4090. *
  4091. * @example
  4092. *
  4093. * var string = wordArray + '';
  4094. * var string = wordArray.toString();
  4095. * var string = wordArray.toString(CryptoJS.enc.Utf8);
  4096. */
  4097. toString: function (encoder) {
  4098. return (encoder || Hex).stringify(this);
  4099. },
  4100. /**
  4101. * Concatenates a word array to this word array.
  4102. *
  4103. * @param {WordArray} wordArray The word array to append.
  4104. *
  4105. * @return {WordArray} This word array.
  4106. *
  4107. * @example
  4108. *
  4109. * wordArray1.concat(wordArray2);
  4110. */
  4111. concat: function (wordArray) {
  4112. // Shortcuts
  4113. var thisWords = this.words;
  4114. var thatWords = wordArray.words;
  4115. var thisSigBytes = this.sigBytes;
  4116. var thatSigBytes = wordArray.sigBytes;
  4117. // Clamp excess bits
  4118. this.clamp();
  4119. // Concat
  4120. if (thisSigBytes % 4) {
  4121. // Copy one byte at a time
  4122. for (var i = 0; i < thatSigBytes; i++) {
  4123. var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
  4124. thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
  4125. }
  4126. } else {
  4127. // Copy one word at a time
  4128. for (var i = 0; i < thatSigBytes; i += 4) {
  4129. thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
  4130. }
  4131. }
  4132. this.sigBytes += thatSigBytes;
  4133. // Chainable
  4134. return this;
  4135. },
  4136. /**
  4137. * Removes insignificant bits.
  4138. *
  4139. * @example
  4140. *
  4141. * wordArray.clamp();
  4142. */
  4143. clamp: function () {
  4144. // Shortcuts
  4145. var words = this.words;
  4146. var sigBytes = this.sigBytes;
  4147. // Clamp
  4148. words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
  4149. words.length = Math.ceil(sigBytes / 4);
  4150. },
  4151. /**
  4152. * Creates a copy of this word array.
  4153. *
  4154. * @return {WordArray} The clone.
  4155. *
  4156. * @example
  4157. *
  4158. * var clone = wordArray.clone();
  4159. */
  4160. clone: function () {
  4161. var clone = Base.clone.call(this);
  4162. clone.words = this.words.slice(0);
  4163. return clone;
  4164. },
  4165. /**
  4166. * Creates a word array filled with random bytes.
  4167. *
  4168. * @param {number} nBytes The number of random bytes to generate.
  4169. *
  4170. * @return {WordArray} The random word array.
  4171. *
  4172. * @static
  4173. *
  4174. * @example
  4175. *
  4176. * var wordArray = CryptoJS.lib.WordArray.random(16);
  4177. */
  4178. random: function (nBytes) {
  4179. var words = [];
  4180. var r = (function (m_w) {
  4181. var m_w = m_w;
  4182. var m_z = 0x3ade68b1;
  4183. var mask = 0xffffffff;
  4184. return function () {
  4185. m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
  4186. m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
  4187. var result = ((m_z << 0x10) + m_w) & mask;
  4188. result /= 0x100000000;
  4189. result += 0.5;
  4190. return result * (Math.random() > .5 ? 1 : -1);
  4191. }
  4192. });
  4193. for (var i = 0, rcache; i < nBytes; i += 4) {
  4194. var _r = r((rcache || Math.random()) * 0x100000000);
  4195. rcache = _r() * 0x3ade67b7;
  4196. words.push((_r() * 0x100000000) | 0);
  4197. }
  4198. return new WordArray.init(words, nBytes);
  4199. }
  4200. });
  4201. /**
  4202. * Encoder namespace.
  4203. */
  4204. var C_enc = C.enc = {};
  4205. /**
  4206. * Hex encoding strategy.
  4207. */
  4208. var Hex = C_enc.Hex = {
  4209. /**
  4210. * Converts a word array to a hex string.
  4211. *
  4212. * @param {WordArray} wordArray The word array.
  4213. *
  4214. * @return {string} The hex string.
  4215. *
  4216. * @static
  4217. *
  4218. * @example
  4219. *
  4220. * var hexString = CryptoJS.enc.Hex.stringify(wordArray);
  4221. */
  4222. stringify: function (wordArray) {
  4223. // Shortcuts
  4224. var words = wordArray.words;
  4225. var sigBytes = wordArray.sigBytes;
  4226. // Convert
  4227. var hexChars = [];
  4228. for (var i = 0; i < sigBytes; i++) {
  4229. var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
  4230. hexChars.push((bite >>> 4).toString(16));
  4231. hexChars.push((bite & 0x0f).toString(16));
  4232. }
  4233. return hexChars.join('');
  4234. },
  4235. /**
  4236. * Converts a hex string to a word array.
  4237. *
  4238. * @param {string} hexStr The hex string.
  4239. *
  4240. * @return {WordArray} The word array.
  4241. *
  4242. * @static
  4243. *
  4244. * @example
  4245. *
  4246. * var wordArray = CryptoJS.enc.Hex.parse(hexString);
  4247. */
  4248. parse: function (hexStr) {
  4249. // Shortcut
  4250. var hexStrLength = hexStr.length;
  4251. // Convert
  4252. var words = [];
  4253. for (var i = 0; i < hexStrLength; i += 2) {
  4254. words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
  4255. }
  4256. return new WordArray.init(words, hexStrLength / 2);
  4257. }
  4258. };
  4259. /**
  4260. * Latin1 encoding strategy.
  4261. */
  4262. var Latin1 = C_enc.Latin1 = {
  4263. /**
  4264. * Converts a word array to a Latin1 string.
  4265. *
  4266. * @param {WordArray} wordArray The word array.
  4267. *
  4268. * @return {string} The Latin1 string.
  4269. *
  4270. * @static
  4271. *
  4272. * @example
  4273. *
  4274. * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
  4275. */
  4276. stringify: function (wordArray) {
  4277. // Shortcuts
  4278. var words = wordArray.words;
  4279. var sigBytes = wordArray.sigBytes;
  4280. // Convert
  4281. var latin1Chars = [];
  4282. for (var i = 0; i < sigBytes; i++) {
  4283. var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
  4284. latin1Chars.push(String.fromCharCode(bite));
  4285. }
  4286. return latin1Chars.join('');
  4287. },
  4288. /**
  4289. * Converts a Latin1 string to a word array.
  4290. *
  4291. * @param {string} latin1Str The Latin1 string.
  4292. *
  4293. * @return {WordArray} The word array.
  4294. *
  4295. * @static
  4296. *
  4297. * @example
  4298. *
  4299. * var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
  4300. */
  4301. parse: function (latin1Str) {
  4302. // Shortcut
  4303. var latin1StrLength = latin1Str.length;
  4304. // Convert
  4305. var words = [];
  4306. for (var i = 0; i < latin1StrLength; i++) {
  4307. words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
  4308. }
  4309. return new WordArray.init(words, latin1StrLength);
  4310. }
  4311. };
  4312. /**
  4313. * UTF-8 encoding strategy.
  4314. */
  4315. var Utf8 = C_enc.Utf8 = {
  4316. /**
  4317. * Converts a word array to a UTF-8 string.
  4318. *
  4319. * @param {WordArray} wordArray The word array.
  4320. *
  4321. * @return {string} The UTF-8 string.
  4322. *
  4323. * @static
  4324. *
  4325. * @example
  4326. *
  4327. * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
  4328. */
  4329. stringify: function (wordArray) {
  4330. try {
  4331. return decodeURIComponent(escape(Latin1.stringify(wordArray)));
  4332. } catch (e) {
  4333. throw new Error('Malformed UTF-8 data');
  4334. }
  4335. },
  4336. /**
  4337. * Converts a UTF-8 string to a word array.
  4338. *
  4339. * @param {string} utf8Str The UTF-8 string.
  4340. *
  4341. * @return {WordArray} The word array.
  4342. *
  4343. * @static
  4344. *
  4345. * @example
  4346. *
  4347. * var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
  4348. */
  4349. parse: function (utf8Str) {
  4350. return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
  4351. }
  4352. };
  4353. /**
  4354. * Abstract buffered block algorithm template.
  4355. *
  4356. * The property blockSize must be implemented in a concrete subtype.
  4357. *
  4358. * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
  4359. */
  4360. var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
  4361. /**
  4362. * Resets this block algorithm's data buffer to its initial state.
  4363. *
  4364. * @example
  4365. *
  4366. * bufferedBlockAlgorithm.reset();
  4367. */
  4368. reset: function () {
  4369. // Initial values
  4370. this._data = new WordArray.init();
  4371. this._nDataBytes = 0;
  4372. },
  4373. /**
  4374. * Adds new data to this block algorithm's buffer.
  4375. *
  4376. * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
  4377. *
  4378. * @example
  4379. *
  4380. * bufferedBlockAlgorithm._append('data');
  4381. * bufferedBlockAlgorithm._append(wordArray);
  4382. */
  4383. _append: function (data) {
  4384. // Convert string to WordArray, else assume WordArray already
  4385. if (typeof data == 'string') {
  4386. data = Utf8.parse(data);
  4387. }
  4388. // Append
  4389. this._data.concat(data);
  4390. this._nDataBytes += data.sigBytes;
  4391. },
  4392. /**
  4393. * Processes available data blocks.
  4394. *
  4395. * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
  4396. *
  4397. * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
  4398. *
  4399. * @return {WordArray} The processed data.
  4400. *
  4401. * @example
  4402. *
  4403. * var processedData = bufferedBlockAlgorithm._process();
  4404. * var processedData = bufferedBlockAlgorithm._process(!!'flush');
  4405. */
  4406. _process: function (doFlush) {
  4407. // Shortcuts
  4408. var data = this._data;
  4409. var dataWords = data.words;
  4410. var dataSigBytes = data.sigBytes;
  4411. var blockSize = this.blockSize;
  4412. var blockSizeBytes = blockSize * 4;
  4413. // Count blocks ready
  4414. var nBlocksReady = dataSigBytes / blockSizeBytes;
  4415. if (doFlush) {
  4416. // Round up to include partial blocks
  4417. nBlocksReady = Math.ceil(nBlocksReady);
  4418. } else {
  4419. // Round down to include only full blocks,
  4420. // less the number of blocks that must remain in the buffer
  4421. nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
  4422. }
  4423. // Count words ready
  4424. var nWordsReady = nBlocksReady * blockSize;
  4425. // Count bytes ready
  4426. var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
  4427. // Process blocks
  4428. if (nWordsReady) {
  4429. for (var offset = 0; offset < nWordsReady; offset += blockSize) {
  4430. // Perform concrete-algorithm logic
  4431. this._doProcessBlock(dataWords, offset);
  4432. }
  4433. // Remove processed words
  4434. var processedWords = dataWords.splice(0, nWordsReady);
  4435. data.sigBytes -= nBytesReady;
  4436. }
  4437. // Return processed words
  4438. return new WordArray.init(processedWords, nBytesReady);
  4439. },
  4440. /**
  4441. * Creates a copy of this object.
  4442. *
  4443. * @return {Object} The clone.
  4444. *
  4445. * @example
  4446. *
  4447. * var clone = bufferedBlockAlgorithm.clone();
  4448. */
  4449. clone: function () {
  4450. var clone = Base.clone.call(this);
  4451. clone._data = this._data.clone();
  4452. return clone;
  4453. },
  4454. _minBufferSize: 0
  4455. });
  4456. /**
  4457. * Abstract hasher template.
  4458. *
  4459. * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
  4460. */
  4461. var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
  4462. /**
  4463. * Configuration options.
  4464. */
  4465. cfg: Base.extend(),
  4466. /**
  4467. * Initializes a newly created hasher.
  4468. *
  4469. * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
  4470. *
  4471. * @example
  4472. *
  4473. * var hasher = CryptoJS.algo.SHA256.create();
  4474. */
  4475. init: function (cfg) {
  4476. // Apply config defaults
  4477. this.cfg = this.cfg.extend(cfg);
  4478. // Set initial values
  4479. this.reset();
  4480. },
  4481. /**
  4482. * Resets this hasher to its initial state.
  4483. *
  4484. * @example
  4485. *
  4486. * hasher.reset();
  4487. */
  4488. reset: function () {
  4489. // Reset data buffer
  4490. BufferedBlockAlgorithm.reset.call(this);
  4491. // Perform concrete-hasher logic
  4492. this._doReset();
  4493. },
  4494. /**
  4495. * Updates this hasher with a message.
  4496. *
  4497. * @param {WordArray|string} messageUpdate The message to append.
  4498. *
  4499. * @return {Hasher} This hasher.
  4500. *
  4501. * @example
  4502. *
  4503. * hasher.update('message');
  4504. * hasher.update(wordArray);
  4505. */
  4506. update: function (messageUpdate) {
  4507. // Append
  4508. this._append(messageUpdate);
  4509. // Update the hash
  4510. this._process();
  4511. // Chainable
  4512. return this;
  4513. },
  4514. /**
  4515. * Finalizes the hash computation.
  4516. * Note that the finalize operation is effectively a destructive, read-once operation.
  4517. *
  4518. * @param {WordArray|string} messageUpdate (Optional) A final message update.
  4519. *
  4520. * @return {WordArray} The hash.
  4521. *
  4522. * @example
  4523. *
  4524. * var hash = hasher.finalize();
  4525. * var hash = hasher.finalize('message');
  4526. * var hash = hasher.finalize(wordArray);
  4527. */
  4528. finalize: function (messageUpdate) {
  4529. // Final message update
  4530. if (messageUpdate) {
  4531. this._append(messageUpdate);
  4532. }
  4533. // Perform concrete-hasher logic
  4534. var hash = this._doFinalize();
  4535. return hash;
  4536. },
  4537. blockSize: 512/32,
  4538. /**
  4539. * Creates a shortcut function to a hasher's object interface.
  4540. *
  4541. * @param {Hasher} hasher The hasher to create a helper for.
  4542. *
  4543. * @return {Function} The shortcut function.
  4544. *
  4545. * @static
  4546. *
  4547. * @example
  4548. *
  4549. * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
  4550. */
  4551. _createHelper: function (hasher) {
  4552. return function (message, cfg) {
  4553. return new hasher.init(cfg).finalize(message);
  4554. };
  4555. },
  4556. /**
  4557. * Creates a shortcut function to the HMAC's object interface.
  4558. *
  4559. * @param {Hasher} hasher The hasher to use in this HMAC helper.
  4560. *
  4561. * @return {Function} The shortcut function.
  4562. *
  4563. * @static
  4564. *
  4565. * @example
  4566. *
  4567. * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
  4568. */
  4569. _createHmacHelper: function (hasher) {
  4570. return function (message, key) {
  4571. return new C_algo.HMAC.init(hasher, key).finalize(message);
  4572. };
  4573. }
  4574. });
  4575. /**
  4576. * Algorithm namespace.
  4577. */
  4578. var C_algo = C.algo = {};
  4579. return C;
  4580. }(Math));
  4581. return CryptoJS;
  4582. }));
  4583. },{}],34:[function(require,module,exports){
  4584. ;(function (root, factory, undef) {
  4585. if (typeof exports === "object") {
  4586. // CommonJS
  4587. module.exports = exports = factory(require("./core"), require("./x64-core"));
  4588. }
  4589. else if (typeof define === "function" && define.amd) {
  4590. // AMD
  4591. define(["./core", "./x64-core"], factory);
  4592. }
  4593. else {
  4594. // Global (browser)
  4595. factory(root.CryptoJS);
  4596. }
  4597. }(this, function (CryptoJS) {
  4598. (function (Math) {
  4599. // Shortcuts
  4600. var C = CryptoJS;
  4601. var C_lib = C.lib;
  4602. var WordArray = C_lib.WordArray;
  4603. var Hasher = C_lib.Hasher;
  4604. var C_x64 = C.x64;
  4605. var X64Word = C_x64.Word;
  4606. var C_algo = C.algo;
  4607. // Constants tables
  4608. var RHO_OFFSETS = [];
  4609. var PI_INDEXES = [];
  4610. var ROUND_CONSTANTS = [];
  4611. // Compute Constants
  4612. (function () {
  4613. // Compute rho offset constants
  4614. var x = 1, y = 0;
  4615. for (var t = 0; t < 24; t++) {
  4616. RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64;
  4617. var newX = y % 5;
  4618. var newY = (2 * x + 3 * y) % 5;
  4619. x = newX;
  4620. y = newY;
  4621. }
  4622. // Compute pi index constants
  4623. for (var x = 0; x < 5; x++) {
  4624. for (var y = 0; y < 5; y++) {
  4625. PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5;
  4626. }
  4627. }
  4628. // Compute round constants
  4629. var LFSR = 0x01;
  4630. for (var i = 0; i < 24; i++) {
  4631. var roundConstantMsw = 0;
  4632. var roundConstantLsw = 0;
  4633. for (var j = 0; j < 7; j++) {
  4634. if (LFSR & 0x01) {
  4635. var bitPosition = (1 << j) - 1;
  4636. if (bitPosition < 32) {
  4637. roundConstantLsw ^= 1 << bitPosition;
  4638. } else /* if (bitPosition >= 32) */ {
  4639. roundConstantMsw ^= 1 << (bitPosition - 32);
  4640. }
  4641. }
  4642. // Compute next LFSR
  4643. if (LFSR & 0x80) {
  4644. // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1
  4645. LFSR = (LFSR << 1) ^ 0x71;
  4646. } else {
  4647. LFSR <<= 1;
  4648. }
  4649. }
  4650. ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw);
  4651. }
  4652. }());
  4653. // Reusable objects for temporary values
  4654. var T = [];
  4655. (function () {
  4656. for (var i = 0; i < 25; i++) {
  4657. T[i] = X64Word.create();
  4658. }
  4659. }());
  4660. /**
  4661. * SHA-3 hash algorithm.
  4662. */
  4663. var SHA3 = C_algo.SHA3 = Hasher.extend({
  4664. /**
  4665. * Configuration options.
  4666. *
  4667. * @property {number} outputLength
  4668. * The desired number of bits in the output hash.
  4669. * Only values permitted are: 224, 256, 384, 512.
  4670. * Default: 512
  4671. */
  4672. cfg: Hasher.cfg.extend({
  4673. outputLength: 512
  4674. }),
  4675. _doReset: function () {
  4676. var state = this._state = []
  4677. for (var i = 0; i < 25; i++) {
  4678. state[i] = new X64Word.init();
  4679. }
  4680. this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
  4681. },
  4682. _doProcessBlock: function (M, offset) {
  4683. // Shortcuts
  4684. var state = this._state;
  4685. var nBlockSizeLanes = this.blockSize / 2;
  4686. // Absorb
  4687. for (var i = 0; i < nBlockSizeLanes; i++) {
  4688. // Shortcuts
  4689. var M2i = M[offset + 2 * i];
  4690. var M2i1 = M[offset + 2 * i + 1];
  4691. // Swap endian
  4692. M2i = (
  4693. (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) |
  4694. (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00)
  4695. );
  4696. M2i1 = (
  4697. (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) |
  4698. (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00)
  4699. );
  4700. // Absorb message into state
  4701. var lane = state[i];
  4702. lane.high ^= M2i1;
  4703. lane.low ^= M2i;
  4704. }
  4705. // Rounds
  4706. for (var round = 0; round < 24; round++) {
  4707. // Theta
  4708. for (var x = 0; x < 5; x++) {
  4709. // Mix column lanes
  4710. var tMsw = 0, tLsw = 0;
  4711. for (var y = 0; y < 5; y++) {
  4712. var lane = state[x + 5 * y];
  4713. tMsw ^= lane.high;
  4714. tLsw ^= lane.low;
  4715. }
  4716. // Temporary values
  4717. var Tx = T[x];
  4718. Tx.high = tMsw;
  4719. Tx.low = tLsw;
  4720. }
  4721. for (var x = 0; x < 5; x++) {
  4722. // Shortcuts
  4723. var Tx4 = T[(x + 4) % 5];
  4724. var Tx1 = T[(x + 1) % 5];
  4725. var Tx1Msw = Tx1.high;
  4726. var Tx1Lsw = Tx1.low;
  4727. // Mix surrounding columns
  4728. var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31));
  4729. var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31));
  4730. for (var y = 0; y < 5; y++) {
  4731. var lane = state[x + 5 * y];
  4732. lane.high ^= tMsw;
  4733. lane.low ^= tLsw;
  4734. }
  4735. }
  4736. // Rho Pi
  4737. for (var laneIndex = 1; laneIndex < 25; laneIndex++) {
  4738. // Shortcuts
  4739. var lane = state[laneIndex];
  4740. var laneMsw = lane.high;
  4741. var laneLsw = lane.low;
  4742. var rhoOffset = RHO_OFFSETS[laneIndex];
  4743. // Rotate lanes
  4744. if (rhoOffset < 32) {
  4745. var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset));
  4746. var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset));
  4747. } else /* if (rhoOffset >= 32) */ {
  4748. var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset));
  4749. var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset));
  4750. }
  4751. // Transpose lanes
  4752. var TPiLane = T[PI_INDEXES[laneIndex]];
  4753. TPiLane.high = tMsw;
  4754. TPiLane.low = tLsw;
  4755. }
  4756. // Rho pi at x = y = 0
  4757. var T0 = T[0];
  4758. var state0 = state[0];
  4759. T0.high = state0.high;
  4760. T0.low = state0.low;
  4761. // Chi
  4762. for (var x = 0; x < 5; x++) {
  4763. for (var y = 0; y < 5; y++) {
  4764. // Shortcuts
  4765. var laneIndex = x + 5 * y;
  4766. var lane = state[laneIndex];
  4767. var TLane = T[laneIndex];
  4768. var Tx1Lane = T[((x + 1) % 5) + 5 * y];
  4769. var Tx2Lane = T[((x + 2) % 5) + 5 * y];
  4770. // Mix rows
  4771. lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high);
  4772. lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low);
  4773. }
  4774. }
  4775. // Iota
  4776. var lane = state[0];
  4777. var roundConstant = ROUND_CONSTANTS[round];
  4778. lane.high ^= roundConstant.high;
  4779. lane.low ^= roundConstant.low;;
  4780. }
  4781. },
  4782. _doFinalize: function () {
  4783. // Shortcuts
  4784. var data = this._data;
  4785. var dataWords = data.words;
  4786. var nBitsTotal = this._nDataBytes * 8;
  4787. var nBitsLeft = data.sigBytes * 8;
  4788. var blockSizeBits = this.blockSize * 32;
  4789. // Add padding
  4790. dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32);
  4791. dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80;
  4792. data.sigBytes = dataWords.length * 4;
  4793. // Hash final blocks
  4794. this._process();
  4795. // Shortcuts
  4796. var state = this._state;
  4797. var outputLengthBytes = this.cfg.outputLength / 8;
  4798. var outputLengthLanes = outputLengthBytes / 8;
  4799. // Squeeze
  4800. var hashWords = [];
  4801. for (var i = 0; i < outputLengthLanes; i++) {
  4802. // Shortcuts
  4803. var lane = state[i];
  4804. var laneMsw = lane.high;
  4805. var laneLsw = lane.low;
  4806. // Swap endian
  4807. laneMsw = (
  4808. (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) |
  4809. (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00)
  4810. );
  4811. laneLsw = (
  4812. (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) |
  4813. (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00)
  4814. );
  4815. // Squeeze state to retrieve hash
  4816. hashWords.push(laneLsw);
  4817. hashWords.push(laneMsw);
  4818. }
  4819. // Return final computed hash
  4820. return new WordArray.init(hashWords, outputLengthBytes);
  4821. },
  4822. clone: function () {
  4823. var clone = Hasher.clone.call(this);
  4824. var state = clone._state = this._state.slice(0);
  4825. for (var i = 0; i < 25; i++) {
  4826. state[i] = state[i].clone();
  4827. }
  4828. return clone;
  4829. }
  4830. });
  4831. /**
  4832. * Shortcut function to the hasher's object interface.
  4833. *
  4834. * @param {WordArray|string} message The message to hash.
  4835. *
  4836. * @return {WordArray} The hash.
  4837. *
  4838. * @static
  4839. *
  4840. * @example
  4841. *
  4842. * var hash = CryptoJS.SHA3('message');
  4843. * var hash = CryptoJS.SHA3(wordArray);
  4844. */
  4845. C.SHA3 = Hasher._createHelper(SHA3);
  4846. /**
  4847. * Shortcut function to the HMAC's object interface.
  4848. *
  4849. * @param {WordArray|string} message The message to hash.
  4850. * @param {WordArray|string} key The secret key.
  4851. *
  4852. * @return {WordArray} The HMAC.
  4853. *
  4854. * @static
  4855. *
  4856. * @example
  4857. *
  4858. * var hmac = CryptoJS.HmacSHA3(message, key);
  4859. */
  4860. C.HmacSHA3 = Hasher._createHmacHelper(SHA3);
  4861. }(Math));
  4862. return CryptoJS.SHA3;
  4863. }));
  4864. },{"./core":33,"./x64-core":35}],35:[function(require,module,exports){
  4865. ;(function (root, factory) {
  4866. if (typeof exports === "object") {
  4867. // CommonJS
  4868. module.exports = exports = factory(require("./core"));
  4869. }
  4870. else if (typeof define === "function" && define.amd) {
  4871. // AMD
  4872. define(["./core"], factory);
  4873. }
  4874. else {
  4875. // Global (browser)
  4876. factory(root.CryptoJS);
  4877. }
  4878. }(this, function (CryptoJS) {
  4879. (function (undefined) {
  4880. // Shortcuts
  4881. var C = CryptoJS;
  4882. var C_lib = C.lib;
  4883. var Base = C_lib.Base;
  4884. var X32WordArray = C_lib.WordArray;
  4885. /**
  4886. * x64 namespace.
  4887. */
  4888. var C_x64 = C.x64 = {};
  4889. /**
  4890. * A 64-bit word.
  4891. */
  4892. var X64Word = C_x64.Word = Base.extend({
  4893. /**
  4894. * Initializes a newly created 64-bit word.
  4895. *
  4896. * @param {number} high The high 32 bits.
  4897. * @param {number} low The low 32 bits.
  4898. *
  4899. * @example
  4900. *
  4901. * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
  4902. */
  4903. init: function (high, low) {
  4904. this.high = high;
  4905. this.low = low;
  4906. }
  4907. /**
  4908. * Bitwise NOTs this word.
  4909. *
  4910. * @return {X64Word} A new x64-Word object after negating.
  4911. *
  4912. * @example
  4913. *
  4914. * var negated = x64Word.not();
  4915. */
  4916. // not: function () {
  4917. // var high = ~this.high;
  4918. // var low = ~this.low;
  4919. // return X64Word.create(high, low);
  4920. // },
  4921. /**
  4922. * Bitwise ANDs this word with the passed word.
  4923. *
  4924. * @param {X64Word} word The x64-Word to AND with this word.
  4925. *
  4926. * @return {X64Word} A new x64-Word object after ANDing.
  4927. *
  4928. * @example
  4929. *
  4930. * var anded = x64Word.and(anotherX64Word);
  4931. */
  4932. // and: function (word) {
  4933. // var high = this.high & word.high;
  4934. // var low = this.low & word.low;
  4935. // return X64Word.create(high, low);
  4936. // },
  4937. /**
  4938. * Bitwise ORs this word with the passed word.
  4939. *
  4940. * @param {X64Word} word The x64-Word to OR with this word.
  4941. *
  4942. * @return {X64Word} A new x64-Word object after ORing.
  4943. *
  4944. * @example
  4945. *
  4946. * var ored = x64Word.or(anotherX64Word);
  4947. */
  4948. // or: function (word) {
  4949. // var high = this.high | word.high;
  4950. // var low = this.low | word.low;
  4951. // return X64Word.create(high, low);
  4952. // },
  4953. /**
  4954. * Bitwise XORs this word with the passed word.
  4955. *
  4956. * @param {X64Word} word The x64-Word to XOR with this word.
  4957. *
  4958. * @return {X64Word} A new x64-Word object after XORing.
  4959. *
  4960. * @example
  4961. *
  4962. * var xored = x64Word.xor(anotherX64Word);
  4963. */
  4964. // xor: function (word) {
  4965. // var high = this.high ^ word.high;
  4966. // var low = this.low ^ word.low;
  4967. // return X64Word.create(high, low);
  4968. // },
  4969. /**
  4970. * Shifts this word n bits to the left.
  4971. *
  4972. * @param {number} n The number of bits to shift.
  4973. *
  4974. * @return {X64Word} A new x64-Word object after shifting.
  4975. *
  4976. * @example
  4977. *
  4978. * var shifted = x64Word.shiftL(25);
  4979. */
  4980. // shiftL: function (n) {
  4981. // if (n < 32) {
  4982. // var high = (this.high << n) | (this.low >>> (32 - n));
  4983. // var low = this.low << n;
  4984. // } else {
  4985. // var high = this.low << (n - 32);
  4986. // var low = 0;
  4987. // }
  4988. // return X64Word.create(high, low);
  4989. // },
  4990. /**
  4991. * Shifts this word n bits to the right.
  4992. *
  4993. * @param {number} n The number of bits to shift.
  4994. *
  4995. * @return {X64Word} A new x64-Word object after shifting.
  4996. *
  4997. * @example
  4998. *
  4999. * var shifted = x64Word.shiftR(7);
  5000. */
  5001. // shiftR: function (n) {
  5002. // if (n < 32) {
  5003. // var low = (this.low >>> n) | (this.high << (32 - n));
  5004. // var high = this.high >>> n;
  5005. // } else {
  5006. // var low = this.high >>> (n - 32);
  5007. // var high = 0;
  5008. // }
  5009. // return X64Word.create(high, low);
  5010. // },
  5011. /**
  5012. * Rotates this word n bits to the left.
  5013. *
  5014. * @param {number} n The number of bits to rotate.
  5015. *
  5016. * @return {X64Word} A new x64-Word object after rotating.
  5017. *
  5018. * @example
  5019. *
  5020. * var rotated = x64Word.rotL(25);
  5021. */
  5022. // rotL: function (n) {
  5023. // return this.shiftL(n).or(this.shiftR(64 - n));
  5024. // },
  5025. /**
  5026. * Rotates this word n bits to the right.
  5027. *
  5028. * @param {number} n The number of bits to rotate.
  5029. *
  5030. * @return {X64Word} A new x64-Word object after rotating.
  5031. *
  5032. * @example
  5033. *
  5034. * var rotated = x64Word.rotR(7);
  5035. */
  5036. // rotR: function (n) {
  5037. // return this.shiftR(n).or(this.shiftL(64 - n));
  5038. // },
  5039. /**
  5040. * Adds this word with the passed word.
  5041. *
  5042. * @param {X64Word} word The x64-Word to add with this word.
  5043. *
  5044. * @return {X64Word} A new x64-Word object after adding.
  5045. *
  5046. * @example
  5047. *
  5048. * var added = x64Word.add(anotherX64Word);
  5049. */
  5050. // add: function (word) {
  5051. // var low = (this.low + word.low) | 0;
  5052. // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
  5053. // var high = (this.high + word.high + carry) | 0;
  5054. // return X64Word.create(high, low);
  5055. // }
  5056. });
  5057. /**
  5058. * An array of 64-bit words.
  5059. *
  5060. * @property {Array} words The array of CryptoJS.x64.Word objects.
  5061. * @property {number} sigBytes The number of significant bytes in this word array.
  5062. */
  5063. var X64WordArray = C_x64.WordArray = Base.extend({
  5064. /**
  5065. * Initializes a newly created word array.
  5066. *
  5067. * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
  5068. * @param {number} sigBytes (Optional) The number of significant bytes in the words.
  5069. *
  5070. * @example
  5071. *
  5072. * var wordArray = CryptoJS.x64.WordArray.create();
  5073. *
  5074. * var wordArray = CryptoJS.x64.WordArray.create([
  5075. * CryptoJS.x64.Word.create(0x00010203, 0x04050607),
  5076. * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
  5077. * ]);
  5078. *
  5079. * var wordArray = CryptoJS.x64.WordArray.create([
  5080. * CryptoJS.x64.Word.create(0x00010203, 0x04050607),
  5081. * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
  5082. * ], 10);
  5083. */
  5084. init: function (words, sigBytes) {
  5085. words = this.words = words || [];
  5086. if (sigBytes != undefined) {
  5087. this.sigBytes = sigBytes;
  5088. } else {
  5089. this.sigBytes = words.length * 8;
  5090. }
  5091. },
  5092. /**
  5093. * Converts this 64-bit word array to a 32-bit word array.
  5094. *
  5095. * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
  5096. *
  5097. * @example
  5098. *
  5099. * var x32WordArray = x64WordArray.toX32();
  5100. */
  5101. toX32: function () {
  5102. // Shortcuts
  5103. var x64Words = this.words;
  5104. var x64WordsLength = x64Words.length;
  5105. // Convert
  5106. var x32Words = [];
  5107. for (var i = 0; i < x64WordsLength; i++) {
  5108. var x64Word = x64Words[i];
  5109. x32Words.push(x64Word.high);
  5110. x32Words.push(x64Word.low);
  5111. }
  5112. return X32WordArray.create(x32Words, this.sigBytes);
  5113. },
  5114. /**
  5115. * Creates a copy of this word array.
  5116. *
  5117. * @return {X64WordArray} The clone.
  5118. *
  5119. * @example
  5120. *
  5121. * var clone = x64WordArray.clone();
  5122. */
  5123. clone: function () {
  5124. var clone = Base.clone.call(this);
  5125. // Clone "words" array
  5126. var words = clone.words = this.words.slice(0);
  5127. // Clone each X64Word object
  5128. var wordsLength = words.length;
  5129. for (var i = 0; i < wordsLength; i++) {
  5130. words[i] = words[i].clone();
  5131. }
  5132. return clone;
  5133. }
  5134. });
  5135. }());
  5136. return CryptoJS;
  5137. }));
  5138. },{"./core":33}],"bignumber.js":[function(require,module,exports){
  5139. 'use strict';
  5140. module.exports = BigNumber; // jshint ignore:line
  5141. },{}],"web3":[function(require,module,exports){
  5142. var web3 = require('./lib/web3');
  5143. web3.providers.HttpProvider = require('./lib/web3/httpprovider');
  5144. web3.providers.QtSyncProvider = require('./lib/web3/qtsync');
  5145. web3.eth.contract = require('./lib/web3/contract');
  5146. web3.eth.namereg = require('./lib/web3/namereg');
  5147. web3.eth.sendIBANTransaction = require('./lib/web3/transfer');
  5148. // dont override global variable
  5149. if (typeof window !== 'undefined' && typeof window.web3 === 'undefined') {
  5150. window.web3 = web3;
  5151. }
  5152. module.exports = web3;
  5153. },{"./lib/web3":9,"./lib/web3/contract":12,"./lib/web3/httpprovider":20,"./lib/web3/namereg":24,"./lib/web3/qtsync":27,"./lib/web3/transfer":30}]},{},["web3"])
  5154. //# sourceMappingURL=web3-light.js.map
  5155. `