@guru_test/mpc-core-kit
Version:
MPC CoreKit SDK for web3Auth
2 lines • 628 kB
JavaScript
/*! For license information please see mpcCoreKit.umd.min.js.LICENSE.txt */
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.MpcCoreKit=t():e.MpcCoreKit=t()}(self,(()=>(()=>{var e={9090:(e,t)=>{var r;function i(e,t){navigator.onLine||e("offline"),e("error",t)}function n(e,t,r){navigator.serviceWorker.register(e,r).then((function(e){t("registered",e),e.waiting?t("updated",e):e.onupdatefound=function(){t("updatefound",e);var r=e.installing;r.onstatechange=function(){"installed"===r.state&&(navigator.serviceWorker.controller?t("updated",e):t("cached",e))}}})).catch((function(e){return i(t,e)}))}"undefined"!=typeof window&&(r="undefined"==typeof document||"interactive"!==document.readyState&&"complete"!==document.readyState?"undefined"!=typeof Promise?new Promise((function(e){return window.addEventListener("load",e)})):{then:function(e){return window.addEventListener("load",e)}}:Promise.resolve()),t.k=function(e,t){void 0===t&&(t={});var s=t.registrationOptions;void 0===s&&(s={}),delete t.registrationOptions;var o=function(e){for(var r=[],i=arguments.length-1;i-- >0;)r[i]=arguments[i+1];t&&t[e]&&t[e].apply(t,r)};"serviceWorker"in navigator&&r.then((function(){Boolean("localhost"===window.location.hostname||"[::1]"===window.location.hostname||window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/))?(function(e,t,r){fetch(e).then((function(i){404===i.status?(t("error",new Error("Service worker not found at "+e)),unregister()):-1===i.headers.get("content-type").indexOf("javascript")?(t("error",new Error("Expected "+e+" to have javascript content-type, but received "+i.headers.get("content-type"))),unregister()):n(e,t,r)})).catch((function(e){return i(t,e)}))}(e,o,s),navigator.serviceWorker.ready.then((function(e){o("ready",e)})).catch((function(e){return i(o,e)}))):(n(e,o,s),navigator.serviceWorker.ready.then((function(e){o("ready",e)})).catch((function(e){return i(o,e)})))}))}},7953:(e,t,r)=>{"use strict";r.d(t,{Sg:()=>h,X3:()=>f,at:()=>u,t0:()=>d});var i=r(9024),n=r(9404),s=r.n(n),o=r(7741),a=r(2606),c=r(8287).hp;const h=e=>o.bI.keyFromPrivate(e.toString("hex",64)),d=e=>{const t=new(s())(e,"hex");return c.from(t.toString("hex",64),"hex")},u=e=>(0,i.qb)(d(e)),f=e=>{const t=(e=>o.bI.keyFromPrivate(e.toString("hex",64)).getPublic())(e);return new a.A(t.getX().toString("hex"),t.getY().toString("hex"))}},3126:(e,t,r)=>{"use strict";r.d(t,{O:()=>a});var i=r(4705);var n,s=(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=function(e){function t(t,r){var i,n,s,o=this.constructor,a=e.call(this,t,r)||this;return Object.defineProperty(a,"name",{value:o.name,enumerable:!1,configurable:!0}),i=a,n=o.prototype,(s=Object.setPrototypeOf)?s(i,n):i.__proto__=n,function(e,t){void 0===t&&(t=e.constructor);var r=Error.captureStackTrace;r&&r(e,t)}(a),a}return s(t,e),t}(Error);class a extends o{constructor(e,t){super(t),(0,i.A)(this,"code",void 0),(0,i.A)(this,"message",void 0),this.code=e,this.message=t||"",Object.defineProperty(this,"name",{value:"TkeyError"})}toJSON(){return{name:this.name,code:this.code,message:this.message}}toString(){return JSON.stringify(this.toJSON())}}},3701:(e,t,r)=>{"use strict";r.d(t,{b:()=>n,j:()=>i});const i="__ONE_KEY_DELETE_NONCE__",n="noncev2"},2606:(e,t,r)=>{"use strict";r.d(t,{A:()=>h});var i=r(4705),n=r(9404),s=r.n(n),o=r(7741),a=r(8287).hp;class c{constructor(e,t){(0,i.A)(this,"x",void 0),(0,i.A)(this,"y",void 0),this.x=new(s())(e,"hex"),this.y=new(s())(t,"hex")}static fromScalar(e,t){const r=t.g.mul(e);return c.fromElliptic(r)}static fromCompressedPub(e){const t=o.bI.keyFromPublic(e,"hex").getPublic();return new c(t.getX(),t.getY())}static fromJSON(e){const{x:t,y:r}=e;return new c(t,r)}static fromElliptic(e){return e.isInfinity()?new c(null,null):new c(e.getX(),e.getY())}static fromSEC1(e,t){if(2===t.length&&"00"===t){const t=e.g.mul(new(s())(0));return c.fromElliptic(t)}const r=e.keyFromPublic(t,"hex").getPublic();return c.fromElliptic(r)}encode(e){switch(e){case"arr":return a.concat([a.from("0x04","hex"),a.from(this.x.toString("hex"),"hex"),a.from(this.y.toString("hex"),"hex")]);case"elliptic-compressed":{const e=o.bI.keyFromPublic({x:this.x.toString("hex"),y:this.y.toString("hex")},"hex");return a.from(e.getPublic(!0,"hex"))}default:throw new Error("encoding doesnt exist in Point")}}toEllipticPoint(e){return this.isIdentity()?e.g.mul(new(s())(0)):e.keyFromPublic({x:this.x.toString("hex"),y:this.y.toString("hex")},"hex").getPublic()}toSEC1(e,t=!1){if(this.isIdentity())return a.from("00","hex");const r=this.toEllipticPoint(e);return a.from(r.encode("hex",t),"hex")}toJSON(){return{x:this.x.toString("hex"),y:this.y.toString("hex")}}isIdentity(){return null===this.x&&null===this.y}equals(e){return this.isIdentity()?e.isIdentity():this.x.eq(e.x)&&this.y.eq(e.y)}}var h=c},2117:(e,t,r)=>{"use strict";r.d(t,{A:()=>o});var i=r(4705),n=r(2606);class s{constructor(e){(0,i.A)(this,"polynomialCommitments",void 0),(0,i.A)(this,"polynomialId",void 0),this.polynomialCommitments=e}static fromJSON(e){const t=e.polynomialCommitments.map((e=>n.A.fromJSON(e)));return new s(t)}getThreshold(){return this.polynomialCommitments.length}getPolynomialID(){let e="";for(let t=0;t<this.polynomialCommitments.length;t+=1){let r=this.polynomialCommitments[t].encode("elliptic-compressed").toString();0!==t&&(r=`|${r}`),e+=r}return this.polynomialId=e,this.polynomialId}toJSON(){return{polynomialCommitments:this.polynomialCommitments}}}var o=s},8324:(e,t,r)=>{"use strict";r.d(t,{A:()=>c});var i=r(4705),n=r(9404),s=r.n(n),o=r(2606);class a{constructor(e,t){(0,i.A)(this,"shareCommitment",void 0),(0,i.A)(this,"shareIndex",void 0),this.shareCommitment=new o.A(t.x,t.y),this.shareIndex=new(s())(e,"hex")}static fromJSON(e){const{shareCommitment:t,shareIndex:r}=e;return new a(r,o.A.fromJSON(t))}toJSON(){return{shareCommitment:this.shareCommitment,shareIndex:this.shareIndex.toString("hex")}}}var c=a},3435:(e,t,r)=>{"use strict";r.d(t,{A:()=>h});var i=r(4705),n=r(9404),s=r.n(n),o=r(7953),a=r(8324);class c{constructor(e,t){(0,i.A)(this,"share",void 0),(0,i.A)(this,"shareIndex",void 0),this.share=new(s())(t,"hex"),this.shareIndex=new(s())(e,"hex")}static fromJSON(e){const{share:t,shareIndex:r}=e;return new c(r,t)}getPublicShare(){return new a.A(this.shareIndex,(0,o.X3)(this.share))}toJSON(){return{share:this.share.toString("hex"),shareIndex:this.shareIndex.toString("hex")}}}var h=c},6582:(e,t,r)=>{"use strict";r.d(t,{A:()=>o});var i=r(4705),n=r(3435);class s{constructor(e,t){(0,i.A)(this,"share",void 0),(0,i.A)(this,"polynomialID",void 0),this.share=e,this.polynomialID=t}static fromJSON(e){const{share:t,polynomialID:r}=e;return new s(n.A.fromJSON(t),r)}toJSON(){return{share:this.share,polynomialID:this.polynomialID.toString()}}}var o=s},5923:(e,t,r)=>{"use strict";r.d(t,{_:()=>i});let i=function(e){return e.secp256k1="secp256k1",e.ed25519="ed25519",e}({})},7741:(e,t,r)=>{"use strict";r.d(t,{Ag:()=>m,Jk:()=>y,MQ:()=>l,WD:()=>g,Yc:()=>u,bI:()=>h,mh:()=>p,w:()=>d});var i=r(8784),n=r(9024),s=r(9404),o=r.n(s),a=r(6729),c=r(8287).hp;const h=new a.ec("secp256k1");async function d(e,t){const r=await(0,n.w)(e,t);return{ciphertext:r.ciphertext.toString("hex"),ephemPublicKey:r.ephemPublicKey.toString("hex"),iv:r.iv.toString("hex"),mac:r.mac.toString("hex")}}async function u(e,t){const r={ciphertext:c.from(t.ciphertext,"hex"),ephemPublicKey:c.from(t.ephemPublicKey,"hex"),iv:c.from(t.iv,"hex"),mac:c.from(t.mac,"hex")};return(0,n.Yc)(e,r)}const f=e=>e&&e.stack&&""!==e.message;async function l(e){return f(e)?e:(0,i.P)(e)}function p(e){const t=new(o())((0,n.F_)());return e.find((e=>e.eq(t)))?p(e):t}const y="KEY_NOT_FOUND",g="SHARE_DELETED";function m(e){return"0x"===e.slice(0,2)?e.slice(2):e}},6679:(e,t,r)=>{"use strict";r.d(t,{A:()=>o});var i=r(4705),n=r(3126);class s extends n.O{constructor(e,t){super(e,t),Object.defineProperty(this,"name",{value:"CoreError"})}static fromCode(e,t=""){return new s(e,`${s.messages[e]} ${t}`)}static default(e=""){return new s(1e3,`${s.messages[1e3]} ${e}`)}static metadataUndefined(e=""){return s.fromCode(1101,e)}static delete1OutOf1OnlyManualSync(e=""){return s.fromCode(1601,e)}static metadataGetFailed(e=""){return s.fromCode(1102,e)}static metadataPostFailed(e=""){return s.fromCode(1103,e)}static tkeyStoreInvalid(e=""){return s.fromCode(1201,e)}static tkeyEncryptionFailed(e=""){return s.fromCode(1202,e)}static tkeyDecryptionFailed(e=""){return s.fromCode(1203,e)}static privateKeyUnavailable(e=""){return s.fromCode(1301,e)}static unableToReconstruct(e=""){return s.fromCode(1302,e)}static incorrectReconstruction(e=""){return s.fromCode(1303,e)}static encryptedShareStoreUnavailable(e=""){return s.fromCode(1306,e)}static acquireLockFailed(e=""){return s.fromCode(1401,e)}static releaseLockFailed(e=""){return s.fromCode(1402,e)}static privKeyUnavailable(e=""){return s.fromCode(1501,e)}static metadataPubKeyUnavailable(e=""){return s.fromCode(1502,e)}static authMetadataGetUnavailable(e=""){return s.fromCode(1503,e)}static authMetadataSetUnavailable(e=""){return s.fromCode(1504,e)}}(0,i.A)(s,"messages",{1e3:"Custom",1001:"Unable to delete service provider share",1002:"Wrong share index",1003:"Unable to updateSDK",1101:"metadata not found, SDK likely not initialized",1102:"getMetadata errored",1103:"setMetadata errored",1104:"previouslyFetchedCloudMetadata provided in initialization is outdated",1105:"previouslyFetchedCloudMetadata.nonce should never be higher than the latestShareDetails, please contact support",1201:"Invalid tkeyStore",1202:"Encryption failed",1203:"Decryption failed",1301:"Private key not available. Please reconstruct key first",1302:"Unable to reconstruct",1303:"reconstructed key is not pub key",1304:"Share found in unexpected polynomial",1305:"Input is not supported",1306:"no encrypted share store for share exists",1307:"Share doesn't exist",1308:"Share was deleted",1401:"Unable to acquire lock",1402:"Unable to release lock",1501:"privkey unavailable",1502:"metadata pubkey unavailable",1503:"getAuthMetadata errored",1504:"setAuthMetadata errored",1601:"delete1OutOf1 requires manualSync=true"});var o=s},7086:(e,t,r)=>{"use strict";r.d(t,{XD:()=>p,xh:()=>w,ZS:()=>b,Yi:()=>v,iu:()=>S});var i=r(7741),n=r(4705),s=r(9404),o=r.n(s),a=r(7953),c=r(2117),h=r(3435);class d{constructor(e){(0,n.A)(this,"polynomial",void 0),(0,n.A)(this,"publicPolynomial",void 0),this.polynomial=e}static fromJSON(e){const{polynomial:t}=e;return new d(t.map((e=>new(o())(e,"hex"))))}getThreshold(){return this.polynomial.length}polyEval(e){const t=new(o())(e,"hex");let r=new(o())(t),n=new(o())(0);n=n.add(this.polynomial[0]);for(let e=1;e<this.polynomial.length;e+=1){const s=r.mul(this.polynomial[e]);n=n.add(s),n=n.umod(i.bI.curve.n),r=r.mul(new(o())(t)),r=r.umod(i.bI.curve.n)}return n}generateShares(e){const t=e.map((e=>"number"==typeof e?new(o())(e):e instanceof o()?e:"string"==typeof e?new(o())(e,"hex"):e)),r={};for(let e=0;e<t.length;e+=1)r[t[e].toString("hex")]=new h.A(t[e],this.polyEval(t[e]));return r}getPublicPolynomial(){const e=[];for(let t=0;t<this.polynomial.length;t+=1)e.push((0,a.X3)(this.polynomial[t]));return this.publicPolynomial=new c.A(e),this.publicPolynomial}getPolynomialID(){return this.publicPolynomial.polynomialId}toJSON(){return{polynomial:this.polynomial.map((e=>e.toString("hex")))}}}var u=d,f=r(2606),l=r(6679);function p(){return i.bI.genKeyPair().getPrivate()}const y=e=>Array.from({length:e},(()=>new(o())(0))),g=(e,t)=>{let r=y(t.length);const n=((e,t)=>{let r=new(o())(1);const n=t[e].x;for(let s=t.length-1;s>=0;s-=1)if(e!==s){let e=new(o())(n);e=e.sub(t[s].x),e=e.umod(i.bI.curve.n),r=r.mul(e),r=r.umod(i.bI.curve.n)}return r})(e,t);if(0===n.cmp(new(o())(0)))throw l.A.default("Denominator for interpolationPoly is 0");r[0]=n.invm(i.bI.curve.n);for(let n=0;n<t.length;n+=1){const s=y(t.length);if(n!==e){let a;for(a=n<e?n+1:n,a-=1;a>=0;a-=1){s[a+1]=s[a+1].add(r[a]),s[a+1]=s[a+1].umod(i.bI.curve.n);let e=new(o())(t[n].x);e=e.mul(r[a]),e=e.umod(i.bI.curve.n),s[a]=s[a].sub(e),s[a]=s[a].umod(i.bI.curve.n)}r=s}}return r},m=e=>{const t=(e=>{const t=[...e];return t.sort(((e,t)=>e.x.cmp(t.x))),t})(e),r=y(t.length);for(let e=0;e<t.length;e+=1){const n=g(e,t);for(let s=0;s<t.length;s+=1){let a=new(o())(t[e].y);a=a.mul(n[s]),r[s]=r[s].add(a),r[s]=r[s].umod(i.bI.curve.n)}}return new u(r)};function b(e){return m(e)}function v(e,t){if(e.length!==t.length)throw l.A.default("shares not equal to nodeIndex length in lagrangeInterpolation");let r=new(o())(0);for(let n=0;n<e.length;n+=1){let s=new(o())(1),a=new(o())(1);for(let r=0;r<e.length;r+=1)if(n!==r){s=s.mul(t[r].neg()),s=s.umod(i.bI.curve.n);let e=t[n].sub(t[r]);e=e.umod(i.bI.curve.n),a=a.mul(e).umod(i.bI.curve.n)}let c=s.mul(a.invm(i.bI.curve.n)).umod(i.bI.curve.n);c=c.mul(e[n]).umod(i.bI.curve.n),r=r.add(c)}return r.umod(i.bI.curve.n)}function w(e,t,r){let n=t;if(t||(n=(0,i.mh)([new(o())(0)])),!r){const t=[n];for(let r=0;r<e;r+=1){const e=(0,i.mh)(t);t.push(e)}return new u(t)}if(!Array.isArray(r))throw l.A.default("deterministic shares in generateRandomPolynomial should be an array");if(r.length>e)throw l.A.default("deterministicShares in generateRandomPolynomial should be less or equal than degree to ensure an element of randomness");const s={};r.forEach((e=>{s[e.shareIndex.toString("hex")]=new f.A(e.shareIndex,e.share)}));for(let t=0;t<e-r.length;t+=1){let e=(0,i.mh)([new(o())(0)]);for(;void 0!==s[e.toString("hex")];)e=(0,i.mh)([new(o())(0)]);s[e.toString("hex")]=new f.A(e,p())}return s[0]=new f.A(new(o())(0),n),b(Object.values(s))}function S(e,t){const r=[];for(let t=0;t<e.length;t+=1){const n=i.bI.keyFromPublic({x:e[t].x.toString("hex"),y:e[t].y.toString("hex")},"");r.push(n.getPublic())}let n=r[0];for(let e=1;e<r.length;e+=1){const s=t.pow(new(o())(e)).umod(i.bI.n),a=r[e].mul(s);n=n.add(a)}return new f.A(n.getX(),n.getY())}},7395:(e,t,r)=>{"use strict";r.d(t,{A:()=>x});var i=r(4705),n=r(9404),s=r.n(n);const o=["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"];var a=r(3126);class c extends a.O{constructor(e,t){super(e,t),Object.defineProperty(this,"name",{value:"ShareSerializationError"})}static fromCode(e,t=""){return new c(e,`${c.messages[e]}${t}`)}static default(e=""){return new c(7e3,`${c.messages[7e3]}${e}`)}static typeNotSupported(e=""){return c.fromCode(7010,e)}static invalidEntropy(e=""){return c.fromCode(7011,e)}static invalidChecksum(e=""){return c.fromCode(7012,e)}static invalidMnemonic(e=""){return c.fromCode(7013,e)}}(0,i.A)(c,"messages",{7e3:"Custom",7010:"Type is not supported",7011:"Invalid Entropy",7012:"Invalid Checksum",7013:"Invalid mnemonic"});var h=c,d=r(6013),u=r(2531);const f=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),l=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),p=new Uint32Array(64);class y extends d.ol{constructor(){super(64,32,8,!1),this.A=0|l[0],this.B=0|l[1],this.C=0|l[2],this.D=0|l[3],this.E=0|l[4],this.F=0|l[5],this.G=0|l[6],this.H=0|l[7]}get(){const{A:e,B:t,C:r,D:i,E:n,F:s,G:o,H:a}=this;return[e,t,r,i,n,s,o,a]}set(e,t,r,i,n,s,o,a){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|i,this.E=0|n,this.F=0|s,this.G=0|o,this.H=0|a}process(e,t){for(let r=0;r<16;r++,t+=4)p[r]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=p[e-15],r=p[e-2],i=(0,u.Ow)(t,7)^(0,u.Ow)(t,18)^t>>>3,n=(0,u.Ow)(r,17)^(0,u.Ow)(r,19)^r>>>10;p[e]=n+p[e-7]+i+p[e-16]|0}let{A:r,B:i,C:n,D:s,E:o,F:a,G:c,H:h}=this;for(let e=0;e<64;e++){const t=h+((0,u.Ow)(o,6)^(0,u.Ow)(o,11)^(0,u.Ow)(o,25))+(0,d.r9)(o,a,c)+f[e]+p[e]|0,l=((0,u.Ow)(r,2)^(0,u.Ow)(r,13)^(0,u.Ow)(r,22))+(0,d.TQ)(r,i,n)|0;h=c,c=a,a=o,o=s+t|0,s=n,n=i,i=r,r=t+l|0}r=r+this.A|0,i=i+this.B|0,n=n+this.C|0,s=s+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,h=h+this.H|0,this.set(r,i,n,s,o,a,c,h)}roundClean(){p.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const g=(0,u.ld)((()=>new y)),m=(0,r(651).RS)(g);var b=r(8287).hp;function v(e){return parseInt(e,2)}function w(e,t,r){let i=e;for(;i.length<r;)i=t+i;return i}function S(e){return e.map((e=>w(e.toString(2),"0",8))).join("")}function _(e){const t=8*e.length/32,r=m(e);return S(Array.from(r)).slice(0,t)}class k{constructor(){(0,i.A)(this,"moduleName",void 0),(0,i.A)(this,"tbSDK",void 0),this.moduleName="shareSerialization"}static serializeMnemonic(e){return function(e,t){let r;if(b.isBuffer(e)||(r=b.from(e,"hex")),r.length<16)throw h.invalidEntropy();if(r.length>32)throw h.invalidEntropy();if(r.length%4!=0)throw h.invalidEntropy();const i=(S(Array.from(r))+_(r)).match(/(.{1,11})/g).map((e=>{const r=v(e);return t[r]}));return"あいこくしん"===t[0]?i.join(" "):i.join(" ")}(e.toString("hex").padStart(64,"0"),o)}static deserializeMnemonic(e){return new(s())(function(e,t){const r=(i=e,(i||"").normalize("NFKD")).split(" ");var i;if(r.length%3!=0)throw h.invalidMnemonic();const n=r.map((e=>{const r=t.indexOf(e);if(-1===r)throw h.invalidMnemonic();return w(r.toString(2),"0",11)})).join(""),s=32*Math.floor(n.length/33),o=n.slice(0,s),a=n.slice(s),c=o.match(/(.{1,8})/g).map(v);if(c.length<16)throw h.invalidEntropy();if(c.length>32)throw h.invalidEntropy();if(c.length%4!=0)throw h.invalidEntropy();const d=b.from(c);if(_(d)!==a)throw h.invalidChecksum();return d.toString("hex")}(e,o),"hex")}setModuleReferences(e){this.tbSDK=e,this.tbSDK._addShareSerializationMiddleware(this.serialize.bind(this),this.deserialize.bind(this))}async initialize(){}async serialize(e,t){if("mnemonic"===t)return k.serializeMnemonic(e);throw h.typeNotSupported()}async deserialize(e,t){if("mnemonic"===t)return k.deserializeMnemonic(e);throw h.typeNotSupported()}}var x=k},1797:(e,t,r)=>{"use strict";r.d(t,{sj:()=>ue,SK:()=>he});var i=r(9379),n=r(4705),s=r(7741),o=r(2606),a=r(5923),c=r(6582),h=r(3435),d=r(7953),u=r(3701),f=r(9895),l=r(9404),p=r.n(l),y=r(6729),g=r(9463),m=r(1357),b=r(5473),v=r.n(b),w=r(3065),S=r.n(w),_=r(8287).hp;function k(e){return`0x${_.from((0,g.So)(e)).toString("hex")}`}var x=r(8287).hp;var A=r(9699),P=r(6679),E=r(2117),I=r(8324),M=r(7086);class T{constructor(e){(0,n.A)(this,"pubKey",void 0),(0,n.A)(this,"publicPolynomials",void 0),(0,n.A)(this,"publicShares",void 0),(0,n.A)(this,"polyIDList",void 0),(0,n.A)(this,"generalStore",void 0),(0,n.A)(this,"tkeyStore",void 0),(0,n.A)(this,"scopedStore",void 0),(0,n.A)(this,"nonce",void 0),(0,n.A)(this,"tssKeyTypes",void 0),(0,n.A)(this,"tssNonces",void 0),(0,n.A)(this,"tssPolyCommits",void 0),(0,n.A)(this,"factorPubs",void 0),(0,n.A)(this,"factorEncs",void 0),this.publicPolynomials={},this.publicShares={},this.generalStore={},this.tkeyStore={},this.scopedStore={},this.pubKey=e,this.polyIDList=[],this.nonce=0,this.tssKeyTypes={},this.tssPolyCommits={},this.tssNonces={},this.factorPubs={},this.factorEncs={}}static fromJSON(e){const{pubKey:t,polyIDList:r,generalStore:i,tkeyStore:n,scopedStore:a,nonce:c,tssKeyTypes:h,tssPolyCommits:d,tssNonces:u,factorPubs:f,factorEncs:l}=e,p=o.A.fromSEC1(s.bI,t),y=new T(p),g=[];if(i&&(y.generalStore=i),n&&(y.tkeyStore=n),a&&(y.scopedStore=a),c&&(y.nonce=c),h){y.tssKeyTypes={};for(const e in h)y.tssKeyTypes[e]=h[e]}if(d){y.tssPolyCommits={};for(const e in d)y.tssPolyCommits[e]=d[e].map((e=>new o.A(e.x,e.y)))}if(u){y.tssNonces={};for(const e in u)y.tssNonces[e]=u[e]}if(f){y.factorPubs={};for(const e in f)y.factorPubs[e]=f[e].map((e=>new o.A(e.x,e.y)))}l&&(y.factorEncs=l);for(let e=0;e<r.length;e+=1){const t=r[e].split("|"),i=t.findIndex((e=>"0x0"===e)),n=t.slice(0,i),s=t.slice(i+1,t.length),a=n.join("|"),c=[];n.forEach((e=>{c.push(o.A.fromCompressedPub(e))}));const h=new E.A(c);y.publicPolynomials[a]=h,g.push([a,s])}return y.polyIDList=g,y}getShareIndexesForPolynomial(e){const t=this.polyIDList.filter((t=>t[0]===e));if(t.length<1)throw P.A.default("there is no matching polyID");if(t.length>1)throw P.A.default("there is more than one matching polyID");return t[0][1]}getLatestPublicPolynomial(){return this.publicPolynomials[this.polyIDList[this.polyIDList.length-1][0]]}addPublicShare(e,t){e in this.publicShares||(this.publicShares[e]={}),this.publicShares[e][t.shareIndex.toString("hex")]=t}setGeneralStoreDomain(e,t){this.generalStore[e]=t}getGeneralStoreDomain(e){return this.generalStore[e]}deleteGeneralStoreDomain(e){delete this.generalStore[e]}setTkeyStoreDomain(e,t){this.tkeyStore[e]=t}getTkeyStoreDomain(e){return this.tkeyStore[e]}addFromPolynomialAndShares(e,t){const r=e.getPublicPolynomial(),i=r.getPolynomialID();this.publicPolynomials[i]=r;const n=[];if(Array.isArray(t))for(let e=0;e<t.length;e+=1)this.addPublicShare(r.getPolynomialID(),t[e].getPublicShare()),n.push(t[e].shareIndex.toString("hex"));else for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&(this.addPublicShare(r.getPolynomialID(),t[e].getPublicShare()),n.push(t[e].shareIndex.toString("hex")));this.polyIDList.push([i,n])}setScopedStore(e,t){this.scopedStore[e]=t}async getEncryptedShare(e){const t=e.share.getPublicShare(),r=this.scopedStore.encryptedShares;if(!r)throw P.A.encryptedShareStoreUnavailable(`${e}`);const i=r[t.shareCommitment.x.toString("hex")];if(!i)throw P.A.encryptedShareStoreUnavailable(`${e}`);const n=await(0,s.Yc)((0,d.t0)(e.share.share),i);return c.A.fromJSON(JSON.parse(n.toString()))}getShareDescription(){return this.getGeneralStoreDomain("shareDescriptions")}addShareDescription(e,t){const r=this.getGeneralStoreDomain("shareDescriptions")||{};r[e]?r[e].push(t):r[e]=[t],this.setGeneralStoreDomain("shareDescriptions",r)}deleteShareDescription(e,t){const r=this.getGeneralStoreDomain("shareDescriptions"),i=r[e].indexOf(t);if(!(i>-1))throw P.A.default(`No share description found for the given shareIndex: ${e} \n and description: ${t}`);r[e].splice(i,1)}updateShareDescription(e,t,r){const i=this.getGeneralStoreDomain("shareDescriptions"),n=i[e].indexOf(t);if(!(n>-1))throw P.A.default(`No share description found for the given shareIndex:\n ${e} and description: ${t}`);i[e][n]=r}shareToShareStore(e){const t=(0,d.X3)(e);for(let r=this.polyIDList.length-1;r>=0;r-=1){const i=this.polyIDList[r][0];for(let n=0;n<this.polyIDList[r][1].length;n+=1){const s=this.polyIDList[r][1][n];let o;if(this.publicShares[i]&&this.publicShares[i][s]&&(o=this.publicShares[i][s]),o||(o=new I.A(s,(0,M.iu)(this.publicPolynomials[i].polynomialCommitments,new(p())(s,"hex")))),o.shareCommitment.x.eq(t.x)&&o.shareCommitment.y.eq(t.y)){const t=new h.A(o.shareIndex,e);return new c.A(t,i)}}}throw P.A.fromCode(1307)}clone(){return T.fromJSON(JSON.parse(v()(this)))}toJSON(){const e=[];for(let t=0;t<this.polyIDList.length;t+=1){const r=this.polyIDList[t][0],i=this.polyIDList[t][1].sort(((e,t)=>new(p())(e,"hex").cmp(new(p())(t,"hex")))),n=r.split("|").concat("0x0").concat(...i).join("|");e.push(n)}return(0,i.A)((0,i.A)((0,i.A)((0,i.A)((0,i.A)({pubKey:this.pubKey.toSEC1(s.bI,!0).toString("hex"),polyIDList:e,scopedStore:this.scopedStore,generalStore:this.generalStore,tkeyStore:this.tkeyStore,nonce:this.nonce},this.tssKeyTypes&&{tssKeyTypes:this.tssKeyTypes}),this.tssNonces&&{tssNonces:this.tssNonces}),this.tssPolyCommits&&{tssPolyCommits:this.tssPolyCommits}),this.factorPubs&&{factorPubs:this.factorPubs}),this.factorEncs&&{factorEncs:this.factorEncs})}updateTSSData(e){const{tssKeyType:t,tssTag:r,tssNonce:i,tssPolyCommits:n,factorPubs:s,factorEncs:o}=e;t&&(this.tssKeyTypes[r]=t),void 0!==i&&(this.tssNonces[r]=i),n&&(this.tssPolyCommits[r]=n),s&&(this.factorPubs[r]=s),o&&(this.factorEncs[r]=o)}}var O=T,N=r(8287).hp;class K{constructor(e,t){(0,n.A)(this,"metadata",void 0),(0,n.A)(this,"privKey",void 0),this.metadata=e,this.privKey=t}static fromJSON(e){const{data:t,sig:r}=e;if(!t)throw P.A.metadataUndefined();const i=O.fromJSON(t);if(!i.pubKey)throw P.A.metadataPubKeyUnavailable();if(!s.bI.keyFromPublic(i.pubKey.toSEC1(s.bI)).verify((0,s.Ag)(k(N.from(v()(t),"utf8"))),r))throw P.A.default("Signature not valid for returning metadata");return new K(i)}toJSON(){const e=this.metadata;if(!this.privKey)throw P.A.privKeyUnavailable();return{data:e,sig:(0,d.Sg)(this.privKey).sign((0,s.Ag)(k(N.from(v()(e),"utf8")))).toDER("hex")}}}var C=K,L=r(8287).hp;const R="ed25519Seed";class D{constructor(e){(0,n.A)(this,"modules",void 0),(0,n.A)(this,"enableLogging",void 0),(0,n.A)(this,"serviceProvider",void 0),(0,n.A)(this,"storageLayer",void 0),(0,n.A)(this,"shares",void 0),(0,n.A)(this,"lastFetchedCloudMetadata",void 0),(0,n.A)(this,"metadata",void 0),(0,n.A)(this,"manualSync",void 0),(0,n.A)(this,"_localMetadataTransitions",void 0),(0,n.A)(this,"_refreshMiddleware",void 0),(0,n.A)(this,"_reconstructKeyMiddleware",void 0),(0,n.A)(this,"_shareSerializationMiddleware",void 0),(0,n.A)(this,"storeDeviceShare",void 0),(0,n.A)(this,"haveWriteMetadataLock",void 0),(0,n.A)(this,"serverTimeOffset",0),(0,n.A)(this,"privKey",void 0),(0,n.A)(this,"_ed25519Seed",void 0);const{enableLogging:t=!1,modules:r={},serviceProvider:i,storageLayer:s,manualSync:o=!1,serverTimeOffset:a}=e||{};this.enableLogging=t,this.serviceProvider=i,this.storageLayer=s,this.modules=r,this.shares={},this.privKey=void 0,this.manualSync=o,this._refreshMiddleware={},this._reconstructKeyMiddleware={},this._shareSerializationMiddleware=void 0,this.storeDeviceShare=void 0,this._localMetadataTransitions=[[],[]],this.setModuleReferences(),this.haveWriteMetadataLock="",this.serverTimeOffset=a}get secp256k1Key(){return void 0!==this.privKey?this.privKey:null}get ed25519Key(){return void 0!==this._ed25519Seed?this._ed25519Seed:null}set secp256k1Key(e){this.privKey=e}set ed25519Key(e){this._ed25519Seed=e}static async fromJSON(e,t){const{enableLogging:r,privKey:i,metadata:n,shares:s,_localMetadataTransitions:a,manualSync:d,lastFetchedCloudMetadata:u,serverTimeOffset:f}=e,{storageLayer:l,serviceProvider:y,modules:g}=t,m=new D({enableLogging:r,storageLayer:l,serviceProvider:y,modules:g,manualSync:d,serverTimeOffset:f});i&&(m.privKey=new(p())(i,"hex"));for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)){const t=s[e];for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)){const r=t[e];t[e]=c.A.fromJSON(r)}}m.shares=s;const b=Object.keys(JSON.parse(v()(new C(new O(new o.A("0","0")),new(p())("0","hex"))))),w=Object.keys(JSON.parse(v()(new c.A(new h.A("0","0"),"")))),S={message:"Sample message",dateAdded:Date.now()},_=Object.keys(S),k=[],x=[];if(a[0].forEach(((e,t)=>{e?k.push(new(p())(e,"hex")):k.push(void 0);const r=Object.keys(a[1][t]);if(r.length===b.length&&r.every((e=>b.includes(e)))){const e=C.fromJSON(a[1][t]);e.privKey=i,x.push(e)}else if(r.length===w.length&&r.every((e=>w.includes(e))))x.push(c.A.fromJSON(a[1][t]));else{if(r.length!==_.length||!r.every((e=>_.includes(e))))throw P.A.default("fromJSON failed. Could not deserialise _localMetadataTransitions");x.push(a[1][t])}})),n||u){let e,t,r;if("0"===m.serviceProvider.postboxKey.toString("hex")){const e=O.fromJSON(u).getLatestPublicPolynomial().getPolynomialID(),t=Object.keys(s[e]),i=t[Math.floor(Math.random()*(t.length-1))];t.length>=1&&(r=s[e][i])}n&&(e=O.fromJSON(n)),u&&(t=O.fromJSON(u)),await m.initialize({neverInitializeNewKey:!0,transitionMetadata:e,previouslyFetchedCloudMetadata:t,previousLocalMetadataTransitions:[k,x],withShare:r})}else await m.initialize({neverInitializeNewKey:!0});return m}getStorageLayer(){return this.storageLayer}getMetadata(){if(void 0!==this.metadata)return this.metadata;throw P.A.metadataUndefined()}async initialize(e){const t=e||{};if(t.delete1OutOf1&&!this.manualSync)throw P.A.delete1OutOf1OnlyManualSync();const{withShare:r,importKey:i,importEd25519Seed:n,neverInitializeNewKey:o,transitionMetadata:a,previouslyFetchedCloudMetadata:h,previousLocalMetadataTransitions:d}=t,u=d&&d[0].length>0&&d[1].length>0,f=a&&u,l=f&&void 0===h;let p,y,g,m;if(r instanceof c.A)p=r;else if("object"==typeof r)p=c.A.fromJSON(r);else{if(r)throw P.A.default("Input is not supported");{const e=l,r=l?d:void 0,a=await this.getGenericMetadataWithTransitionStates({serviceProvider:this.serviceProvider,includeLocalMetadataTransitions:e,_localMetadataTransitions:r,fromJSONConstructor:{fromJSON:e=>e}});if(a.message===s.Jk){if(o)throw P.A.default("key has not been generated yet");if(!this.serviceProvider.migratableKey||i||n)await this._initializeNewKey({initializeModules:!0,importedKey:i,delete1OutOf1:t.delete1OutOf1,importEd25519Seed:n});else{const e=this.manualSync;this.manualSync=!0,await this._initializeNewKey({initializeModules:!0,importedKey:this.serviceProvider.migratableKey,delete1OutOf1:!0}),e||await this.syncLocalMetadataTransitions(),this.manualSync=e}return this.getKeyDetails()}p=c.A.fromJSON(a)}}try{m=await this.catchupToLatestShare({shareStore:p})}catch(e){const t=e;if(1503!==t.code||!f)throw t}if(f&&!l){if(h.nonce<m.shareMetadata.nonce)throw P.A.fromCode(1104);if(h.nonce>m.shareMetadata.nonce)throw P.A.fromCode(1105);g=h}else g=m?m.shareMetadata.clone():void 0;f?(y=a,this._localMetadataTransitions=d):y=m.shareMetadata,this.lastFetchedCloudMetadata=g,this.metadata=y;const b=m?m.latestShare:p;if(this.inputShareStore(b),n&&this.getEd25519PublicKey())throw P.A.default("Ed25119 key already exists");return await this.initializeModules(),this.getKeyDetails()}async catchupToLatestShare(e){const{shareStore:t,polyID:r,includeLocalMetadataTransitions:i}=e;let n;try{n=await this.getAuthMetadata({privKey:t.share.share,includeLocalMetadataTransitions:i})}catch(e){const t=e;if(t&&1308===t.code)throw t;const r=await(0,s.MQ)(t);throw P.A.authMetadataGetUnavailable(`, ${r.message}`)}try{if(r&&t.polynomialID===r)return{latestShare:t,shareMetadata:n};const e=await n.getEncryptedShare(t);return await this.catchupToLatestShare({shareStore:e,polyID:r,includeLocalMetadataTransitions:i})}catch(e){const r=e;if(r&&1308===r.code)throw r;return{latestShare:t,shareMetadata:n}}}async reconstructKey(e=!0){if(!this.metadata)throw P.A.metadataUndefined();const t=this.metadata.getLatestPublicPolynomial(),r=t.getThreshold(),n=t.getPolynomialID();let s=r;const o=this.metadata.getShareIndexesForPolynomial(n),a={};for(let e=0;e<o.length;e+=1)a[o[e]]=!0;const c=[];for(let e=this.metadata.polyIDList.length-1;e>=0&&s>0;e-=1){const t=this.shares[this.metadata.polyIDList[e][0]];if(t){const e=Object.keys(t);for(let r=0;r<e.length&&s>0;r+=1)if(e[r]in a){const i=t[e[r]];if(i.polynomialID===n)c.push(i);else{const e=await this.catchupToLatestShare({shareStore:i,polyID:n,includeLocalMetadataTransitions:!0});if(e.latestShare.polynomialID!==n)throw new P.A(1304,"Share found in unexpected polynomial");c.push(e.latestShare)}delete a[e[r]],s-=1}}}if(c.forEach((e=>{this.inputShareStore(e)})),s>0)throw P.A.unableToReconstruct(` require ${r} but have ${r-s}`);const h=Object.keys(this.shares[n]),u=[],f=[];for(let e=0;e<r;e+=1)u.push(this.shares[n][h[e]].share.share),f.push(this.shares[n][h[e]].share.shareIndex);const l=(0,M.Yi)(u,f),p=(0,d.X3)(l);if(0!==this.metadata.pubKey.x.cmp(p.x))throw P.A.incorrectReconstruction();this.secp256k1Key=l;const y={allKeys:[l]};if(e&&Object.keys(this._reconstructKeyMiddleware).length>0&&await Promise.all(Object.keys(this._reconstructKeyMiddleware).map((async e=>{if(Object.prototype.hasOwnProperty.call(this._reconstructKeyMiddleware,e)){const t=await this._reconstructKeyMiddleware[e]();y[e]=t,y.allKeys.push(...t)}}))),this.getEd25519PublicKey()){const e=await this.retrieveEd25519Seed();if(!e)throw P.A.default("Ed25519 seed not found");this._ed25519Seed=e}return(0,i.A)({secp256k1Key:l,ed25519Seed:this._ed25519Seed},y)}reconstructLatestPoly(){if(!this.metadata)throw P.A.metadataUndefined();const e=this.metadata.getLatestPublicPolynomial(),t=e.getPolynomialID(),r=e.getThreshold(),i=[],n=Object.keys(this.shares[t]);if(n.length<r)throw P.A.unableToReconstruct("not enough shares to reconstruct poly");if(new Set(n).size!==n.length)thro