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