wative-core 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.esm.js CHANGED
@@ -1 +1 @@
1
- import*as e from"fs";import*as t from"path";import a from"web3";import*as r from"tweetnacl";import*as s from"bs58";import*as n from"bip39";import{Keypair as o,Connection as i}from"@solana/web3.js";import{Wallet as c}from"@coral-xyz/anchor";import*as u from"crypto-js";import{hdkey as l}from"ethereumjs-wallet";import{HDKey as p}from"micro-ed25519-hdkey";var d=function(){return d=Object.assign||function(e){for(var t,a=1,r=arguments.length;a<r;a++)for(var s in t=arguments[a])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},d.apply(this,arguments)};function h(e,t,a,r){return new(a||(a=Promise))((function(s,n){function o(e){try{c(r.next(e))}catch(e){n(e)}}function i(e){try{c(r.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof a?t:new a((function(e){e(t)}))).then(o,i)}c((r=r.apply(e,t||[])).next())}))}function m(e,t){var a,r,s,n,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return n={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(n[Symbol.iterator]=function(){return this}),n;function i(i){return function(c){return function(i){if(a)throw new TypeError("Generator is already executing.");for(;n&&(n=0,i[0]&&(o=0)),o;)try{if(a=1,r&&(s=2&i[0]?r.return:i[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,i[1])).done)return s;switch(r=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(s=o.trys,(s=s.length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],r=0}finally{a=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,c])}}}"function"==typeof SuppressedError&&SuppressedError;var g=function(e,t){return h(void 0,void 0,void 0,(function(){var a,r,s;return m(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,e.apply(void 0,t)];case 1:return r=n.sent(),a={status:!0,output:r},[3,3];case 2:return s=n.sent(),a={status:!1,output:s.toString()},[3,3];case 3:return[2,a]}}))}))},f=function(){function e(e){this.web3=new a(e)}return e.prototype.getEvmGasPrice=function(){return h(this,void 0,void 0,(function(){return m(this,(function(e){switch(e.label){case 0:return[4,g(this.web3.eth.getGasPrice,[])];case 1:return[2,e.sent()]}}))}))},e.prototype.getEvmGasLimit=function(e,t){return h(this,void 0,void 0,(function(){return m(this,(function(a){switch(a.label){case 0:return[4,g(this.web3.eth.estimateGas,[e,t])];case 1:return[2,a.sent()]}}))}))},e}(),y=function(t){return t=t.trim(),e.existsSync(t)},b=function(e,a){var r=a.length;if(0===r)return!0;for(var s=0;s<r;s++){var n=t.join(e,"accounts/".concat(a[s],".json"));if(!y(n))return!1}return!0},v=function(t){var a=e.readFileSync(t).toString();return JSON.parse(a)},w=function(t,a){var r=JSON.stringify(t);e.writeFileSync(a,r)},k=function(e,t){return u.AES.encrypt(e,t).toString()},x=function(e,t){return u.AES.decrypt(e,t).toString(u.enc.Utf8)},_=["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"],A=new a(a.givenProvider),S=function(){function S(e,t,a){if(this.account_passwords={},this.account_ciphertexts={},this.setting_path=e,this.account_labels=t,0!==t.length){if(a){if(t.length!==a.length)throw new Error("account_labels should have same length for account_passwords");for(var r=0;r<t.length;r++){if(!this.checkPassword(t[r],a[r].trim()))throw new Error("account_passwords is not correct");this.account_passwords[t[r]]=a[r].trim()}}this.reload()}}return S.prototype.isLogin=function(e){return e in this.account_passwords},S.prototype.reloadAccount=function(){this.reload()},S.prototype.getAccountLabel=function(e){return e=this.getAccountChecksumAddress(e),this.checkAccountIsExist(e)?this.account_ciphertexts[e].account_labels:null},S.prototype.login=function(e,t){return this.checkPassword(e,t)?(this.account_passwords[e]=t,this.account_labels.push(e),this.reload(),{status:!0,output:"Login success"}):{status:!1,output:"Password is not correct"}},S.prototype.checkAccountLabelIsExist=function(e){return b(this.setting_path,[e])},S.prototype.checkAccountIsExist=function(e){return(e=this.getAccountChecksumAddress(e))in this.account_ciphertexts||(this.reload(),e in this.account_ciphertexts)},S.prototype.checkPassword=function(e,a){var r=t.join(this.setting_path,"accounts/".concat(e,".json"));if(!y(r))return!1;var s,n=v(r);s="PK"===n.account_type?d({salt:a},n.ciphertexts):{slat:a,data:n.pp_ciphertexts};var o=u.SHA256(JSON.stringify(s)).toString();return n.signature===o},S.prototype.showPrivateKey=function(e){if(!this.checkAccountIsExist(e))throw new Error("Account is not exist");e=this.getAccountChecksumAddress(e);var t=this.account_ciphertexts[e],a=this.account_passwords[t.account_labels];return x(t.data,a)},S.prototype.getAccountChainType=function(e){return e.startsWith("0x")&&42===e.length?"evm":/^[A-HJ-NP-Za-km-z1-9]*$/.test(e)?"solana":"unknown"},S.prototype.generatePKAccount=function(e,t,a,r){if(this.checkAccountLabelIsExist(e))throw new Error("Account labels already exist");var s=k(t,a),n={address:this.getAccountAddressByPrivateKey(t,r),data:s},o=d({salt:a},n),i={signature:u.SHA256(JSON.stringify(o)).toString(),account_type:"PK",tag:"",ciphertexts:n};return this.account_passwords[e]=a,this.account_labels.push(e),{status:!0,output:i}},S.prototype.generatePPAccount=function(e,t,a){if(this.checkAccountLabelIsExist(e))return{status:!1,output:"Account labels already exist"};var r=k(t,a),s={slat:a,data:r},n=u.SHA256(JSON.stringify(s)).toString(),o=this.getSubAccount("evm",t,0);if(!1===o.status)return{status:!1,output:o.output};var i=this.getSubAccount("solana",t,0);if(!1===i.status)return{status:!1,output:i.output};var c={signature:n,account_type:"PP",pp_ciphertexts:r,tag:"",data:[{ciphertexts:{evm:{address:o.output.address,data:k(o.output.pk,a)},solana:{address:i.output.address,data:k(i.output.pk,a)}}}]};return this.account_passwords[e]=a,this.account_labels.push(e),{status:!0,output:c}},S.prototype.generateSubAccount=function(e,a){if(!this.checkAccountLabelIsExist(e))return{status:!1,output:"Account labels not exist"};var r=t.join(this.setting_path,"accounts/".concat(e,".json")),s=v(r).pp_ciphertexts,n=x(s,this.account_passwords[e]),o=this.getSubAccount("evm",n,a);if(!1===o.status)return{status:!1,output:o.output};var i=this.getSubAccount("solana",n,a);return!1===i.status?{status:!1,output:i.output}:{status:!0,output:{evm:{address:o.output.address,data:k(o.output.pk,this.account_passwords[e])},solana:{address:i.output.address,data:k(i.output.pk,this.account_passwords[e])}}}},S.prototype.resetPassword=function(e,a){if(!this.checkAccountLabelIsExist(e))return{status:!1,output:"Account labels not exist"};if(!this.checkPassword(e,this.account_passwords[e]))return{status:!1,output:"account passwords is not correct"};var r=t.join(this.setting_path,"accounts/".concat(e,".json")),s=v(r);if("PK"===s.account_type){var n=s.ciphertexts.data,o=x(n,this.account_passwords[e]);s.ciphertexts.data=k(o,a);var i=d({salt:a},s.ciphertexts);return s.signature=u.SHA256(JSON.stringify(i)).toString(),w(s,r),delete this.account_passwords[e],{status:!0,output:"Password reset successfully"}}var c=x(s.pp_ciphertexts,this.account_passwords[e]);s.pp_ciphertexts=k(c,a);var l={slat:a,data:s.pp_ciphertexts};s.signature=u.SHA256(JSON.stringify(l)).toString();for(var p=s.data,h=0;h<p.length;h++){var m=x(p[h].ciphertexts.evm.data,this.account_passwords[e]);p[h].ciphertexts.evm.data=k(m,a);var g=x(p[h].ciphertexts.solana.data,this.account_passwords[e]);p[h].ciphertexts.solana.data=k(g,a)}return w(s,r),delete this.account_passwords[e],{status:!0,output:"Password reset successfully"}},S.prototype.signTransaction=function(e,t,a){return e=this.getAccountChecksumAddress(e),"unknown"===this.getAccountChainType(e)?{status:!1,output:"Chain type unknown"}:"evm"===this.getAccountChainType(e)?this.signEvmTransaction(t,a):this.signSolanaTransaction(e,a,t)},S.prototype.sendSignedTransaction=function(e,t,a){return e=this.getAccountChecksumAddress(e),"unknown"===this.getAccountChainType(e)?{status:!1,output:"Chain type unknown"}:"evm"===this.getAccountChainType(e)?this.sendEvmTransaction(t,a):this.sendSolanaTransaction(t,a)},S.prototype.signMessage=function(e,t){return e=this.getAccountChecksumAddress(e),"unknown"===this.getAccountChainType(e)?{status:!1,output:"Chain type unknown"}:"evm"===this.getAccountChainType(e)?{status:!0,output:this.signEvmMessage(t,e)}:{status:!0,output:this.signSolanaMessage(t,e)}},S.prototype.simulateTransaction=function(e,t,a){return h(this,void 0,void 0,(function(){var r,n,c,u;return m(this,(function(l){switch(l.label){case 0:return console.log("simulateTransaction",e,t,a),r=new i(t),n=this.showPrivateKey(e),c=o.fromSecretKey(s.decode(n)),[4,g(r.simulateTransaction.bind(r),[a,[c]])];case 1:return u=l.sent(),console.log("simulate_transaction_result: ",u),[2,u]}}))}))},S.prototype.signEvmTransaction=function(e,t){return h(this,void 0,void 0,(function(){var r,s,n,o;return m(this,(function(i){switch(i.label){case 0:return this.account_passwords?(r=e.from,e.gas?[3,2]:[4,new f(t).getEvmGasLimit(e,t)]):[2,{status:!1,output:"Please set password first"}];case 1:if(!(s=i.sent()).status)return[2,s];e.gas=s.output,i.label=2;case 2:return e.gasPrice?[3,4]:[4,new f(t).getEvmGasPrice()];case 3:if(!(s=i.sent()).status)return[2,s];e.gasPrice=s.output,i.label=4;case 4:return n=this.showPrivateKey(r),o=new a(t),[4,g(o.eth.accounts.signTransaction.bind(o.eth.accounts),[e,n])];case 5:return[2,i.sent()]}}))}))},S.prototype.sendEvmTransaction=function(e,t){return h(this,void 0,void 0,(function(){var r;return m(this,(function(s){switch(s.label){case 0:return r=new a(t),[4,g(r.eth.sendSignedTransaction.bind(r.eth),[e])];case 1:return[2,s.sent()]}}))}))},S.prototype.signSolanaTransaction=function(e,t,a){return h(this,void 0,void 0,(function(){var r,n,u,l,p;return m(this,(function(d){switch(d.label){case 0:return r=this.showPrivateKey(e),n=o.fromSecretKey(s.decode(r)),u=new c(n),"recentBlockhash"in a&&a.recentBlockhash?[3,2]:(l=new i(t),[4,g(l.getLatestBlockhash.bind(l),[])]);case 1:if(!(p=d.sent()).status)return[2,{status:!1,output:"Failed to get latest blockhash"}];a.recentBlockhash=p.output.blockhash,d.label=2;case 2:return a.feePayer=u.publicKey,[4,g(u.signTransaction.bind(u),[a])];case 3:return[2,d.sent()]}}))}))},S.prototype.sendSolanaTransaction=function(e,t){return h(this,void 0,void 0,(function(){var a;return m(this,(function(r){switch(r.label){case 0:return a=new i(t),[4,g(a.sendRawTransaction.bind(a),[e.serialize()])];case 1:return[2,r.sent()]}}))}))},S.prototype.signEvmMessage=function(e,t){var a=this.showPrivateKey(t);return A.eth.accounts.sign(e,a).signature},S.prototype.signSolanaMessage=function(e,t){var a=this.showPrivateKey(t),n=r.sign.detached(new Uint8Array(e.match(/.{1,2}/g).map((function(e){return parseInt(e,16)}))),s.decode(a));return s.encode(n)},S.prototype.reload=function(){if(!b(this.setting_path,this.account_labels))throw new Error("Account labels not exist");for(var a=this.account_labels.length,r=0;r<a;r++){var s=t.join(this.setting_path,"accounts/".concat(this.account_labels[r],".json")),n=JSON.parse(e.readFileSync(s,"utf8"));if("PK"!==n.account_type)for(var o=n.data.length,i=0;i<o;i++)this.account_ciphertexts[n.data[i].ciphertexts.evm.address]={account_labels:this.account_labels[r],data:n.data[i].ciphertexts.evm.data},this.account_ciphertexts[n.data[i].ciphertexts.solana.address]={account_labels:this.account_labels[r],data:n.data[i].ciphertexts.solana.data};else this.account_ciphertexts[n.ciphertexts.address]={account_labels:this.account_labels[r],data:n.ciphertexts.data}}},S.prototype.getAccountChecksumAddress=function(e){return"evm"===this.getAccountChainType(e)&&(e=A.utils.toChecksumAddress(e)),e},S.prototype.getAccountAddressByPrivateKey=function(e,t){return"evm"===this.getNetworkTypeByChainId(t)?A.eth.accounts.privateKeyToAccount(e).address:o.fromSecretKey(s.decode(e)).publicKey.toBase58()},S.prototype.getNetworkTypeByChainId=function(e){return"901"===e||"902"===e||"903"===e?"solana":"evm"},S.prototype.getSubAccount=function(e,t,a){if(!function(e){var t=e.split(/\s+/g),a=t.length;if(12!==a)return!1;for(var r=0;r<a;r++)if(!_.includes(t[r]))return!1;return!0}(t))return{status:!1,output:"Please set correct mnemonic"};if("solana"===e){var r=n.mnemonicToSeedSync(t),i=p.fromMasterSeed(r),c=o.fromSeed(i.derive("m/44'/501'/".concat(a,"'/0'")).privateKey);return{status:!0,output:{address:c.publicKey.toBase58(),pk:s.encode(c.secretKey)}}}if("evm"===e){r=n.mnemonicToSeedSync(t);var u=(i=l.fromMasterSeed(r)).derivePath("m/44'/60'/0'/0").deriveChild(a).getWallet();return{status:!0,output:{address:A.utils.toChecksumAddress(u.getAddressString()),pk:u.getPrivateKeyString()}}}return{status:!1,output:"Unknown chain type"}},S}(),j=require("../package.json"),P=function(){function e(e,t,a){this.account=new S(e,t,a)}return e.version=j.version,e}();export{P as WativeCore};
1
+ import*as e from"fs";import*as t from"path";import r from"web3";import*as a from"tweetnacl";import*as s from"bs58";import*as n from"bip39";import{Keypair as o,Connection as i}from"@solana/web3.js";import{Wallet as c}from"@coral-xyz/anchor";import*as u from"crypto-js";import{hdkey as l}from"ethereumjs-wallet";import{HDKey as p}from"micro-ed25519-hdkey";var d=function(){return d=Object.assign||function(e){for(var t,r=1,a=arguments.length;r<a;r++)for(var s in t=arguments[r])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},d.apply(this,arguments)};function h(e,t,r,a){return new(r||(r=Promise))((function(s,n){function o(e){try{c(a.next(e))}catch(e){n(e)}}function i(e){try{c(a.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,i)}c((a=a.apply(e,t||[])).next())}))}function m(e,t){var r,a,s,n,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]};return n={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(n[Symbol.iterator]=function(){return this}),n;function i(i){return function(c){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;n&&(n=0,i[0]&&(o=0)),o;)try{if(r=1,a&&(s=2&i[0]?a.return:i[0]?a.throw||((s=a.return)&&s.call(a),0):a.next)&&!(s=s.call(a,i[1])).done)return s;switch(a=0,s&&(i=[2&i[0],s.value]),i[0]){case 0:case 1:s=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,a=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(s=o.trys,(s=s.length>0&&s[s.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!s||i[1]>s[0]&&i[1]<s[3])){o.label=i[1];break}if(6===i[0]&&o.label<s[1]){o.label=s[1],s=i;break}if(s&&o.label<s[2]){o.label=s[2],o.ops.push(i);break}s[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],a=0}finally{r=s=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,c])}}}"function"==typeof SuppressedError&&SuppressedError;var g=function(e,t){return h(void 0,void 0,void 0,(function(){var r,a,s;return m(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,e.apply(void 0,t)];case 1:return a=n.sent(),r={status:!0,output:a},[3,3];case 2:return s=n.sent(),r={status:!1,output:s.toString()},[3,3];case 3:return[2,r]}}))}))},f=function(){function e(e){this.web3=new r(e)}return e.prototype.getEvmGasPrice=function(){return h(this,void 0,void 0,(function(){return m(this,(function(e){switch(e.label){case 0:return[4,g(this.web3.eth.getGasPrice,[])];case 1:return[2,e.sent()]}}))}))},e.prototype.getEvmGasLimit=function(e,t){return h(this,void 0,void 0,(function(){return m(this,(function(r){switch(r.label){case 0:return[4,g(this.web3.eth.estimateGas,[e,t])];case 1:return[2,r.sent()]}}))}))},e}(),y=function(t){return t=t.trim(),e.existsSync(t)},b=function(e,r){var a=r.length;if(0===a)return!0;for(var s=0;s<a;s++){var n=t.join(e,"accounts/".concat(r[s],".json"));if(!y(n))return!1}return!0},v=function(t){var r=e.readFileSync(t).toString();return JSON.parse(r)},w=function(t,r){var a=JSON.stringify(t);e.writeFileSync(r,a)},k=function(e,t){return u.AES.encrypt(e,t).toString()},x=function(e,t){return u.AES.decrypt(e,t).toString(u.enc.Utf8)},A=["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"],_=new r(r.givenProvider),S=function(){function S(e,t,r){if(this.account_passwords={},this.account_ciphertexts={},this.setting_path=e,this.account_labels=t,0!==t.length){if(r){if(t.length!==r.length)throw new Error("account_labels should have same length for account_passwords");for(var a=0;a<t.length;a++){if(!this.checkPassword(t[a],r[a].trim()))throw new Error("account_passwords is not correct");this.account_passwords[t[a]]=r[a].trim()}}this.reload()}}return S.prototype.isLogin=function(e){return e in this.account_passwords},S.prototype.reloadAccount=function(){this.reload()},S.prototype.getAccountLabel=function(e){return e=this.getAccountChecksumAddress(e),this.checkAccountIsExist(e)?this.account_ciphertexts[e].account_labels:null},S.prototype.login=function(e,t){return this.checkPassword(e,t)?(this.account_passwords[e]=t,this.account_labels.push(e),this.reload(),{status:!0,output:"Login success"}):{status:!1,output:"Password is not correct"}},S.prototype.checkAccountLabelIsExist=function(e){return b(this.setting_path,[e])},S.prototype.checkAccountIsExist=function(e){return(e=this.getAccountChecksumAddress(e))in this.account_ciphertexts||(this.reload(),e in this.account_ciphertexts)},S.prototype.checkPassword=function(e,r){var a=t.join(this.setting_path,"accounts/".concat(e,".json"));if(!y(a))return!1;var s,n=v(a);s="PK"===n.account_type?d({salt:r},n.ciphertexts):{slat:r,data:n.pp_ciphertexts};var o=u.SHA256(JSON.stringify(s)).toString();return n.signature===o},S.prototype.showPrivateKey=function(e){if(!this.checkAccountIsExist(e))throw new Error("Account is not exist");e=this.getAccountChecksumAddress(e);var t=this.account_ciphertexts[e],r=this.account_passwords[t.account_labels];return x(t.data,r)},S.prototype.getAccountChainType=function(e){return e.startsWith("0x")&&42===e.length?"evm":/^[A-HJ-NP-Za-km-z1-9]*$/.test(e)?"solana":"unknown"},S.prototype.generatePKAccount=function(e,t,r,a){if(this.checkAccountLabelIsExist(e))throw new Error("Account labels already exist");var s=k(t,r),n={address:this.getAccountAddressByPrivateKey(t,a),data:s},o=d({salt:r},n),i={signature:u.SHA256(JSON.stringify(o)).toString(),account_type:"PK",tag:"",ciphertexts:n};return this.account_passwords[e]=r,this.account_labels.push(e),{status:!0,output:i}},S.prototype.generatePPAccount=function(e,t,r){if(this.checkAccountLabelIsExist(e))return{status:!1,output:"Account labels already exist"};var a=k(t,r),s={slat:r,data:a},n=u.SHA256(JSON.stringify(s)).toString(),o=this.getSubAccount("evm",t,0);if(!1===o.status)return{status:!1,output:o.output};var i=this.getSubAccount("solana",t,0);if(!1===i.status)return{status:!1,output:i.output};var c={signature:n,account_type:"PP",pp_ciphertexts:a,tag:"",data:[{ciphertexts:{evm:{address:o.output.address,data:k(o.output.pk,r)},solana:{address:i.output.address,data:k(i.output.pk,r)}}}]};return this.account_passwords[e]=r,this.account_labels.push(e),{status:!0,output:c}},S.prototype.generateSubAccount=function(e,r){if(!this.checkAccountLabelIsExist(e))return{status:!1,output:"Account labels not exist"};var a=t.join(this.setting_path,"accounts/".concat(e,".json")),s=v(a).pp_ciphertexts,n=x(s,this.account_passwords[e]),o=this.getSubAccount("evm",n,r);if(!1===o.status)return{status:!1,output:o.output};var i=this.getSubAccount("solana",n,r);return!1===i.status?{status:!1,output:i.output}:{status:!0,output:{evm:{address:o.output.address,data:k(o.output.pk,this.account_passwords[e])},solana:{address:i.output.address,data:k(i.output.pk,this.account_passwords[e])}}}},S.prototype.resetPassword=function(e,r){if(!this.checkAccountLabelIsExist(e))return{status:!1,output:"Account labels not exist"};if(!this.checkPassword(e,this.account_passwords[e]))return{status:!1,output:"account passwords is not correct"};var a=t.join(this.setting_path,"accounts/".concat(e,".json")),s=v(a);if("PK"===s.account_type){var n=s.ciphertexts.data,o=x(n,this.account_passwords[e]);s.ciphertexts.data=k(o,r);var i=d({salt:r},s.ciphertexts);return s.signature=u.SHA256(JSON.stringify(i)).toString(),w(s,a),delete this.account_passwords[e],{status:!0,output:"Password reset successfully"}}var c=x(s.pp_ciphertexts,this.account_passwords[e]);s.pp_ciphertexts=k(c,r);var l={slat:r,data:s.pp_ciphertexts};s.signature=u.SHA256(JSON.stringify(l)).toString();for(var p=s.data,h=0;h<p.length;h++){var m=x(p[h].ciphertexts.evm.data,this.account_passwords[e]);p[h].ciphertexts.evm.data=k(m,r);var g=x(p[h].ciphertexts.solana.data,this.account_passwords[e]);p[h].ciphertexts.solana.data=k(g,r)}return w(s,a),delete this.account_passwords[e],{status:!0,output:"Password reset successfully"}},S.prototype.signTransaction=function(e,t,r){return e=this.getAccountChecksumAddress(e),"unknown"===this.getAccountChainType(e)?{status:!1,output:"Chain type unknown"}:"evm"===this.getAccountChainType(e)?this.signEvmTransaction(t,r):this.signSolanaTransaction(e,r,t)},S.prototype.sendSignedTransaction=function(e,t,r){return e=this.getAccountChecksumAddress(e),"unknown"===this.getAccountChainType(e)?{status:!1,output:"Chain type unknown"}:"evm"===this.getAccountChainType(e)?this.sendEvmTransaction(t,r):this.sendSolanaTransaction(t,r)},S.prototype.signMessage=function(e,t){return e=this.getAccountChecksumAddress(e),"unknown"===this.getAccountChainType(e)?{status:!1,output:"Chain type unknown"}:"evm"===this.getAccountChainType(e)?{status:!0,output:this.signEvmMessage(t,e)}:{status:!0,output:this.signSolanaMessage(t,e)}},S.prototype.simulateTransaction=function(e,t,r){return h(this,void 0,void 0,(function(){var a,n,c;return m(this,(function(u){switch(u.label){case 0:return a=new i(t),n=this.showPrivateKey(e),c=o.fromSecretKey(s.decode(n)),[4,g(a.simulateTransaction.bind(a),[r,[c]])];case 1:return[2,u.sent()]}}))}))},S.prototype.signEvmTransaction=function(e,t){return h(this,void 0,void 0,(function(){var a,s,n,o;return m(this,(function(i){switch(i.label){case 0:return this.account_passwords?(a=e.from,e.gas?[3,2]:[4,new f(t).getEvmGasLimit(e,t)]):[2,{status:!1,output:"Please set password first"}];case 1:if(!(s=i.sent()).status)return[2,s];e.gas=s.output,i.label=2;case 2:return e.gasPrice?[3,4]:[4,new f(t).getEvmGasPrice()];case 3:if(!(s=i.sent()).status)return[2,s];e.gasPrice=s.output,i.label=4;case 4:return n=this.showPrivateKey(a),o=new r(t),[4,g(o.eth.accounts.signTransaction.bind(o.eth.accounts),[e,n])];case 5:return[2,i.sent()]}}))}))},S.prototype.sendEvmTransaction=function(e,t){return h(this,void 0,void 0,(function(){var a;return m(this,(function(s){switch(s.label){case 0:return a=new r(t),[4,g(a.eth.sendSignedTransaction.bind(a.eth),[e])];case 1:return[2,s.sent()]}}))}))},S.prototype.signSolanaTransaction=function(e,t,r){return h(this,void 0,void 0,(function(){var a,n,u,l,p;return m(this,(function(d){switch(d.label){case 0:return a=this.showPrivateKey(e),n=o.fromSecretKey(s.decode(a)),u=new c(n),"recentBlockhash"in r&&r.recentBlockhash?[3,2]:(l=new i(t),[4,g(l.getLatestBlockhash.bind(l),[])]);case 1:if(!(p=d.sent()).status)return[2,{status:!1,output:"Failed to get latest blockhash"}];r.recentBlockhash=p.output.blockhash,d.label=2;case 2:return r.feePayer=u.publicKey,[4,g(u.signTransaction.bind(u),[r])];case 3:return[2,d.sent()]}}))}))},S.prototype.sendSolanaTransaction=function(e,t){return h(this,void 0,void 0,(function(){var r;return m(this,(function(a){switch(a.label){case 0:return r=new i(t),[4,g(r.sendRawTransaction.bind(r),[e.serialize()])];case 1:return[2,a.sent()]}}))}))},S.prototype.signEvmMessage=function(e,t){var r=this.showPrivateKey(t);return _.eth.accounts.sign(e,r).signature},S.prototype.signSolanaMessage=function(e,t){var r=this.showPrivateKey(t),n=a.sign.detached(new Uint8Array(e.match(/.{1,2}/g).map((function(e){return parseInt(e,16)}))),s.decode(r));return s.encode(n)},S.prototype.reload=function(){if(!b(this.setting_path,this.account_labels))throw new Error("Account labels not exist");for(var r=this.account_labels.length,a=0;a<r;a++){var s=t.join(this.setting_path,"accounts/".concat(this.account_labels[a],".json")),n=JSON.parse(e.readFileSync(s,"utf8"));if("PK"!==n.account_type)for(var o=n.data.length,i=0;i<o;i++)this.account_ciphertexts[n.data[i].ciphertexts.evm.address]={account_labels:this.account_labels[a],data:n.data[i].ciphertexts.evm.data},this.account_ciphertexts[n.data[i].ciphertexts.solana.address]={account_labels:this.account_labels[a],data:n.data[i].ciphertexts.solana.data};else this.account_ciphertexts[n.ciphertexts.address]={account_labels:this.account_labels[a],data:n.ciphertexts.data}}},S.prototype.getAccountChecksumAddress=function(e){return"evm"===this.getAccountChainType(e)&&(e=_.utils.toChecksumAddress(e)),e},S.prototype.getAccountAddressByPrivateKey=function(e,t){return"evm"===this.getNetworkTypeByChainId(t)?_.eth.accounts.privateKeyToAccount(e).address:o.fromSecretKey(s.decode(e)).publicKey.toBase58()},S.prototype.getNetworkTypeByChainId=function(e){return"901"===e||"902"===e||"903"===e?"solana":"evm"},S.prototype.getSubAccount=function(e,t,r){if(!function(e){var t=e.split(/\s+/g),r=t.length;if(12!==r)return!1;for(var a=0;a<r;a++)if(!A.includes(t[a]))return!1;return!0}(t))return{status:!1,output:"Please set correct mnemonic"};if("solana"===e){var a=n.mnemonicToSeedSync(t),i=p.fromMasterSeed(a),c=o.fromSeed(i.derive("m/44'/501'/".concat(r,"'/0'")).privateKey);return{status:!0,output:{address:c.publicKey.toBase58(),pk:s.encode(c.secretKey)}}}if("evm"===e){a=n.mnemonicToSeedSync(t);var u=(i=l.fromMasterSeed(a)).derivePath("m/44'/60'/0'/0").deriveChild(r).getWallet();return{status:!0,output:{address:_.utils.toChecksumAddress(u.getAddressString()),pk:u.getPrivateKeyString()}}}return{status:!1,output:"Unknown chain type"}},S}(),j=require("../package.json"),P=function(){function e(e,t,r){this.account=new S(e,t,r)}return e.version=j.version,e}();export{P as WativeCore};
package/lib/index.umd.js CHANGED
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("fs"),require("path"),require("web3"),require("tweetnacl"),require("bs58"),require("bip39"),require("@solana/web3.js"),require("@coral-xyz/anchor"),require("crypto-js"),require("ethereumjs-wallet"),require("micro-ed25519-hdkey")):"function"==typeof define&&define.amd?define(["exports","fs","path","web3","tweetnacl","bs58","bip39","@solana/web3.js","@coral-xyz/anchor","crypto-js","ethereumjs-wallet","micro-ed25519-hdkey"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).demo={},e.fs,e.path,e.Web3,e.nacl,e.bs58,e.bip39,e.web3_js,e.anchor,e.CryptoJS,e.ethereumjsWallet,e.microEd25519Hdkey)}(this,(function(e,t,r,a,n,s,o,i,c,u,l,p){"use strict";function d(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function h(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var a=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,a.get?a:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var m=h(t),g=h(r),f=d(a),y=h(n),b=h(s),v=h(o),w=h(u),k=function(){return k=Object.assign||function(e){for(var t,r=1,a=arguments.length;r<a;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},k.apply(this,arguments)};function x(e,t,r,a){return new(r||(r=Promise))((function(n,s){function o(e){try{c(a.next(e))}catch(e){s(e)}}function i(e){try{c(a.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,i)}c((a=a.apply(e,t||[])).next())}))}function _(e,t){var r,a,n,s,o={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(i){return function(c){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,i[0]&&(o=0)),o;)try{if(r=1,a&&(n=2&i[0]?a.return:i[0]?a.throw||((n=a.return)&&n.call(a),0):a.next)&&!(n=n.call(a,i[1])).done)return n;switch(a=0,n&&(i=[2&i[0],n.value]),i[0]){case 0:case 1:n=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,a=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(n=o.trys,(n=n.length>0&&n[n.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!n||i[1]>n[0]&&i[1]<n[3])){o.label=i[1];break}if(6===i[0]&&o.label<n[1]){o.label=n[1],n=i;break}if(n&&o.label<n[2]){o.label=n[2],o.ops.push(i);break}n[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],a=0}finally{r=n=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,c])}}}"function"==typeof SuppressedError&&SuppressedError;var A=function(e,t){return x(void 0,void 0,void 0,(function(){var r,a,n;return _(this,(function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),[4,e.apply(void 0,t)];case 1:return a=s.sent(),r={status:!0,output:a},[3,3];case 2:return n=s.sent(),r={status:!1,output:n.toString()},[3,3];case 3:return[2,r]}}))}))},S=function(){function e(e){this.web3=new f.default(e)}return e.prototype.getEvmGasPrice=function(){return x(this,void 0,void 0,(function(){return _(this,(function(e){switch(e.label){case 0:return[4,A(this.web3.eth.getGasPrice,[])];case 1:return[2,e.sent()]}}))}))},e.prototype.getEvmGasLimit=function(e,t){return x(this,void 0,void 0,(function(){return _(this,(function(r){switch(r.label){case 0:return[4,A(this.web3.eth.estimateGas,[e,t])];case 1:return[2,r.sent()]}}))}))},e}(),j=function(e){return e=e.trim(),m.existsSync(e)},P=function(e,t){var r=t.length;if(0===r)return!0;for(var a=0;a<r;a++){var n=g.join(e,"accounts/".concat(t[a],".json"));if(!j(n))return!1}return!0},z=function(e){var t=m.readFileSync(e).toString();return JSON.parse(t)},q=function(e,t){var r=JSON.stringify(e);m.writeFileSync(t,r)},T=function(e,t){return w.AES.encrypt(e,t).toString()},E=function(e,t){return w.AES.decrypt(e,t).toString(w.enc.Utf8)},C=["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"],K=new f.default(f.default.givenProvider),O=function(){function e(e,t,r){if(this.account_passwords={},this.account_ciphertexts={},this.setting_path=e,this.account_labels=t,0!==t.length){if(r){if(t.length!==r.length)throw new Error("account_labels should have same length for account_passwords");for(var a=0;a<t.length;a++){if(!this.checkPassword(t[a],r[a].trim()))throw new Error("account_passwords is not correct");this.account_passwords[t[a]]=r[a].trim()}}this.reload()}}return e.prototype.isLogin=function(e){return e in this.account_passwords},e.prototype.reloadAccount=function(){this.reload()},e.prototype.getAccountLabel=function(e){return e=this.getAccountChecksumAddress(e),this.checkAccountIsExist(e)?this.account_ciphertexts[e].account_labels:null},e.prototype.login=function(e,t){return this.checkPassword(e,t)?(this.account_passwords[e]=t,this.account_labels.push(e),this.reload(),{status:!0,output:"Login success"}):{status:!1,output:"Password is not correct"}},e.prototype.checkAccountLabelIsExist=function(e){return P(this.setting_path,[e])},e.prototype.checkAccountIsExist=function(e){return(e=this.getAccountChecksumAddress(e))in this.account_ciphertexts||(this.reload(),e in this.account_ciphertexts)},e.prototype.checkPassword=function(e,t){var r=g.join(this.setting_path,"accounts/".concat(e,".json"));if(!j(r))return!1;var a,n=z(r);a="PK"===n.account_type?k({salt:t},n.ciphertexts):{slat:t,data:n.pp_ciphertexts};var s=w.SHA256(JSON.stringify(a)).toString();return n.signature===s},e.prototype.showPrivateKey=function(e){if(!this.checkAccountIsExist(e))throw new Error("Account is not exist");e=this.getAccountChecksumAddress(e);var t=this.account_ciphertexts[e],r=this.account_passwords[t.account_labels];return E(t.data,r)},e.prototype.getAccountChainType=function(e){return e.startsWith("0x")&&42===e.length?"evm":/^[A-HJ-NP-Za-km-z1-9]*$/.test(e)?"solana":"unknown"},e.prototype.generatePKAccount=function(e,t,r,a){if(this.checkAccountLabelIsExist(e))throw new Error("Account labels already exist");var n=T(t,r),s={address:this.getAccountAddressByPrivateKey(t,a),data:n},o=k({salt:r},s),i={signature:w.SHA256(JSON.stringify(o)).toString(),account_type:"PK",tag:"",ciphertexts:s};return this.account_passwords[e]=r,this.account_labels.push(e),{status:!0,output:i}},e.prototype.generatePPAccount=function(e,t,r){if(this.checkAccountLabelIsExist(e))return{status:!1,output:"Account labels already exist"};var a=T(t,r),n={slat:r,data:a},s=w.SHA256(JSON.stringify(n)).toString(),o=this.getSubAccount("evm",t,0);if(!1===o.status)return{status:!1,output:o.output};var i=this.getSubAccount("solana",t,0);if(!1===i.status)return{status:!1,output:i.output};var c={signature:s,account_type:"PP",pp_ciphertexts:a,tag:"",data:[{ciphertexts:{evm:{address:o.output.address,data:T(o.output.pk,r)},solana:{address:i.output.address,data:T(i.output.pk,r)}}}]};return this.account_passwords[e]=r,this.account_labels.push(e),{status:!0,output:c}},e.prototype.generateSubAccount=function(e,t){if(!this.checkAccountLabelIsExist(e))return{status:!1,output:"Account labels not exist"};var r=g.join(this.setting_path,"accounts/".concat(e,".json")),a=z(r).pp_ciphertexts,n=E(a,this.account_passwords[e]),s=this.getSubAccount("evm",n,t);if(!1===s.status)return{status:!1,output:s.output};var o=this.getSubAccount("solana",n,t);return!1===o.status?{status:!1,output:o.output}:{status:!0,output:{evm:{address:s.output.address,data:T(s.output.pk,this.account_passwords[e])},solana:{address:o.output.address,data:T(o.output.pk,this.account_passwords[e])}}}},e.prototype.resetPassword=function(e,t){if(!this.checkAccountLabelIsExist(e))return{status:!1,output:"Account labels not exist"};if(!this.checkPassword(e,this.account_passwords[e]))return{status:!1,output:"account passwords is not correct"};var r=g.join(this.setting_path,"accounts/".concat(e,".json")),a=z(r);if("PK"===a.account_type){var n=a.ciphertexts.data,s=E(n,this.account_passwords[e]);a.ciphertexts.data=T(s,t);var o=k({salt:t},a.ciphertexts);return a.signature=w.SHA256(JSON.stringify(o)).toString(),q(a,r),delete this.account_passwords[e],{status:!0,output:"Password reset successfully"}}var i=E(a.pp_ciphertexts,this.account_passwords[e]);a.pp_ciphertexts=T(i,t);var c={slat:t,data:a.pp_ciphertexts};a.signature=w.SHA256(JSON.stringify(c)).toString();for(var u=a.data,l=0;l<u.length;l++){var p=E(u[l].ciphertexts.evm.data,this.account_passwords[e]);u[l].ciphertexts.evm.data=T(p,t);var d=E(u[l].ciphertexts.solana.data,this.account_passwords[e]);u[l].ciphertexts.solana.data=T(d,t)}return q(a,r),delete this.account_passwords[e],{status:!0,output:"Password reset successfully"}},e.prototype.signTransaction=function(e,t,r){return e=this.getAccountChecksumAddress(e),"unknown"===this.getAccountChainType(e)?{status:!1,output:"Chain type unknown"}:"evm"===this.getAccountChainType(e)?this.signEvmTransaction(t,r):this.signSolanaTransaction(e,r,t)},e.prototype.sendSignedTransaction=function(e,t,r){return e=this.getAccountChecksumAddress(e),"unknown"===this.getAccountChainType(e)?{status:!1,output:"Chain type unknown"}:"evm"===this.getAccountChainType(e)?this.sendEvmTransaction(t,r):this.sendSolanaTransaction(t,r)},e.prototype.signMessage=function(e,t){return e=this.getAccountChecksumAddress(e),"unknown"===this.getAccountChainType(e)?{status:!1,output:"Chain type unknown"}:"evm"===this.getAccountChainType(e)?{status:!0,output:this.signEvmMessage(t,e)}:{status:!0,output:this.signSolanaMessage(t,e)}},e.prototype.simulateTransaction=function(e,t,r){return x(this,void 0,void 0,(function(){var a,n,s,o;return _(this,(function(c){switch(c.label){case 0:return console.log("simulateTransaction",e,t,r),a=new i.Connection(t),n=this.showPrivateKey(e),s=i.Keypair.fromSecretKey(b.decode(n)),[4,A(a.simulateTransaction.bind(a),[r,[s]])];case 1:return o=c.sent(),console.log("simulate_transaction_result: ",o),[2,o]}}))}))},e.prototype.signEvmTransaction=function(e,t){return x(this,void 0,void 0,(function(){var r,a,n,s;return _(this,(function(o){switch(o.label){case 0:return this.account_passwords?(r=e.from,e.gas?[3,2]:[4,new S(t).getEvmGasLimit(e,t)]):[2,{status:!1,output:"Please set password first"}];case 1:if(!(a=o.sent()).status)return[2,a];e.gas=a.output,o.label=2;case 2:return e.gasPrice?[3,4]:[4,new S(t).getEvmGasPrice()];case 3:if(!(a=o.sent()).status)return[2,a];e.gasPrice=a.output,o.label=4;case 4:return n=this.showPrivateKey(r),s=new f.default(t),[4,A(s.eth.accounts.signTransaction.bind(s.eth.accounts),[e,n])];case 5:return[2,o.sent()]}}))}))},e.prototype.sendEvmTransaction=function(e,t){return x(this,void 0,void 0,(function(){var r;return _(this,(function(a){switch(a.label){case 0:return r=new f.default(t),[4,A(r.eth.sendSignedTransaction.bind(r.eth),[e])];case 1:return[2,a.sent()]}}))}))},e.prototype.signSolanaTransaction=function(e,t,r){return x(this,void 0,void 0,(function(){var a,n,s,o,u;return _(this,(function(l){switch(l.label){case 0:return a=this.showPrivateKey(e),n=i.Keypair.fromSecretKey(b.decode(a)),s=new c.Wallet(n),"recentBlockhash"in r&&r.recentBlockhash?[3,2]:(o=new i.Connection(t),[4,A(o.getLatestBlockhash.bind(o),[])]);case 1:if(!(u=l.sent()).status)return[2,{status:!1,output:"Failed to get latest blockhash"}];r.recentBlockhash=u.output.blockhash,l.label=2;case 2:return r.feePayer=s.publicKey,[4,A(s.signTransaction.bind(s),[r])];case 3:return[2,l.sent()]}}))}))},e.prototype.sendSolanaTransaction=function(e,t){return x(this,void 0,void 0,(function(){var r;return _(this,(function(a){switch(a.label){case 0:return r=new i.Connection(t),[4,A(r.sendRawTransaction.bind(r),[e.serialize()])];case 1:return[2,a.sent()]}}))}))},e.prototype.signEvmMessage=function(e,t){var r=this.showPrivateKey(t);return K.eth.accounts.sign(e,r).signature},e.prototype.signSolanaMessage=function(e,t){var r=this.showPrivateKey(t),a=y.sign.detached(new Uint8Array(e.match(/.{1,2}/g).map((function(e){return parseInt(e,16)}))),b.decode(r));return b.encode(a)},e.prototype.reload=function(){if(!P(this.setting_path,this.account_labels))throw new Error("Account labels not exist");for(var e=this.account_labels.length,t=0;t<e;t++){var r=g.join(this.setting_path,"accounts/".concat(this.account_labels[t],".json")),a=JSON.parse(m.readFileSync(r,"utf8"));if("PK"!==a.account_type)for(var n=a.data.length,s=0;s<n;s++)this.account_ciphertexts[a.data[s].ciphertexts.evm.address]={account_labels:this.account_labels[t],data:a.data[s].ciphertexts.evm.data},this.account_ciphertexts[a.data[s].ciphertexts.solana.address]={account_labels:this.account_labels[t],data:a.data[s].ciphertexts.solana.data};else this.account_ciphertexts[a.ciphertexts.address]={account_labels:this.account_labels[t],data:a.ciphertexts.data}}},e.prototype.getAccountChecksumAddress=function(e){return"evm"===this.getAccountChainType(e)&&(e=K.utils.toChecksumAddress(e)),e},e.prototype.getAccountAddressByPrivateKey=function(e,t){return"evm"===this.getNetworkTypeByChainId(t)?K.eth.accounts.privateKeyToAccount(e).address:i.Keypair.fromSecretKey(b.decode(e)).publicKey.toBase58()},e.prototype.getNetworkTypeByChainId=function(e){return"901"===e||"902"===e||"903"===e?"solana":"evm"},e.prototype.getSubAccount=function(e,t,r){if(!function(e){var t=e.split(/\s+/g),r=t.length;if(12!==r)return!1;for(var a=0;a<r;a++)if(!C.includes(t[a]))return!1;return!0}(t))return{status:!1,output:"Please set correct mnemonic"};if("solana"===e){var a=v.mnemonicToSeedSync(t),n=p.HDKey.fromMasterSeed(a),s=i.Keypair.fromSeed(n.derive("m/44'/501'/".concat(r,"'/0'")).privateKey);return{status:!0,output:{address:s.publicKey.toBase58(),pk:b.encode(s.secretKey)}}}if("evm"===e){a=v.mnemonicToSeedSync(t);var o=(n=l.hdkey.fromMasterSeed(a)).derivePath("m/44'/60'/0'/0").deriveChild(r).getWallet();return{status:!0,output:{address:K.utils.toChecksumAddress(o.getAddressString()),pk:o.getPrivateKeyString()}}}return{status:!1,output:"Unknown chain type"}},e}(),I=require("../package.json"),L=function(){function e(e,t,r){this.account=new O(e,t,r)}return e.version=I.version,e}();e.WativeCore=L,Object.defineProperty(e,"__esModule",{value:!0})}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("fs"),require("path"),require("web3"),require("tweetnacl"),require("bs58"),require("bip39"),require("@solana/web3.js"),require("@coral-xyz/anchor"),require("crypto-js"),require("ethereumjs-wallet"),require("micro-ed25519-hdkey")):"function"==typeof define&&define.amd?define(["exports","fs","path","web3","tweetnacl","bs58","bip39","@solana/web3.js","@coral-xyz/anchor","crypto-js","ethereumjs-wallet","micro-ed25519-hdkey"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).demo={},e.fs,e.path,e.Web3,e.nacl,e.bs58,e.bip39,e.web3_js,e.anchor,e.CryptoJS,e.ethereumjsWallet,e.microEd25519Hdkey)}(this,(function(e,t,r,a,n,s,o,i,c,u,l,p){"use strict";function d(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function h(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var a=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,a.get?a:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var m=h(t),g=h(r),f=d(a),y=h(n),b=h(s),v=h(o),w=h(u),k=function(){return k=Object.assign||function(e){for(var t,r=1,a=arguments.length;r<a;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},k.apply(this,arguments)};function x(e,t,r,a){return new(r||(r=Promise))((function(n,s){function o(e){try{c(a.next(e))}catch(e){s(e)}}function i(e){try{c(a.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,i)}c((a=a.apply(e,t||[])).next())}))}function _(e,t){var r,a,n,s,o={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(i){return function(c){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,i[0]&&(o=0)),o;)try{if(r=1,a&&(n=2&i[0]?a.return:i[0]?a.throw||((n=a.return)&&n.call(a),0):a.next)&&!(n=n.call(a,i[1])).done)return n;switch(a=0,n&&(i=[2&i[0],n.value]),i[0]){case 0:case 1:n=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,a=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(n=o.trys,(n=n.length>0&&n[n.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!n||i[1]>n[0]&&i[1]<n[3])){o.label=i[1];break}if(6===i[0]&&o.label<n[1]){o.label=n[1],n=i;break}if(n&&o.label<n[2]){o.label=n[2],o.ops.push(i);break}n[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],a=0}finally{r=n=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,c])}}}"function"==typeof SuppressedError&&SuppressedError;var A=function(e,t){return x(void 0,void 0,void 0,(function(){var r,a,n;return _(this,(function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),[4,e.apply(void 0,t)];case 1:return a=s.sent(),r={status:!0,output:a},[3,3];case 2:return n=s.sent(),r={status:!1,output:n.toString()},[3,3];case 3:return[2,r]}}))}))},S=function(){function e(e){this.web3=new f.default(e)}return e.prototype.getEvmGasPrice=function(){return x(this,void 0,void 0,(function(){return _(this,(function(e){switch(e.label){case 0:return[4,A(this.web3.eth.getGasPrice,[])];case 1:return[2,e.sent()]}}))}))},e.prototype.getEvmGasLimit=function(e,t){return x(this,void 0,void 0,(function(){return _(this,(function(r){switch(r.label){case 0:return[4,A(this.web3.eth.estimateGas,[e,t])];case 1:return[2,r.sent()]}}))}))},e}(),j=function(e){return e=e.trim(),m.existsSync(e)},P=function(e,t){var r=t.length;if(0===r)return!0;for(var a=0;a<r;a++){var n=g.join(e,"accounts/".concat(t[a],".json"));if(!j(n))return!1}return!0},z=function(e){var t=m.readFileSync(e).toString();return JSON.parse(t)},q=function(e,t){var r=JSON.stringify(e);m.writeFileSync(t,r)},T=function(e,t){return w.AES.encrypt(e,t).toString()},E=function(e,t){return w.AES.decrypt(e,t).toString(w.enc.Utf8)},C=["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"],K=new f.default(f.default.givenProvider),O=function(){function e(e,t,r){if(this.account_passwords={},this.account_ciphertexts={},this.setting_path=e,this.account_labels=t,0!==t.length){if(r){if(t.length!==r.length)throw new Error("account_labels should have same length for account_passwords");for(var a=0;a<t.length;a++){if(!this.checkPassword(t[a],r[a].trim()))throw new Error("account_passwords is not correct");this.account_passwords[t[a]]=r[a].trim()}}this.reload()}}return e.prototype.isLogin=function(e){return e in this.account_passwords},e.prototype.reloadAccount=function(){this.reload()},e.prototype.getAccountLabel=function(e){return e=this.getAccountChecksumAddress(e),this.checkAccountIsExist(e)?this.account_ciphertexts[e].account_labels:null},e.prototype.login=function(e,t){return this.checkPassword(e,t)?(this.account_passwords[e]=t,this.account_labels.push(e),this.reload(),{status:!0,output:"Login success"}):{status:!1,output:"Password is not correct"}},e.prototype.checkAccountLabelIsExist=function(e){return P(this.setting_path,[e])},e.prototype.checkAccountIsExist=function(e){return(e=this.getAccountChecksumAddress(e))in this.account_ciphertexts||(this.reload(),e in this.account_ciphertexts)},e.prototype.checkPassword=function(e,t){var r=g.join(this.setting_path,"accounts/".concat(e,".json"));if(!j(r))return!1;var a,n=z(r);a="PK"===n.account_type?k({salt:t},n.ciphertexts):{slat:t,data:n.pp_ciphertexts};var s=w.SHA256(JSON.stringify(a)).toString();return n.signature===s},e.prototype.showPrivateKey=function(e){if(!this.checkAccountIsExist(e))throw new Error("Account is not exist");e=this.getAccountChecksumAddress(e);var t=this.account_ciphertexts[e],r=this.account_passwords[t.account_labels];return E(t.data,r)},e.prototype.getAccountChainType=function(e){return e.startsWith("0x")&&42===e.length?"evm":/^[A-HJ-NP-Za-km-z1-9]*$/.test(e)?"solana":"unknown"},e.prototype.generatePKAccount=function(e,t,r,a){if(this.checkAccountLabelIsExist(e))throw new Error("Account labels already exist");var n=T(t,r),s={address:this.getAccountAddressByPrivateKey(t,a),data:n},o=k({salt:r},s),i={signature:w.SHA256(JSON.stringify(o)).toString(),account_type:"PK",tag:"",ciphertexts:s};return this.account_passwords[e]=r,this.account_labels.push(e),{status:!0,output:i}},e.prototype.generatePPAccount=function(e,t,r){if(this.checkAccountLabelIsExist(e))return{status:!1,output:"Account labels already exist"};var a=T(t,r),n={slat:r,data:a},s=w.SHA256(JSON.stringify(n)).toString(),o=this.getSubAccount("evm",t,0);if(!1===o.status)return{status:!1,output:o.output};var i=this.getSubAccount("solana",t,0);if(!1===i.status)return{status:!1,output:i.output};var c={signature:s,account_type:"PP",pp_ciphertexts:a,tag:"",data:[{ciphertexts:{evm:{address:o.output.address,data:T(o.output.pk,r)},solana:{address:i.output.address,data:T(i.output.pk,r)}}}]};return this.account_passwords[e]=r,this.account_labels.push(e),{status:!0,output:c}},e.prototype.generateSubAccount=function(e,t){if(!this.checkAccountLabelIsExist(e))return{status:!1,output:"Account labels not exist"};var r=g.join(this.setting_path,"accounts/".concat(e,".json")),a=z(r).pp_ciphertexts,n=E(a,this.account_passwords[e]),s=this.getSubAccount("evm",n,t);if(!1===s.status)return{status:!1,output:s.output};var o=this.getSubAccount("solana",n,t);return!1===o.status?{status:!1,output:o.output}:{status:!0,output:{evm:{address:s.output.address,data:T(s.output.pk,this.account_passwords[e])},solana:{address:o.output.address,data:T(o.output.pk,this.account_passwords[e])}}}},e.prototype.resetPassword=function(e,t){if(!this.checkAccountLabelIsExist(e))return{status:!1,output:"Account labels not exist"};if(!this.checkPassword(e,this.account_passwords[e]))return{status:!1,output:"account passwords is not correct"};var r=g.join(this.setting_path,"accounts/".concat(e,".json")),a=z(r);if("PK"===a.account_type){var n=a.ciphertexts.data,s=E(n,this.account_passwords[e]);a.ciphertexts.data=T(s,t);var o=k({salt:t},a.ciphertexts);return a.signature=w.SHA256(JSON.stringify(o)).toString(),q(a,r),delete this.account_passwords[e],{status:!0,output:"Password reset successfully"}}var i=E(a.pp_ciphertexts,this.account_passwords[e]);a.pp_ciphertexts=T(i,t);var c={slat:t,data:a.pp_ciphertexts};a.signature=w.SHA256(JSON.stringify(c)).toString();for(var u=a.data,l=0;l<u.length;l++){var p=E(u[l].ciphertexts.evm.data,this.account_passwords[e]);u[l].ciphertexts.evm.data=T(p,t);var d=E(u[l].ciphertexts.solana.data,this.account_passwords[e]);u[l].ciphertexts.solana.data=T(d,t)}return q(a,r),delete this.account_passwords[e],{status:!0,output:"Password reset successfully"}},e.prototype.signTransaction=function(e,t,r){return e=this.getAccountChecksumAddress(e),"unknown"===this.getAccountChainType(e)?{status:!1,output:"Chain type unknown"}:"evm"===this.getAccountChainType(e)?this.signEvmTransaction(t,r):this.signSolanaTransaction(e,r,t)},e.prototype.sendSignedTransaction=function(e,t,r){return e=this.getAccountChecksumAddress(e),"unknown"===this.getAccountChainType(e)?{status:!1,output:"Chain type unknown"}:"evm"===this.getAccountChainType(e)?this.sendEvmTransaction(t,r):this.sendSolanaTransaction(t,r)},e.prototype.signMessage=function(e,t){return e=this.getAccountChecksumAddress(e),"unknown"===this.getAccountChainType(e)?{status:!1,output:"Chain type unknown"}:"evm"===this.getAccountChainType(e)?{status:!0,output:this.signEvmMessage(t,e)}:{status:!0,output:this.signSolanaMessage(t,e)}},e.prototype.simulateTransaction=function(e,t,r){return x(this,void 0,void 0,(function(){var a,n,s;return _(this,(function(o){switch(o.label){case 0:return a=new i.Connection(t),n=this.showPrivateKey(e),s=i.Keypair.fromSecretKey(b.decode(n)),[4,A(a.simulateTransaction.bind(a),[r,[s]])];case 1:return[2,o.sent()]}}))}))},e.prototype.signEvmTransaction=function(e,t){return x(this,void 0,void 0,(function(){var r,a,n,s;return _(this,(function(o){switch(o.label){case 0:return this.account_passwords?(r=e.from,e.gas?[3,2]:[4,new S(t).getEvmGasLimit(e,t)]):[2,{status:!1,output:"Please set password first"}];case 1:if(!(a=o.sent()).status)return[2,a];e.gas=a.output,o.label=2;case 2:return e.gasPrice?[3,4]:[4,new S(t).getEvmGasPrice()];case 3:if(!(a=o.sent()).status)return[2,a];e.gasPrice=a.output,o.label=4;case 4:return n=this.showPrivateKey(r),s=new f.default(t),[4,A(s.eth.accounts.signTransaction.bind(s.eth.accounts),[e,n])];case 5:return[2,o.sent()]}}))}))},e.prototype.sendEvmTransaction=function(e,t){return x(this,void 0,void 0,(function(){var r;return _(this,(function(a){switch(a.label){case 0:return r=new f.default(t),[4,A(r.eth.sendSignedTransaction.bind(r.eth),[e])];case 1:return[2,a.sent()]}}))}))},e.prototype.signSolanaTransaction=function(e,t,r){return x(this,void 0,void 0,(function(){var a,n,s,o,u;return _(this,(function(l){switch(l.label){case 0:return a=this.showPrivateKey(e),n=i.Keypair.fromSecretKey(b.decode(a)),s=new c.Wallet(n),"recentBlockhash"in r&&r.recentBlockhash?[3,2]:(o=new i.Connection(t),[4,A(o.getLatestBlockhash.bind(o),[])]);case 1:if(!(u=l.sent()).status)return[2,{status:!1,output:"Failed to get latest blockhash"}];r.recentBlockhash=u.output.blockhash,l.label=2;case 2:return r.feePayer=s.publicKey,[4,A(s.signTransaction.bind(s),[r])];case 3:return[2,l.sent()]}}))}))},e.prototype.sendSolanaTransaction=function(e,t){return x(this,void 0,void 0,(function(){var r;return _(this,(function(a){switch(a.label){case 0:return r=new i.Connection(t),[4,A(r.sendRawTransaction.bind(r),[e.serialize()])];case 1:return[2,a.sent()]}}))}))},e.prototype.signEvmMessage=function(e,t){var r=this.showPrivateKey(t);return K.eth.accounts.sign(e,r).signature},e.prototype.signSolanaMessage=function(e,t){var r=this.showPrivateKey(t),a=y.sign.detached(new Uint8Array(e.match(/.{1,2}/g).map((function(e){return parseInt(e,16)}))),b.decode(r));return b.encode(a)},e.prototype.reload=function(){if(!P(this.setting_path,this.account_labels))throw new Error("Account labels not exist");for(var e=this.account_labels.length,t=0;t<e;t++){var r=g.join(this.setting_path,"accounts/".concat(this.account_labels[t],".json")),a=JSON.parse(m.readFileSync(r,"utf8"));if("PK"!==a.account_type)for(var n=a.data.length,s=0;s<n;s++)this.account_ciphertexts[a.data[s].ciphertexts.evm.address]={account_labels:this.account_labels[t],data:a.data[s].ciphertexts.evm.data},this.account_ciphertexts[a.data[s].ciphertexts.solana.address]={account_labels:this.account_labels[t],data:a.data[s].ciphertexts.solana.data};else this.account_ciphertexts[a.ciphertexts.address]={account_labels:this.account_labels[t],data:a.ciphertexts.data}}},e.prototype.getAccountChecksumAddress=function(e){return"evm"===this.getAccountChainType(e)&&(e=K.utils.toChecksumAddress(e)),e},e.prototype.getAccountAddressByPrivateKey=function(e,t){return"evm"===this.getNetworkTypeByChainId(t)?K.eth.accounts.privateKeyToAccount(e).address:i.Keypair.fromSecretKey(b.decode(e)).publicKey.toBase58()},e.prototype.getNetworkTypeByChainId=function(e){return"901"===e||"902"===e||"903"===e?"solana":"evm"},e.prototype.getSubAccount=function(e,t,r){if(!function(e){var t=e.split(/\s+/g),r=t.length;if(12!==r)return!1;for(var a=0;a<r;a++)if(!C.includes(t[a]))return!1;return!0}(t))return{status:!1,output:"Please set correct mnemonic"};if("solana"===e){var a=v.mnemonicToSeedSync(t),n=p.HDKey.fromMasterSeed(a),s=i.Keypair.fromSeed(n.derive("m/44'/501'/".concat(r,"'/0'")).privateKey);return{status:!0,output:{address:s.publicKey.toBase58(),pk:b.encode(s.secretKey)}}}if("evm"===e){a=v.mnemonicToSeedSync(t);var o=(n=l.hdkey.fromMasterSeed(a)).derivePath("m/44'/60'/0'/0").deriveChild(r).getWallet();return{status:!0,output:{address:K.utils.toChecksumAddress(o.getAddressString()),pk:o.getPrivateKeyString()}}}return{status:!1,output:"Unknown chain type"}},e}(),I=require("../package.json"),L=function(){function e(e,t,r){this.account=new O(e,t,r)}return e.version=I.version,e}();e.WativeCore=L,Object.defineProperty(e,"__esModule",{value:!0})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wative-core",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "An agile keystore management toolkit",
5
5
  "main": "lib/index.umd.js",
6
6
  "module": "lib/index.esm.js",
@@ -22,7 +22,7 @@
22
22
  "keystore",
23
23
  "wallet"
24
24
  ],
25
- "author": "dannyburger",
25
+ "author": "",
26
26
  "license": "ISC",
27
27
  "files": [
28
28
  "src/",