wative-core 1.0.4 → 1.0.6
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 +1 -1
- package/lib/index.umd.js +1 -1
- package/package.json +1 -1
- package/src/account.ts +6 -3
package/lib/index.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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,a){if(this.account_passwords={},this.account_ciphertexts={},this.disable_address=!1,this.account_signatures="",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 s=0;s<t.length;s++){if(!this.checkPassword(t[s],r[s].trim()))throw new Error("account_passwords is not correct");this.account_passwords[t[s]]=r[s].trim()}}a&&(this.disable_address=a),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.getAccounts=function(e){var t=this.getAccountSignature();t!==this.account_signatures&&(this.account_signatures=t,this.reload());for(var r=Object.keys(this.account_ciphertexts),a=[],s=0;s<r.length;s++)this.getAccountChainType(r[s])===e&&a.push(r[s]);return a},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),this.checkAccountIsExist(e)?"unknown"===this.getAccountChainType(e)?{status:!1,output:"Chain type unknown"}:"evm"===this.getAccountChainType(e)?this.signEvmTransaction(t,r):this.signSolanaTransaction(e,r,t):{status:!1,output:"Account is not exist"}},S.prototype.sendSignedTransaction=function(e,t,r){return e=this.getAccountChecksumAddress(e),this.checkAccountIsExist(e)?"unknown"===this.getAccountChainType(e)?{status:!1,output:"Chain type unknown"}:"evm"===this.getAccountChainType(e)?this.sendEvmTransaction(t,r):this.sendSolanaTransaction(t,r):{status:!1,output:"Account is not exist"}},S.prototype.signMessage=function(e,t){return e=this.getAccountChecksumAddress(e),this.checkAccountIsExist(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)}:{status:!1,output:"Account is not exist"}},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.checkIsDisableAddress=function(e,t){if(!e||!this.disable_address)return!1;for(var r=e.length,a=0;a<r;a++){var s=e[a].from,n=e[a].to;if(t>=s&&t<=n)return!0}return!1},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=n.disabled_slots,c=0;c<o;c++)this.checkIsDisableAddress(i,c)||(this.account_ciphertexts[n.data[c].ciphertexts.evm.address]={account_labels:this.account_labels[a],data:n.data[c].ciphertexts.evm.data},this.account_ciphertexts[n.data[c].ciphertexts.solana.address]={account_labels:this.account_labels[a],data:n.data[c].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.prototype.getAccountSignature=function(){for(var r=this.account_labels.length,a=[],s=0;s<r;s++){var n=t.join(this.setting_path,"accounts/".concat(this.account_labels[s],".json")),o=e.readFileSync(n,"utf8");a.push(o)}return u.MD5(JSON.stringify(a)).toString()},S}(),j=require("../package.json"),P=function(){function e(e,t,r,a){this.account=new S(e,t,r,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,a){if(this.account_passwords={},this.account_ciphertexts={},this.disable_address=!1,this.account_signatures="",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 s=0;s<t.length;s++){if(!this.checkPassword(t[s],r[s].trim()))throw new Error("account_passwords is not correct");this.account_passwords[t[s]]=r[s].trim()}}a&&(this.disable_address=a),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.getAccounts=function(e){var t=this.getAccountSignature();t!==this.account_signatures&&(this.account_signatures=t,this.reload());for(var r=Object.keys(this.account_ciphertexts),a=[],s=0;s<r.length;s++)this.getAccountChainType(r[s])===e&&a.push(r[s]);return a},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),this.checkAccountIsExist(e)?"unknown"===this.getAccountChainType(e)?{status:!1,output:"Chain type unknown"}:"evm"===this.getAccountChainType(e)?this.signEvmTransaction(t,r):this.signSolanaTransaction(e,r,t):{status:!1,output:"Account is not exist"}},S.prototype.sendSignedTransaction=function(e,t,r){return e=this.getAccountChecksumAddress(e),this.checkAccountIsExist(e)?"unknown"===this.getAccountChainType(e)?{status:!1,output:"Chain type unknown"}:"evm"===this.getAccountChainType(e)?this.sendEvmTransaction(t,r):this.sendSolanaTransaction(t,r):{status:!1,output:"Account is not exist"}},S.prototype.signMessage=function(e,t){return e=this.getAccountChecksumAddress(e),this.checkAccountIsExist(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)}:{status:!1,output:"Account is not exist"}},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.checkIsDisableAddress=function(e,t){if(!e||!this.disable_address)return!1;for(var r=e.length,a=0;a<r;a++){var s=e[a].from,n=e[a].to;if(t>=s&&t<=n)return!0}return!1},S.prototype.reload=function(){if(!b(this.setting_path,this.account_labels))throw new Error("Account labels not exist");for(var r={},a=this.account_labels.length,s=0;s<a;s++){var n=t.join(this.setting_path,"accounts/".concat(this.account_labels[s],".json")),o=JSON.parse(e.readFileSync(n,"utf8"));if("PK"!==o.account_type)for(var i=o.data.length,c=o.disabled_slots,u=0;u<i;u++)this.checkIsDisableAddress(c,u)||(r[o.data[u].ciphertexts.evm.address]={account_labels:this.account_labels[s],data:o.data[u].ciphertexts.evm.data},r[o.data[u].ciphertexts.solana.address]={account_labels:this.account_labels[s],data:o.data[u].ciphertexts.solana.data});else r[o.ciphertexts.address]={account_labels:this.account_labels[s],data:o.ciphertexts.data}}this.account_ciphertexts=r},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.prototype.getAccountSignature=function(){for(var r=this.account_labels.length,a=[],s=0;s<r;s++){var n=t.join(this.setting_path,"accounts/".concat(this.account_labels[s],".json")),o=e.readFileSync(n,"utf8");a.push(o)}return u.MD5(JSON.stringify(a)).toString()},S}(),j=require("../package.json"),P=function(){function e(e,t,r,a){this.account=new S(e,t,r,a)}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,s,n,o,i,c,u,l,d){"use strict";function p(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 g=h(t),m=h(r),f=p(a),y=h(s),b=h(n),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 s in t=arguments[r])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},k.apply(this,arguments)};function x(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 _(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 A=function(e,t){return x(void 0,void 0,void 0,(function(){var r,a,s;return _(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]}}))}))},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(),g.existsSync(e)},P=function(e,t){var r=t.length;if(0===r)return!0;for(var a=0;a<r;a++){var s=m.join(e,"accounts/".concat(t[a],".json"));if(!j(s))return!1}return!0},z=function(e){var t=g.readFileSync(e).toString();return JSON.parse(t)},q=function(e,t){var r=JSON.stringify(e);g.writeFileSync(t,r)},E=function(e,t){return w.AES.encrypt(e,t).toString()},T=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,a){if(this.account_passwords={},this.account_ciphertexts={},this.disable_address=!1,this.account_signatures="",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 s=0;s<t.length;s++){if(!this.checkPassword(t[s],r[s].trim()))throw new Error("account_passwords is not correct");this.account_passwords[t[s]]=r[s].trim()}}a&&(this.disable_address=a),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.getAccounts=function(e){var t=this.getAccountSignature();t!==this.account_signatures&&(this.account_signatures=t,this.reload());for(var r=Object.keys(this.account_ciphertexts),a=[],s=0;s<r.length;s++)this.getAccountChainType(r[s])===e&&a.push(r[s]);return a},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=m.join(this.setting_path,"accounts/".concat(e,".json"));if(!j(r))return!1;var a,s=z(r);a="PK"===s.account_type?k({salt:t},s.ciphertexts):{slat:t,data:s.pp_ciphertexts};var n=w.SHA256(JSON.stringify(a)).toString();return s.signature===n},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 T(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 s=E(t,r),n={address:this.getAccountAddressByPrivateKey(t,a),data:s},o=k({salt:r},n),i={signature:w.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}},e.prototype.generatePPAccount=function(e,t,r){if(this.checkAccountLabelIsExist(e))return{status:!1,output:"Account labels already exist"};var a=E(t,r),s={slat:r,data:a},n=w.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:E(o.output.pk,r)},solana:{address:i.output.address,data:E(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=m.join(this.setting_path,"accounts/".concat(e,".json")),a=z(r).pp_ciphertexts,s=T(a,this.account_passwords[e]),n=this.getSubAccount("evm",s,t);if(!1===n.status)return{status:!1,output:n.output};var o=this.getSubAccount("solana",s,t);return!1===o.status?{status:!1,output:o.output}:{status:!0,output:{evm:{address:n.output.address,data:E(n.output.pk,this.account_passwords[e])},solana:{address:o.output.address,data:E(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=m.join(this.setting_path,"accounts/".concat(e,".json")),a=z(r);if("PK"===a.account_type){var s=a.ciphertexts.data,n=T(s,this.account_passwords[e]);a.ciphertexts.data=E(n,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=T(a.pp_ciphertexts,this.account_passwords[e]);a.pp_ciphertexts=E(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 d=T(u[l].ciphertexts.evm.data,this.account_passwords[e]);u[l].ciphertexts.evm.data=E(d,t);var p=T(u[l].ciphertexts.solana.data,this.account_passwords[e]);u[l].ciphertexts.solana.data=E(p,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),this.checkAccountIsExist(e)?"unknown"===this.getAccountChainType(e)?{status:!1,output:"Chain type unknown"}:"evm"===this.getAccountChainType(e)?this.signEvmTransaction(t,r):this.signSolanaTransaction(e,r,t):{status:!1,output:"Account is not exist"}},e.prototype.sendSignedTransaction=function(e,t,r){return e=this.getAccountChecksumAddress(e),this.checkAccountIsExist(e)?"unknown"===this.getAccountChainType(e)?{status:!1,output:"Chain type unknown"}:"evm"===this.getAccountChainType(e)?this.sendEvmTransaction(t,r):this.sendSolanaTransaction(t,r):{status:!1,output:"Account is not exist"}},e.prototype.signMessage=function(e,t){return e=this.getAccountChecksumAddress(e),this.checkAccountIsExist(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)}:{status:!1,output:"Account is not exist"}},e.prototype.simulateTransaction=function(e,t,r){return x(this,void 0,void 0,(function(){var a,s,n;return _(this,(function(o){switch(o.label){case 0:return a=new i.Connection(t),s=this.showPrivateKey(e),n=i.Keypair.fromSecretKey(b.decode(s)),[4,A(a.simulateTransaction.bind(a),[r,[n]])];case 1:return[2,o.sent()]}}))}))},e.prototype.signEvmTransaction=function(e,t){return x(this,void 0,void 0,(function(){var r,a,s,n;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 s=this.showPrivateKey(r),n=new f.default(t),[4,A(n.eth.accounts.signTransaction.bind(n.eth.accounts),[e,s])];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,s,n,o,u;return _(this,(function(l){switch(l.label){case 0:return a=this.showPrivateKey(e),s=i.Keypair.fromSecretKey(b.decode(a)),n=new c.Wallet(s),"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=n.publicKey,[4,A(n.signTransaction.bind(n),[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.checkIsDisableAddress=function(e,t){if(!e||!this.disable_address)return!1;for(var r=e.length,a=0;a<r;a++){var s=e[a].from,n=e[a].to;if(t>=s&&t<=n)return!0}return!1},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=m.join(this.setting_path,"accounts/".concat(this.account_labels[t],".json")),a=JSON.parse(g.readFileSync(r,"utf8"));if("PK"!==a.account_type)for(var s=a.data.length,n=a.disabled_slots,o=0;o<s;o++)this.checkIsDisableAddress(n,o)||(this.account_ciphertexts[a.data[o].ciphertexts.evm.address]={account_labels:this.account_labels[t],data:a.data[o].ciphertexts.evm.data},this.account_ciphertexts[a.data[o].ciphertexts.solana.address]={account_labels:this.account_labels[t],data:a.data[o].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),s=d.HDKey.fromMasterSeed(a),n=i.Keypair.fromSeed(s.derive("m/44'/501'/".concat(r,"'/0'")).privateKey);return{status:!0,output:{address:n.publicKey.toBase58(),pk:b.encode(n.secretKey)}}}if("evm"===e){a=v.mnemonicToSeedSync(t);var o=(s=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.prototype.getAccountSignature=function(){for(var e=this.account_labels.length,t=[],r=0;r<e;r++){var a=m.join(this.setting_path,"accounts/".concat(this.account_labels[r],".json")),s=g.readFileSync(a,"utf8");t.push(s)}return w.MD5(JSON.stringify(t)).toString()},e}(),I=require("../package.json"),N=function(){function e(e,t,r,a){this.account=new O(e,t,r,a)}return e.version=I.version,e}();e.WativeCore=N,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,s,n,o,i,c,u,l,d){"use strict";function p(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 g=h(t),m=h(r),f=p(a),y=h(s),b=h(n),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 s in t=arguments[r])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},k.apply(this,arguments)};function x(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 _(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 A=function(e,t){return x(void 0,void 0,void 0,(function(){var r,a,s;return _(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]}}))}))},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(),g.existsSync(e)},P=function(e,t){var r=t.length;if(0===r)return!0;for(var a=0;a<r;a++){var s=m.join(e,"accounts/".concat(t[a],".json"));if(!j(s))return!1}return!0},z=function(e){var t=g.readFileSync(e).toString();return JSON.parse(t)},q=function(e,t){var r=JSON.stringify(e);g.writeFileSync(t,r)},E=function(e,t){return w.AES.encrypt(e,t).toString()},T=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,a){if(this.account_passwords={},this.account_ciphertexts={},this.disable_address=!1,this.account_signatures="",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 s=0;s<t.length;s++){if(!this.checkPassword(t[s],r[s].trim()))throw new Error("account_passwords is not correct");this.account_passwords[t[s]]=r[s].trim()}}a&&(this.disable_address=a),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.getAccounts=function(e){var t=this.getAccountSignature();t!==this.account_signatures&&(this.account_signatures=t,this.reload());for(var r=Object.keys(this.account_ciphertexts),a=[],s=0;s<r.length;s++)this.getAccountChainType(r[s])===e&&a.push(r[s]);return a},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=m.join(this.setting_path,"accounts/".concat(e,".json"));if(!j(r))return!1;var a,s=z(r);a="PK"===s.account_type?k({salt:t},s.ciphertexts):{slat:t,data:s.pp_ciphertexts};var n=w.SHA256(JSON.stringify(a)).toString();return s.signature===n},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 T(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 s=E(t,r),n={address:this.getAccountAddressByPrivateKey(t,a),data:s},o=k({salt:r},n),i={signature:w.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}},e.prototype.generatePPAccount=function(e,t,r){if(this.checkAccountLabelIsExist(e))return{status:!1,output:"Account labels already exist"};var a=E(t,r),s={slat:r,data:a},n=w.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:E(o.output.pk,r)},solana:{address:i.output.address,data:E(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=m.join(this.setting_path,"accounts/".concat(e,".json")),a=z(r).pp_ciphertexts,s=T(a,this.account_passwords[e]),n=this.getSubAccount("evm",s,t);if(!1===n.status)return{status:!1,output:n.output};var o=this.getSubAccount("solana",s,t);return!1===o.status?{status:!1,output:o.output}:{status:!0,output:{evm:{address:n.output.address,data:E(n.output.pk,this.account_passwords[e])},solana:{address:o.output.address,data:E(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=m.join(this.setting_path,"accounts/".concat(e,".json")),a=z(r);if("PK"===a.account_type){var s=a.ciphertexts.data,n=T(s,this.account_passwords[e]);a.ciphertexts.data=E(n,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=T(a.pp_ciphertexts,this.account_passwords[e]);a.pp_ciphertexts=E(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 d=T(u[l].ciphertexts.evm.data,this.account_passwords[e]);u[l].ciphertexts.evm.data=E(d,t);var p=T(u[l].ciphertexts.solana.data,this.account_passwords[e]);u[l].ciphertexts.solana.data=E(p,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),this.checkAccountIsExist(e)?"unknown"===this.getAccountChainType(e)?{status:!1,output:"Chain type unknown"}:"evm"===this.getAccountChainType(e)?this.signEvmTransaction(t,r):this.signSolanaTransaction(e,r,t):{status:!1,output:"Account is not exist"}},e.prototype.sendSignedTransaction=function(e,t,r){return e=this.getAccountChecksumAddress(e),this.checkAccountIsExist(e)?"unknown"===this.getAccountChainType(e)?{status:!1,output:"Chain type unknown"}:"evm"===this.getAccountChainType(e)?this.sendEvmTransaction(t,r):this.sendSolanaTransaction(t,r):{status:!1,output:"Account is not exist"}},e.prototype.signMessage=function(e,t){return e=this.getAccountChecksumAddress(e),this.checkAccountIsExist(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)}:{status:!1,output:"Account is not exist"}},e.prototype.simulateTransaction=function(e,t,r){return x(this,void 0,void 0,(function(){var a,s,n;return _(this,(function(o){switch(o.label){case 0:return a=new i.Connection(t),s=this.showPrivateKey(e),n=i.Keypair.fromSecretKey(b.decode(s)),[4,A(a.simulateTransaction.bind(a),[r,[n]])];case 1:return[2,o.sent()]}}))}))},e.prototype.signEvmTransaction=function(e,t){return x(this,void 0,void 0,(function(){var r,a,s,n;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 s=this.showPrivateKey(r),n=new f.default(t),[4,A(n.eth.accounts.signTransaction.bind(n.eth.accounts),[e,s])];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,s,n,o,u;return _(this,(function(l){switch(l.label){case 0:return a=this.showPrivateKey(e),s=i.Keypair.fromSecretKey(b.decode(a)),n=new c.Wallet(s),"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=n.publicKey,[4,A(n.signTransaction.bind(n),[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.checkIsDisableAddress=function(e,t){if(!e||!this.disable_address)return!1;for(var r=e.length,a=0;a<r;a++){var s=e[a].from,n=e[a].to;if(t>=s&&t<=n)return!0}return!1},e.prototype.reload=function(){if(!P(this.setting_path,this.account_labels))throw new Error("Account labels not exist");for(var e={},t=this.account_labels.length,r=0;r<t;r++){var a=m.join(this.setting_path,"accounts/".concat(this.account_labels[r],".json")),s=JSON.parse(g.readFileSync(a,"utf8"));if("PK"!==s.account_type)for(var n=s.data.length,o=s.disabled_slots,i=0;i<n;i++)this.checkIsDisableAddress(o,i)||(e[s.data[i].ciphertexts.evm.address]={account_labels:this.account_labels[r],data:s.data[i].ciphertexts.evm.data},e[s.data[i].ciphertexts.solana.address]={account_labels:this.account_labels[r],data:s.data[i].ciphertexts.solana.data});else e[s.ciphertexts.address]={account_labels:this.account_labels[r],data:s.ciphertexts.data}}this.account_ciphertexts=e},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),s=d.HDKey.fromMasterSeed(a),n=i.Keypair.fromSeed(s.derive("m/44'/501'/".concat(r,"'/0'")).privateKey);return{status:!0,output:{address:n.publicKey.toBase58(),pk:b.encode(n.secretKey)}}}if("evm"===e){a=v.mnemonicToSeedSync(t);var o=(s=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.prototype.getAccountSignature=function(){for(var e=this.account_labels.length,t=[],r=0;r<e;r++){var a=m.join(this.setting_path,"accounts/".concat(this.account_labels[r],".json")),s=g.readFileSync(a,"utf8");t.push(s)}return w.MD5(JSON.stringify(t)).toString()},e}(),I=require("../package.json"),N=function(){function e(e,t,r,a){this.account=new O(e,t,r,a)}return e.version=I.version,e}();e.WativeCore=N,Object.defineProperty(e,"__esModule",{value:!0})}));
|
package/package.json
CHANGED
package/src/account.ts
CHANGED
|
@@ -544,13 +544,14 @@ export class Account {
|
|
|
544
544
|
throw new Error("Account labels not exist");
|
|
545
545
|
}
|
|
546
546
|
|
|
547
|
+
let new_account_ciphertexts = {};
|
|
547
548
|
let account_labels_size = this.account_labels.length;
|
|
548
549
|
for (let i = 0; i < account_labels_size; i++) {
|
|
549
550
|
let account_path = path.join(this.setting_path, `accounts/${this.account_labels[i]}.json`);
|
|
550
551
|
let account_data: any = JSON.parse(fs.readFileSync(account_path, 'utf8'));
|
|
551
552
|
|
|
552
553
|
if (account_data.account_type === "PK") {
|
|
553
|
-
|
|
554
|
+
new_account_ciphertexts[account_data.ciphertexts.address] = {
|
|
554
555
|
account_labels: this.account_labels[i],
|
|
555
556
|
data: account_data.ciphertexts.data
|
|
556
557
|
};
|
|
@@ -565,16 +566,18 @@ export class Account {
|
|
|
565
566
|
continue;
|
|
566
567
|
}
|
|
567
568
|
|
|
568
|
-
|
|
569
|
+
new_account_ciphertexts[account_data.data[j].ciphertexts.evm.address] = {
|
|
569
570
|
account_labels: this.account_labels[i],
|
|
570
571
|
data: account_data.data[j].ciphertexts.evm.data
|
|
571
572
|
};
|
|
572
|
-
|
|
573
|
+
new_account_ciphertexts[account_data.data[j].ciphertexts.solana.address] = {
|
|
573
574
|
account_labels: this.account_labels[i],
|
|
574
575
|
data: account_data.data[j].ciphertexts.solana.data
|
|
575
576
|
};
|
|
576
577
|
}
|
|
577
578
|
}
|
|
579
|
+
|
|
580
|
+
this.account_ciphertexts = new_account_ciphertexts;
|
|
578
581
|
}
|
|
579
582
|
|
|
580
583
|
private getAccountChecksumAddress(account_address: string) {
|